- Как пользоваться GitHub на компьютере с Linux
- Установка git
- Синтаксис
- Создание проекта на локальном компьютере
- Отправка данных на GitHub
- Создание репозитория
- Заливаем проект в репозиторий на GitHub
- Получение файлов с GitHub
- Клонирование проекта
- Возможные ошибки
- 1. При попытке отправить данные на GitHub, получаем ошибку:
- Install github on linux server
- Get started with git and GitHub
- Setup your own private GitHub server using GitLab and Ubuntu Server 12.04 LTS
- Lets get going…
- Setting up MySQL
- Grabbing GitLab
- Time to install Nginx
- Having issues? 502 error(s)?
Как пользоваться GitHub на компьютере с Linux
GitHub — один из используемых сервисов размещения проектов для совместной разработки. Он поддерживает контроль версий, возможность отслеживания изменений кода, сравнение строк, а также он бесплатен.
В данной статье приведены примеры использования сервиса на компьютере под управлением операционных систем семейства Linux. Мы рассмотрим, как создать проект на локальном компьютере и залить его на сервис с помощью командной строки. Рассмотренные варианты использования git также можно применять на desktop системах, запустив окно терминала.
Установка git
Управление выполняется с помощью приложения git. Если его нет в системе, установку можно выполнить из репозитория.
Если используем CentOS / Red Hat:
yum install git-core
Если используем Ubuntu / Debian:
apt-get install git
Если мы хотим воспользоваться сервисом с компьютера Windows или Mac OS, необходимо скачать и установить desktop версию с официального сайта.
Синтаксис
Команды имеют следующий синтаксис:
* полный перечень опций, команд и аргументов можно получить командой man git.
Создание проекта на локальном компьютере
Прежде чем отправить проект на GitHub, создаем его на нашем компьютере. Для этого переходим в каталог с файлами проекта:
Инициализируем проект для git:
Мы получим ответ похожий на:
Initialized empty Git repository in /projects/.git/
Это означает, что репозиторий git создан.
Теперь добавим файлы в репозиторий:
* данной командой мы добавили папку и ее содержимое в репозиторий git.
Отправка данных на GitHub
Теперь можно отправить данные на сервис. Для этого у нас должна быть зарегистрированная учетная запись и создан репозиторий на GitHub.
Создание репозитория
Переходим на портал github.com и входим в систему или проходим несложную регистрацию:
Проходим процесс подтверждения, что мы не робот. Затем завершаем несколько шагов регистрации, нажимая Submit. В итоге мы получим письмо на адрес электронной почты, которую указали при регистрации. Необходимо будем подтвердить email, перейдя в письме по кнопке Verify email address.
Создаем репозиторий. Для этого кликаем по иконке профиля и переходим в раздел Your repositories:
И кликаем по кнопке New. В следующем окне даем название репозиторию и нажимаем Create repository:
Мы увидим страницу с путем к репозиторию:
Заливаем проект в репозиторий на GitHub
Добавляем комментарий к нашему проекту:
git commit -m «Очередное изменение проекта» -a
* где Очередное изменение проекта — произвольный комментарий; параметр -a указывает, что комментарий нужно применить ко всем измененным файлам.
Теперь подключаемся к созданному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
* где dmosktest — логин, который был указан при регистрации на github, а project1 — название, которое мы задали, когда создавали репозиторий.
* удалить удаленный репозиторий можно командой git remote rm origin.
Закидываем проект на GitHub:
git push origin master
* где master — ветка проекта (веток может быть несколько).
В нашем проекте на GitHub должны появиться файлы проекта:
Получение файлов с GitHub
Для загрузки на компьютер файлов, создаем каталог с проектом и переходим в него:
Проводим начальную настройку локального репозитория:
Подключаемся к удаленному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
Скачиваем проект командой:
git pull https://github.com/dmosktest/project1.git master
Клонирование проекта
Например, использую наш репозиторий:
git clone https://github.com/dmosktest/project1.git
* данная команда создаст в текущей папке каталог project1 и инициализирует его как локальный репозиторий git. Также загрузит файлы проекта.
Возможные ошибки
1. При попытке отправить данные на GitHub, получаем ошибку:
error: src refspec master does not match any.
error: failed to push some refs to ‘https://github.com/dmosktest/project1.git’
* где dmosktest/project1.git — путь к нашему репозиторию.
Причина: проект ни разу не был зафиксирован (закоммичен).
Решение: добавляем комментарий к нашему проекту:
Install github on linux server
How to install Git on any OS
Git can be installed on the most common operating systems like Windows, Mac, and Linux. In fact, Git comes installed by default on most Mac and Linux machines!
Checking for Git
To see if you already have Git installed, open up your terminal application.
- If you’re on a Mac, look for a command prompt application called «Terminal».
- If you’re on a Windows machine, open the windows command prompt or «Git Bash».
Once you’ve opened your terminal application, type git version . The output will either tell you which version of Git is installed, or it will alert you that git is an unknown command. If it’s an unknown command, read further and find out how to install Git.
Install Git Using GitHub Desktop
Installing GitHub Desktop will also install the latest version of Git if you don’t already have it. With GitHub Desktop, you get a command line version of Git with a robust GUI. Regardless of if you have Git installed or not, GitHub Desktop offers a simple collaboration tool for Git. You can learn more here.
Install Git on Windows
- Navigate to the latest Git for Windows installer and download the latest version.
- Once the installer has started, follow the instructions as provided in the Git Setup wizard screen until the installation is complete.
- Open the windows command prompt (or Git Bash if you selected not to use the standard Git Windows Command Prompt during the Git installation).
- Type git version to verify Git was installed.
Note: git-scm is a popular and recommended resource for downloading Git for Windows. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git included with the recommended command prompt, Git Bash . The download source is the same Git for Windows installer as referenced in the steps above.
Install Git on Mac
Most versions of MacOS will already have Git installed, and you can activate it through the terminal with git version . However, if you don’t have Git installed for whatever reason, you can install the latest version of Git using one of several popular methods as listed below:
Install Git From an Installer
- Navigate to the latest macOS Git Installer and download the latest version.
- Once the installer has started, follow the instructions as provided until the installation is complete.
- Open the command prompt «terminal» and type git version to verify Git was installed.
Note: git-scm is a popular and recommended resource for downloading Git on a Mac. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git. The download source is the same macOS Git Installer as referenced in the steps above.
Install Git from Homebrew
Homebrew is a popular package manager for macOS. If you already have Homwbrew installed, you can follow the below steps to install Git:
- Open up a terminal window and install Git using the following command: brew install git .
- Once the command output has completed, you can verify the installation by typing: git version .
Install Git on Linux
Fun fact: Git was originally developed to version the Linux operating system! So, it only makes sense that it is easy to configure to run on Linux.
You can install Git on Linux through the package management tool that comes with your distribution.
- Git packages are available using apt .
- It’s a good idea to make sure you’re running the latest version. To do so, Navigate to your command prompt shell and run the following command to make sure everything is up-to-date: sudo apt-get update .
- To install Git, run the following command: sudo apt-get install git-all .
- Once the command output has completed, you can verify the installation by typing: git version .
- Git packages are available using dnf .
- To install Git, navigate to your command prompt shell and run the following command: sudo dnf install git-all .
- Once the command output has completed, you can verify the installation by typing: git version .
Note: You can download the proper Git versions and read more about how to install on specific Linux systems, like installing Git on Ubuntu or Fedora, in git-scm’s documentation.
Other Methods of Installing Git
Looking to install Git via the source code? Learn more here.
Get started with git and GitHub
Review code, manage projects, and build software alongside 40 million developers.
Setup your own private GitHub server using GitLab and Ubuntu Server 12.04 LTS
By ballen
Post date
I’m the first to admit that I absolutely love writing code and applications, I’m also a huge fan of GitHub, GitHub is a fantastic tool for hosting and collaborating on public projects such as open-source projects however and although you can pay to enable you to host private Git repositories on GitHub if you have more than a few you’ll soon start paying big bucks!
Recently I found a fantastic ‘clone’ of GitHub, it’s called GitLab and pretty much has all the features that GitHub does and like GitHub, GitLab is written in Ruby (on Rails).
In this blog post, I will demonstrate how to configure you’re own GitLab server specifically on Ubuntu Server 12.04 LTS – for those that follow my blog posts quite closely you’ll not doubt of realised by now that I do love Ubuntu Server (I prefer the debian based distros over the likes of the RedHat derivatives!)
So, this is a little longer than most of my other blog posts on here so I hope you can keep up as we delve into getting the raft of dependencies installed and everything up and running!
Lets get going…
From the console of your server we need to download and install some initial packages, execute the following commands:
Next, by default Ubuntu 12.04 LTS comes bundled with Ruby 1.8 we need to replace this with Ruby 2.0, so lets remove the old version and then we’ll build the version 2.0 from source… (this bit can take some time, you might want to consider running the rest of the installation in a screen session incase you get an SSH idle connection timeout!)
Now, lets confirm that we are now running version 2.0 of Ruby:
We will now create a git user for GitLab to use, lets add the new system account like so:
Next, as we will be installing our RoR dependencies using Bundler, we’ll download the Bundler Gem like so:
Ok, so that was the first bit out of the way, now lets move on to installing GitLab Shell, we’ll download GitLab Shell with the following commands:-
At the time of writing, the version of GitLab Shell was v1.8.0, you may want to replace the branch version above with the latest as per the branches found here: https://github.com/gitlabhq/gitlab-shell/releases
Now that we have GitLab Shell installed on the server, we should now edit the config.yml file and set the ‘gitlab_url’ property so that it points to our server, so using Nano we’ll edit and update the file:
Update this line to reflect your server’s FQDN:
Now we finalise the installation of GitLab shell but running the installer:
Setting up MySQL
It is now time to prepare the MySQL database, you can also use Postgres if you wish but I will not be covering that in this post.
So, lets install the MySQL server and client libraries (when prompted for the MySQL root password be sure to remember it as you will need to use it shortly!):
We will now create a dedicated MySQL user and create a database for GitLab, so lets now login to MySQL like so:
and now execute the following queries, be sure to change the ‘YOUR_PASSWORD_HERE’ string for your own random password, this will be used by the dedicated GitLab DB account.
Fantastic! – Now lets just make sure that you can login as expected to MySQL using the new ‘gitlab’ account:
If all went well, you should be able to execute ‘show databases;‘ command at the MySQL prompt you should see the gitlabhq_production database in the list!
Grabbing GitLab
We’ve now got everything prepared so we can now start the actual installation of the GitLab application!
So lets now clone GitLab and switch to the latest ‘stable’ branch:
Like with GitLab Shell, at the time of writing the latest stable release is 6.4, so hence why the above code checked out ‘6-4-stable’ you should change this to the latest if you prefer!
Again, we have some more editing to do in the GitLab configuration file, like before we need to set the server’s FQDN, lets open the file first:-
Now lets find the section below and update it accordingly, basically you should be replacing ‘localhost‘ with your server’s FQDN, for example ‘gitlab.mydomain.com‘, this should match the same FQDN that we set up earlier in the GitLab Shell config.yml file…
Ok, now we are going to set some directory permissions and configure the ‘git’ user’s Git configuration; simple stuff just copy and execute the following commands on your server…
We now need to configure the database connection file with our MySQL user account details we created earlier…
By default, the file looks like as follows, update the ‘production‘ section to match your database username and password that we configured earlier, you should only need to change the username and password…
Now that we’ve set that up, lets secure the file but setting some more restrictive file permissions:
Ok, we are now ready to start the GitLab application install (don’t panic when you see ‘postgres’ in the command below, notice the operator actually says ‘–without’ so this is 100% correct! :D)…
After that is complete, lets run this command, and type ‘yes’ when prompted:
After the above command completes, you will be shown the default administrator credentials, it should look like this:
Lets now configure GitLab to start automatically whenever the server is booted, to do this execute the following commands:
Lets keep the log files in check, lets enable logrotate:-
Lets now check that everything installed ok on the server and we are not getting any error messages that we should be concerned about:-
We can now start GitLab and hopefully all will work without any issues:
Lets compile the assets:
….this should speed up the initial loading time!
Time to install Nginx
Ok, GitLab is now running but we now need to install a web server, my personal favorite for speed and stability is Nginx, so that is what I will be installing…
We now need to edit the Nginx gitlab configuration file to set the server’s FQDN and again, this should match the ones we added to both ‘GitLab Shell’ and GitLab’s config.yml files earlier, so:
and now restart Nginx like so:
I’m sure you’ll be over the moon to hear that we are finished.
Having issues? 502 error(s)?
First of all, its a good idea to run this command to ensure that everything that should be ok, is ok…
I actually found that on my installation, it was complaining that the version of git was out of date, this didn’t really matter too much so I just left it!
I found that the first time I tried accessing GitLab after installation, the CPU and memory was battered by ‘unicorn_rails’ process, to get around this I updated the ‘timeout’ value in the /home/git/gitlab/config/unicorn.rb file to ‘300’ and then restarted both Nginx and GitLab, once complete I tried accessing GitLab once again, it took a while but after it was complete it loaded and all was good! – See more infomation about this issue here: https://groups.google.com/forum/#!topic/gitlabhq/u9AMESyd-N0
I found that after installation whenver I tried to connect to my server, I was being thrown a 502 error by Nginx, I did some digging around on Google and found that to resolve the issue I had to add my servers FQDN to the /etc/hosts file on the 127.0.0.1 line!
So if you have the same issue, change the two lines in /etc/hosts from:
and restart nginx and GitLab and you should then be good to go!
If you are having other issues, it is well worth knowing where the log files are so that you can view them and get clues as to what may be causing the issue, I’d recommend checking the following log files for errors:-