Git — это система контроля версий с открытым исходным кодом, которая отслеживает изменения в вашем программном обеспечении на уровне исходного кода. Она используется тысячами разработчиков по всему миру для отслеживания и управления изменениями кода, возврата к предыдущим этапам и создания альтернативных версий файлов и каталогов.
HTTP Git Server — это проект с открытым исходным кодом, который позволяет пользователям совместно использовать репозитории Git через локальную сеть (LAN). Он очень прост, легко настраивается и помогает разработчикам управлять им из интерфейса командной строки.
В этом руководстве мы расскажем о настройке HTTP-сервера Git-репозитория с помощью Nginx на Ubuntu 22.04.
Предварительные условия
- Сервер под управлением Ubuntu 22.04.
- На IP-адрес вашего сервера указывает действительное доменное имя.
- На вашем сервере настроен пароль root.
Установка веб-сервера Nginx
В этом посте мы будем использовать сервер Nginx для обслуживания репозитория Git, поэтому вам нужно будет установить веб-сервер Nginx и другие необходимые пакеты на ваш сервер. Вы можете установить их с помощью следующей команды:
apt-get install nginx git fcgiwrap apache2-utils unzip -y
После установки всех пакетов можно приступать к созданию Git-репозитория.
Создание Git-репозитория
Сначала создайте каталог для хранения Git-репозитория в корневой части сайта Nginx:
mkdir /var/www/html/gitrepo
Далее перейдите в каталог gitrepo и создайте еще один каталог для пользователя:
cd /var/www/html/gitrepo mkdir hitesh.git
Затем перейдите в каталог пользователя и инициализируйте Git-репозиторий с помощью следующей команды:
cd hitesh.git git --bare init
Вы получите следующий результат:
Initialized empty Git repository in /var/www/html/gitrepo/hitesh.git/
Далее обновите информацию о Git-сервере с помощью следующей команды:
git update-server-info
Затем измените права собственности на gitrepo и установите соответствующие разрешения с помощью следующей команды:
chown -R www-data:www-data /var/www/html/gitrepo chmod -R 755 /var/www/html/gitrepo
Затем создайте пользователя hitesh и установите пароль:
htpasswd -c /var/www/html/gitrepo/htpasswd hitesh
Вы можете установить пароль, как показано ниже:
New password: Re-type new password: Adding password for user hitesh
Проверить пароль можно с помощью следующей команды:
cat /var/www/html/gitrepo/htpasswd
Пример вывода:
hitesh:$vcr2$AdyCEkaA$Fsq5nDbLhBDdafCQGBUsr2
Настройка Nginx для обслуживания репозитория Git
Далее создайте файл конфигурации виртуального хоста Nginx для обслуживания репозитория Git через интернет.
nano /etc/nginx/conf.d/gitrepo.conf
Добавьте следующие конфигурации:
server {
listen 80;
root /var/www/html/gitrepo;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name git.example.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
location ~ (/.*) {
client_max_body_size 0;
auth_basic "Git Login";
auth_basic_user_file "/var/www/html/gitrepo/htpasswd";
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend;
fastcgi_param GIT_HTTP_EXPORT_ALL "";
fastcgi_param GIT_PROJECT_ROOT /var/www/html/gitrepo;
fastcgi_param REMOTE_USER $remote_user;
fastcgi_param PATH_INFO $1;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
}
}
Сохраните и закройте файл, когда закончите, затем проверьте Nginx на наличие синтаксических ошибок с помощью следующей команды:
nginx -t
Вы получите следующий результат:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Наконец, перезапустите службу Nginx, чтобы применить изменения:
systemctl restart nginx
Вы также можете проверить состояние Nginx с помощью следующей команды:
systemctl status nginx
Вы получите следующий результат:
? nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2022-11-05 08:00:04 UTC; 2s ago
Docs: man:nginx(8)
Process: 144985 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 144986 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 144987 (nginx)
Tasks: 2 (limit: 2341)
Memory: 2.5M
CPU: 42ms
CGroup: /system.slice/nginx.service
??144987 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
??144988 nginx: worker process
Nove 5 08:00:04 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Nove 5 08:00:04 ubuntu2204 systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Nove 5 08:00:04 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.
Защита HTTP-сервера Git с помощью Let’s Encrypt
Перед началом работы вам нужно установить в системе клиент Certbot для установки и управления SSL Let’s Encrypt. Вы можете установить его с помощью следующей команды:
apt-get install certbot python3-certbot-nginx -y
После установки клиента Certbot выполните следующую команду, чтобы загрузить и установить Let’s Encrypt SSL для вашего сайта:
certbot --nginx -d git.example.com
Укажите свой адрес электронной почты и примите условия предоставления услуг, как показано ниже:
Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): [email protected] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must agree in order to register with the ACME server at https://acme-v02.api.letsencrypt.org/directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (A)gree/(C)ancel: A - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing to share your email address with the Electronic Frontier Foundation, a founding partner of the Let's Encrypt project and the non-profit organization that develops Certbot? We'd like to send you email about our work encrypting the web, EFF news, campaigns, and ways to support digital freedom. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: Y Obtaining a new certificate Performing the following challenges: http-01 challenge for git.example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/git.conf
Выберите, нужно ли перенаправлять HTTP-трафик на HTTPS:
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Введите 2 и нажмите Enter, чтобы запустить процесс. После завершения установки вы должны увидеть следующий результат:
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/git.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://git.example.com You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=git.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/git.example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/git.example.com/privkey.pem Your cert will expire on 2023-02-06. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le
На данный момент ваш HTTP-сервер Git защищен с помощью Let’s Encrypt SSL.
Подключение к репозиторию Git с клиента
На данный момент HTTP-сервер Git настроен с помощью Nginx и Let’s Encrypt SSL. Теперь пришло время подключиться к нему с клиентской машины и протестировать его.
Сначала установите пакет Git на клиентской машине с помощью следующей команды:
apt-get install git -y
Затем создайте каталог для вашего проекта с помощью следующей команды:
mkdir project
Затем перейдите в каталог проекта и инициализируйте Git с помощью следующей команды:
cd project git init
Далее настройте Git, используя свою электронную почту и имя пользователя:
git config --global user.email "[email protected]" git config --global user.name "hitesh"
Затем добавьте свой HTTP-сервер Git с помощью следующей команды:
git remote add origin https://[email protected]/hitesh.git
Далее создайте каталог data и добавьте в него файл:
mkdir data echo "This is my first application" > data/app
Затем добавьте созданный каталог и файл в Git-репозиторий:
git add .
Затем зафиксируйте изменения с помощью следующей команды:
git commit -a -m "Add files and directories"
Вы получите следующий результат:
[master (root-commit) 0299d83] Add files and directories 1 file changed, 1 insertion(+) create mode 100644 data/app
Далее загрузите файл и каталог на HTTP Git-сервер с помощью следующей команды:
git push origin master
Вам будет предложено ввести пароль для доступа к Git-серверу:
Password for 'https://[email protected]':
После подключения вы получите следующий результат:
Counting objects: 4, done. Writing objects: 100% (4/4), 281 bytes | 281.00 KiB/s, done. Total 4 (delta 0), reused 0 (delta 0) To https://git.example.com/hitesh.git * [new branch] master -> master
Вы также можете загрузить свой репозиторий с Git-сервера напрямую, используя следующую команду:
git clone https://[email protected]/hitesh.git
Вы получите следующий результат:
Cloning into 'hitesh'... Password for 'https://[email protected]': remote: Enumerating objects: 4, done. remote: Counting objects: 100% (4/4), done. remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (4/4), done.
Заключение
Поздравляем! Вы успешно настроили HTTP-сервер Git с Nginx на Ubuntu 22.04. Теперь с помощью командной строки вы можете использовать HTTP-сервер Git в своей локальной среде разработки для управления и отслеживания проекта.