Установка GitLab CE за прокси Nginx | Блог NetPoint

Установка GitLab CE за прокси Nginx | Блог NetPoint Сертификаты
Содержание
  1. Introduction
  2. Add a custom domain to Pages
  3. Get the verification code
  4. Set up DNS records for Pages
  5. Verify the domain’s ownership
  6. Adding an ssl/tls certificate to pages
  7. Adding more domain aliases
  8. Additional troubleshooting
  9. Automatic let’s encrypt renewal
  10. Available ssl configuration tasks
  11. Common ssl errors
  12. Custom certificates missing or skipped
  13. Custom certificates not detected
  14. Details on how gitlab and ssl work
  15. Edit the gitlab configuration
  16. Gitlab components
  17. Git-lfs and other embedded services written in golang report custom certificate signed by unknown authority
  18. Install custom public certificates
  19. Let’s encrypt certificate signed by unknown authority
  20. Let’s encrypt fails on reconfigure
  21. Manual addition of ssl/tls certificates
  22. Manual let’s encrypt renewal
  23. Other certificate authorities
  24. Reconfigure fails due to certificates
  25. Reconfigure gitlab to enable ssl
  26. Set up pages with a custom domain
  27. Ssl_connect wrong version number
  28. Status: deprecated
  29. Troubleshooting pages domain verification
  30. Useful openssl debugging commands
  31. Using gitlab runner with a gitlab instance configured with internal ca certificate or self-signed certificate
  32. Добавление ssh ключа
  33. Лимиты по созданию проектов (ограничение)
  34. Настройка nginx
  35. Настройка профиля
  36. Ограничение или блокировка открытой регистрации
  37. Ограничение регистрации по домену
  38. Подготовка к установке gitlab
  39. Системные требования
  40. Установка gitlab ce
  41. Установка и настройка gitlab на ubuntu 18.04 | записки системного администратора
  42. Установка сервера nginx с сертификатом let’s encrypt

Introduction

GitLab, specifically GitLab CE (Community Edition), is an open source application primarily used to host Git repositories, with additional development-related features like issue tracking. The GitLab project makes it relatively straight forward to set up a GitLab instance on your own hardware with an easy installation mechanism.

Add a custom domain to Pages

Navigate to your project’s Setting > Pages and click New domain
to add your custom domain to GitLab Pages. You can choose whether to:

Click Create New Domain.

Get the verification code

After you add a new domain to Pages, the verification code prompts you. Copy the values from GitLab
and paste them in your domain’s control panel as a TXT record on the next step.

Set up DNS records for Pages

Read this document for an overview of DNS records for Pages.
If you’re familiar with the subject, follow the instructions below
according to the type of domain you want to use with your Pages site:

Verify the domain’s ownership

Once you have added all the DNS records:

  1. Go back at your project’s Settings > Pages.
  2. Locate your domain name and click Details.
  3. Click the Retry verification button to activate your new domain.

As soon as your domain becomes active, your website is available through your domain name.

WARNING:
Considering GitLab instances with domain verification enabled,
if the domain can’t be verified for 7 days, it’s removed
from the GitLab project.

Notes:

Adding an ssl/tls certificate to pages

Read this document for an overview on SSL/TLS certification.

To secure your custom domain with GitLab Pages you can opt by:

Adding more domain aliases

You can add more than one alias (custom domains and subdomains) to the same project.
An alias can be understood as having many doors leading to the same room.

All the aliases you’ve set to your site are listed on Setting > Pages.
From that page, you can view, add, and remove them.

Additional troubleshooting

For additional troubleshooting steps, see Troubleshooting SSL.

Automatic let’s encrypt renewal

Introduced in GitLab 10.7.

Available ssl configuration tasks

Omnibus-GitLab supports several common use cases for SSL configuration.

Common ssl errors

  1. SSL certificate problem: unable to get local issuer certificate

    This error indicates the client cannot get the root CA. To fix this, you can either trust the root CA of the server you are trying to connect to on the client or modify the certificate to present the full chained certificate on the server you are trying to connect to.

    NOTE:
    It is recommended to use the full certificate chain in order to prevent SSL errors when clients connect. The full certificate chain order should consist of the server certificate first, followed by all intermediate certificates, with the root CA last.

  2. unable to verify the first certificate

    This error indicates that an incomplete certificate chain is being presented by the server. To fix this error, you will need to replace server’s certificate with the full chained certificate. The full certificate chain order should consist of the server certificate first, followed by all intermediate certificates, with the root CA last.

  3. certificate signed by unknown authority

    This error indicates that the client does not trust the certificate or CA. To fix this error, the client connecting to server will need to trust the certificate or CA.

  4. SSL certificate problem: self signed certificate in certificate chain

    This error indicates that the client does not trust the certificate or CA. To fix this error, the client connecting to server will need to trust the certificate or CA.

Custom certificates missing or skipped

GitLab versions 8.9.0, 8.9.1, and 8.9.2 all mistakenly used the
/etc/gitlab/ssl/trusted-certs/ directory. This directory is safe to remove if it
is empty. If it still contains custom certificates then move them to /etc/gitlab/trusted-certs/
and run gitlab-ctl reconfigure.

If no symlinks are created in /opt/gitlab/embedded/ssl/certs/ and you see
the message “Skipping cert.pem” after running gitlab-ctl reconfigure, that
means there may be one of four issues:

  1. The file in /etc/gitlab/trusted-certs/ is a symlink
  2. The file is not a valid PEM or DER-encoded certificate
  3. Perl is not installed on the operating system which is needed for c_rehash to properly symlink certificates.
  4. The certificate contains the string TRUSTED

Test the certificate’s validity using the commands below:

/opt/gitlab/embedded/bin/openssl x509 -in /etc/gitlab/trusted-certs/example.pem -text -noout
/opt/gitlab/embedded/bin/openssl x509 -inform DER -in /etc/gitlab/trusted-certs/example.der -text -noout

Invalid certificate files produce the following output:

unable to load certificate
140663131141784:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: TRUSTED CERTIFICATE

To test if c_rehash is not symlinking the certificate due to a missing perl interpreter:

$ /opt/gitlab/embedded/bin/c_rehash /etc/gitlab/trusted-certs

bash: /opt/gitlab/embedded/bin/c_rehash: /usr/bin/perl: bad interpreter: No such file or directory

If you see this message, you will need to install perl with your distribution’s package manager.

Про сертификаты:  Обновление цифрового сертификата безопасности для сервисов «1С»

If you inspect the certificate itself, then look for the string TRUSTED:

-----BEGIN TRUSTED CERTIFICATE-----
...
-----END TRUSTED CERTIFICATE-----

If it does, like the example above, then try removing the string TRUSTED and running gitlab-ctl reconfigure again.

Custom certificates not detected

If after running gitlab-ctl reconfigure:

  1. no symlinks are created in /opt/gitlab/embedded/ssl/certs/;
  2. you have placed custom certificates in /etc/gitlab/trusted-certs/; and
  3. you do not see any skipped or symlinked custom certificate messages

You may be encountering an issue where Omnibus GitLab thinks that the custom
certificates have already been added.

To resolve, delete the trusted certificates directory hash:

rm /var/opt/gitlab/trusted-certs-directory-hash

Then run gitlab-ctl reconfigure again. The reconfigure should now detect and symlink
your custom certificates.

Details on how gitlab and ssl work

GitLab-Omnibus includes its own library of OpenSSL and links all compiled
programs (e.g. Ruby, PostgreSQL, etc.) against this library. This library is
compiled to look for certificates in /opt/gitlab/embedded/ssl/certs.

GitLab-Omnibus manages custom certificates by symlinking any certificate that
gets added to /etc/gitlab/trusted-certs/ to /opt/gitlab/embedded/ssl/certs
using the c_rehash
tool. For example, let’s suppose we add customcacert.pem to
/etc/gitlab/trusted-certs/:

Here we see the fingerprint of the certificate is 7f279c95, which links to
the custom certificate.

Edit the gitlab configuration

Start by opening up the GitLab configuration file again:

Gitlab components

Introduced in GitLab 11.0.

Follow the steps to enable basic Let’s Encrypt integration and
modify /etc/gitlab/gitlab.rb with any of the following that apply:

Git-lfs and other embedded services written in golang report custom certificate signed by unknown authority

NOTE:
In GitLab 11.5, the following workaround is no longer necessary, embedded golang apps now use the standard GitLab certificate directory automatically.

The gitlab-workhorse and other services written in golang use the crypto/tls library from golang
instead of OpenSSL.

Add the following entry in /etc/gitlab/gitlab.rb to work around the
issue as reported:

NOTE:
If you have installed GitLab to a path other than /opt/gitlab/ then modify the entry above
with the correct path in your operating environment.

Install custom public certificates

NOTE:
A perl interpreter is required for c_rehash dependency to properly symlink the certificates.
Perl is currently not bundled in Omnibus GitLab.

Let’s encrypt certificate signed by unknown authority

The initial implementation of Let’s Encrypt integration only used the certificate, not the full certificate chain.

Starting in 10.5.4, the full certificate chain will be used. For installs which are already using a certificate, the switchover will not happen until the renewal logic indicates the certificate is near expiration. To force it sooner, run the following

Where HOSTNAME is the hostname of the certificate.

Let’s encrypt fails on reconfigure

When you reconfigure, there are common scenarios under which Let’s Encrypt may fail:

Manual addition of ssl/tls certificates

You can use any certificate satisfying the following requirements:

For example, Cloudflare certificates
meet these requirements.

Manual let’s encrypt renewal

Renew Let’s Encrypt certificates manually using one of the following commands:

sudo gitlab-ctl reconfigure
sudo gitlab-ctl renew-le-certs

WARNING:
GitLab 12.1 or later will attempt to renew any Let’s Encrypt certificate.
If you plan to use your own Let’s Encrypt certificate you must set letsencrypt[‘enable’] = false
in /etc/gitlab/gitlab.rb to disable integration. Otherwise the certificate
could be overwritten due to the renewal.

NOTE:
The above commands require root privileges and only generate a renewal if the certificate is close to expiration.
Consider the upstream rate limits if encountering an error during renewal.

Other certificate authorities

Omnibus GitLab supports connections to external services with
self-signed certificates.

NOTE:
Custom certificates were introduced in GitLab 8.9.

Reconfigure fails due to certificates

ERROR: Not a certificate: /opt/gitlab/embedded/ssl/certs/FILE. Move it from /opt/gitlab/embedded/ssl/certs to a different location and reconfigure again.

Check /opt/gitlab/embedded/ssl/certs and remove any files other than README.md that aren’t valid X.509 certificates.

NOTE:
Running gitlab-ctl reconfigure constructs symlinks named from the subject hashes
of your custom public certificates and places them in /opt/gitlab/embedded/ssl/certs/.
Broken symlinks in /opt/gitlab/embedded/ssl/certs/ will be automatically removed.

Reconfigure gitlab to enable ssl

Now, reconfigure GitLab again to implement your changes:

Set up pages with a custom domain

To set up Pages with a custom domain name, read the requirements
and steps below.

Ssl_connect wrong version number

A misconfiguration may result in:

Status: deprecated

This article covers an older method of configuring GitLab with Let’s Encrypt manually. As of GitLab version 10.5, Let’s Encrypt support is available natively within Gitlab.

Our guide on How To Install and Configure GitLab on Ubuntu 16.04 has been updated to include the relevant configuration settings within GitLab. We recommend referring to that guide moving forward.

Troubleshooting pages domain verification

To manually verify that you have properly configured the domain verification
TXT DNS entry, you can run the following command in your terminal:

dig _gitlab-pages-verification-code.<YOUR-PAGES-DOMAIN> TXT

Expect the output:

;; ANSWER SECTION:_gitlab-pages-verification-code.<YOUR-PAGES-DOMAIN>. 300 IN TXT "gitlab-pages-verification-code=<YOUR-VERIFICATION-CODE>"

In some cases it can help to add the verification code with the same domain name as you are trying to register.

Про сертификаты:  Как скопировать или перенести сертификаты КриптоПро (CryptoPro)

For a root domain:

For a subdomain:

Useful openssl debugging commands

Sometimes it’s helpful to get a better picture of the SSL certificate chain by viewing it directly
at the source. These commands are part of the standard OpenSSL library of tools for diagnostics and
debugging.

NOTE:
GitLab includes its own custom-compiled version of OpenSSL
that all GitLab libraries are linked against. It’s important to run the following commands using
this OpenSSL version.

Using gitlab runner with a gitlab instance configured with internal ca certificate or self-signed certificate

Besides getting the errors mentioned in
Using an internal CA certificate with GitLab,
your CI pipelines may get stuck in Pending status. In the runner logs you may
see the following error message:

Добавление ssh ключа

Для работы с Git и GitLab можно указать публичный SSH ключ, чтобы не приходилось каждый раз вводить пароль вашей учетной записи.

Введите команду (если у вас уже существует ключ):

cat ~/.ssh/id_rsa.pub

Команда вернет следующий результат:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC5onOVtATUjVkqk91lq v0g5TzOZTMBp4avWLEZO/97jQa1PL7y4zx4iOmUDOdlux/gC QSW0knti/yJrtzPJibDOedRJ9KkPPGpyD1JPqRGiy3eEY2gs755McfopX6U99aYjUVBgtcfX5AXp1 5Dd9jJEFhhEDDD/WEVfYERP1ZjybaRWy6vykkPa5W2YloXRIJq/kJk9ubtd5iGnRJfDZrkza2Q97ruNGWbeEty4rgDVNwb/Znz84qt9DzzI9rvlZTfB/9EApmB0Y7eu6vR3AG5T3gBZIAYGdurdqbIj/dI8nUduE9AImzlGxeACKs0iOi/037u5gvB gitlab@netpoint-dc.ml

Это пример ключа. У вас будут свои данные

Скопируйте публичный ключ полностью, перейдите в настройки профиля и нажмите на ссылку «SSH Keys» слева. Вставьте ключ в большое поле и напишите его название в поле Title. Для сохранения (добавления) ключа нажмите на кнопку «Add key».

Если публичного ключа у вас нет, вы получите примерно следующий ответ от команды:

 cat: /home/gitlab/.ssh/id_rsa.pub:  No such file or directory 

Для генерации связки приватного и публичного ключа введите команду:

ssh-keygen -t rsa

У вас должно получиться примерно следующее:

На все вопросы в процессе генерации можно нажимать клавишу «Enter» или ввести подходящую вам директорию.

Снова введите команду для просмотра содержимого публичного ключа

cat ~/.ssh/id_rsa.pub

Скопируйте ключ и введите его в свойствах профиля.

Лимиты по созданию проектов (ограничение)

По умолчанию в GitLab любой пользователь может создать 100000 проектов. Откройте раздел «Account and limit» и измените значение в строке «Default projects limit» на 0 , нажмите на кнопку «Save changes». Значение «0» необходимо, когда нужно запретить пользователям создание проектов.

Настройка nginx

Откройте ваш конфигурационный файл

CentOSnano /etc/nginx/conf.d/${WEBSITE_NAME}.conf

Debian/Ubuntunano /etc/nginx/sites-available/$WEBSITE_NAME

Настройка профиля

После авторизации нажмите на профиль левой кнопкой мыши в правом верхнем углу и нажмите на пункт «Profile».

Нажмите на кнопку «Edit profile» справа вверху.

Введите ваши данные (email, контакты, имя пользователя, аватар) и нажмите на кнопку «Update profile settings» , чтобы сохранить данные.

Ограничение или блокировка открытой регистрации

На данный момент любой человек может зарегистрироваться в вашем проекте и участвовать в разработке. Вы можете ограничить доступ к проекту или отключить регистрацию совсем.

Нажмите на значок гаечного ключа сверху.

В разделе администратора нажмите на ссылку «Settings» слева

Вас могут заинтересовать следующие категории

В разделе «Sign-up restrictions» уберите отметку с пункта «Sign-up enabled» и сохраните изменения, чтобы убрать возможность регистрации.

Ограничение регистрации по домену

GitLab поддерживает ограничение по домену почты. Установите отметку в пункте » Send confirmation email on sign-up», введите доверенный домен в поле «Whitelisted domains for sign-ups» и нажмите на кнопку «Save changes», чтобы сохранить изменения.

Подготовка к установке gitlab

Обновите индекс пакетов командой:

Debian/Ubuntu

apt-get update

CentOS

yum update

Выполните установку дополнительных компонентов:

Debian/Ubuntu

apt-get install ca-certificates curl postfix 

CentOS

yum install curl policycoreutils postfix

Во время установки будет открыто диалоговое окно для настройки MTA Postfix (почтового сервера). Выберите пункт «Интернет-сайт».

В следующем окне введите реально существующее доменное имя. Доменное имя будет использоваться для отправки с него писем.

Вы можете ввести IP адрес сервера вместо доменного имени, но в таком случае доставка писем на внешние почтовые серверы не гарантируется.

Системные требования

Рекомендуется использовать не менее 8 ГБ оперативной памяти и процессор не менее 2-ух ядер. Более подробно о системных требованиях можно прочитать в документации GitLab.

GitLab может быть установлен в следующих дистрибутивах Linux:

  • Ubuntu;
  • Debian;
  • CentOS;
  • openSUSE;
  • Red Hat Enterprise Linux (CentOS);
  • Scientific Linux (CentOS);
  • Oracle Linux (CentOS).

После установки операционной системы подключитесь к ней по SSH для выполнения действий на сервере, где будет работать GitLab CE.

Установка gitlab ce

Процесс установки занимает не так много времени. Воспользуйтесь скриптом для подготовки рабочей среды под GitLab. Будут установлены дополнительные программы и настроено подключение к репозиторию GitLab CE.

Выполните следующую команду для скачивания и выполнения скрипта:

Debian/Ubuntu

Установка и настройка gitlab на ubuntu 18.04 | записки системного администратора

Выполним установку и настройку Gitlab Community Edition через установку Omnibus-пакета

1. Установка зависимостей для Gitlab-пакета с предварительным обновлением локального кеша пакетов

2. Добавление Gitlab репозитария, из которого будет установлен пакет Gitlab Community Edition

3. Установка Gitlab

4. Настройка домен/урл по которому будет доступен Gitlab снаружи
Если не используется SSL, тогда указываем протокол http в параметре
external_url в файле /etc/gitlab/gitlab.rb

Для фактического применения сделанных настроек необходимо выполнить команду:

5. Настройка Gitlab на работу с SSL

Получение бесплатного Let’sEncrypt-сертификата

Gitlab поддерживает два способа работы с SSL:

1.Автоматическое генерирование самим Gitlab-ом сертификатов Let’sEncrypt(c их поселедующим ручным (с помощью команды gitlab-ctl renew-le-certs) или автоматическим обновлением)
https://my-sertif.ru/omnibus/settings/ssl.html#lets-encrypt-integration

2.Ручная настройка HTTPS со своими собственными сертификатами
https://my-sertif.ru/omnibus/settings/nginx.html#manually-configuring-https

Будем использовать второй способ, в котором получим бесплатный Let’sEncrypt-сертификат и установим автообновление этого сертификата

Сгенерируем Диффи-Хелмана ключ

Про сертификаты:  Где взять экипаж для Брига из Эферии: гайд в Black Desert

Настройка Gitlab на поддержку SSL

https://my-sertif.ru/omnibus/settings/ssl.html
https://my-sertif.ru/omnibus/settings/nginx.html#manually-configuring-https

Протокол изменяем с http на https

Включаем принудительный редирект http->https

Указываем пути к сертификату, приватному ключу и к ключу Дифи-Хелмана

Обязательно отключаем поддержку letsencrypt, встроенную в Gitlab
Чтобы при выполнении команды gitlab-ctl reconfigure
Gitlab не пытался самостоятельно обновить сертификаты Let’sEncrypt и тем самым перезаписать уже действующие сертификаты

Перенастраиваем/переконфигурируем Gitlab после внесений изменений в файл /etc/gitlab/gitlab.rb

Настройка автообновления Let’sEncrypt-сертификата с последующим перечитыванием nginx-ом своей конфигурации и нового сертификата/ключа
https://my-sertif.ru/omnibus/settings/nginx.html#update-the-ssl-certificates

Для получение сертификата добавляем в cron-скрипт для запуска каждые 2 месяца, который

6. Базовая настройка Gitlab после его установки

Установка пароля:
Логинимся в Gitlab (предварительно в WEB-интерфейсе устанавливаем пароль)

Отключение авторегистрации:

Указание корректного Email-адреса:

Изменение дефолтного имени пользователя с админискими правми с root на свое имя:

Настройка Gitlab Shell на нестандартный порт SSH(если SSH-сервер запущен не на стандартном порту)

Настройка SMTP-сервера
В качестве SMTP-сервера используем локально запущеннный postfix без поддержки SSL, слушающий запросы на localhost

Перенастраиваем/переконфигурируем Gitlab после внесений изменений в файл /etc/gitlab/gitlab.rb

Тестирование SMTP-кнфигурации путем отправки тестового сообщения из консоли Gitlab
https://my-sertif.ru/omnibus/settings/smtp.html#testing-the-smtp-configuration

Заходим в Gitlab консоль

Выполняем команду по отправке тестового сообщения

Если необходимо отключить отправку всех типов сообщений
https://my-sertif.ru/omnibus/settings/smtp.html#disable-all-outgoing-email

Отключение неиспользуемых сервисов
Отключение Prometheus (который включен по умолчанию)

Отключение Grafana

При отключении сервиса Prometheus fвтоматически также будут отключены такие сервисы,которые использует prometheus

Применяем настройки

Проверяем отсутствие запущенных Prometheus и Grafana-сервисов


Настройка Nginx статусной страницы

Конфигурация, которая создается после изменений в файле /etc/gitlab/gitlab.rb
и выполнению команды для применения изменений (gitlab-ctl reconfigure)

Error-логи Nginx

Все конфигурационные файлы/файлы виртуальных хостов/статусной страницы и т.д. для Nginx распологаются в каталоге /var/opt/gitlab/nginx/conf:

Настройка ротации логов

https://my-sertif.ru/omnibus/settings/logs.html

GitLab включает расширенную систему журналов, в которой все службы и компоненты GitLab будут записывать в системные логи

Дефолтное месторасположение логов всех сервисов/компонентов доступно по команде:

Runit-управляемые сервисы генерируют логи испольхуя svlogd
Ротацию логов таких сервисов настраиваем через параметры

Например, настроим ротацию с такой логикой
Ротировать только по времени(раз в сутки), ротация по размеру отключена
Хранить 7 ротированных файлов, при ротации сжимать старый лог-файл

Logrotate-сервис,который встроен в Gitlab управляет всеми логами кроме логов для Runit-управляемых сервисов
Аналогично, как и для логов runit-сервисов, настроим ротацию всех остальных
логов средствами встроенного в Gitlab logrotate-сервиса, а именно:
Ежесуточная ротация по времени(не по рамзмеру), с хранением 7 посоледних ротированных копий/лог-файлов, с сжатием ротированных файлов

Применяем сделанные настройки

При необходимости можно выполнить ручной запуск ротации(по дефолту ротация выполняется по расписанию)

Несколько команд для просмотра логов средствами утилиты gitlab-ctl

Просмотр логов всех сервисов в online-режиме

Просмотр всех логов в конкретном подкаталоге(например, в подкаталоге gitlab-rails)

Просмотр лога конкретного файла(например, access-лога Gitlab-сервиса)


Настройка лимитов на подключение к Gitlab

Enabling/Disabling Rack Attack and setting up basic auth throttling
https://my-sertif.ru/omnibus/settings/configuration.html#enablingdisabling-rack-attack-and-setting-up-basic-auth-throttling
https://my-sertif.ru/ee/security/rack_attack.html

3 неуспешные попытки за 10 минут — блокировка на 3 часа

Rate Limit/Throttling
Более 5 запросов незарегистрированным пользователем — троттлинг на 120 секунд
с кодом ответа 429 и ответом Too Many Requests

https://my-sertif.ru/ee/security/rate_limits.html

6-й запрос

Проверка наличия IP-адрса в заблокаированных:

Дефолтное место хранения репозитариев
https://my-sertif.ru/omnibus/settings/configuration.html#configuring-the-external-url-for-gitlab

Storage-директории

Полезные команды для работы с Gitlab-сервисами через утилиту gitlab-ctl

Послать команду на nginx-сервис для перечитывания им своей конфигурации при обновлении

Включение Container Registry в Gitlab

Получение Let’sEncrypt-сертификата для домена registry.mydomain.com

Для автоматического продления сертификата добавим в ранее созданный скрипт /usr/local/bin/ssl-renew.sh после строки с командой по запуску certbot
команду для обновления сертификата для домена registry.mydomain.com

И в конеце скрипта последней строкой добавляем перезапуск сервиса registry

Итого скрипт по обновлению сертификатов(как для gitlab, так и для registry) имеет вид:

По умолчанию registry запускается на порту 5000

Взаимодействие Gitlab и Registry
https://my-sertif.ru/omnibus/architecture/registry/README.html

Процес аутентификации в Container Registry в Gitlab(docker login…)
1.Docker client->Docker daemon->registry.mydomain.com->
2.Реджистри возвращает код ответа 401 т.к. не был предоставлен валидный токен
Вместе с кодом ответа 401 реджистри отправляет клиенту(который попытался залогиниться в реджистри с помощью команды docker login https://registry.mydomain.com)
token_realm (который указан в конфигурации реджистри в файле /var/opt/gitlab/registry/config.yml)

Этот token_realm как раз и указывает клиенту, где он может получить токен т.е.
обратиться за токеном на Gitlab (https://gitlab.mydomain.com) по указанному роуту

3.Docker клиент подключается к Gitlab API и получает токен
Этот токен Gitlab подписывает приватным ключем РЕДЖИСТРИ, а сертификат РЕДЖИСТРИ, которым будет
проверяться подписанный Gitlab-ом приватным ключем токен, прописан в конфиг.файла registry

Эта пара приватный ключ и сертификат для Реджистри является самоподписными и автоматически
выпускается Gitlab-ом при включении/настройке Registry
И эта пара никакого не имеет отношения к сертификату/ключу, который использует клиент при подключении к Registry снаружи(который мы выпускали средствами Let’sEncrypt)

4.Docker клиент подключается снова к Registry, но уже с валидным токеном, который он получил от Gitlab API и
успешно аутентифицируется в Docker-реджистри

Увеличение времени жизни токена(по дефолту 5 минут)
https://my-sertif.ru/13.6/ee/administration/packages/container_registry.html#container-registry-domain-configuration
Полезно,если в хранилище загружается большой по размеру образ, который не успевает загрузиться за 5 минут

Тегирование, загрузка, скачивание образов с Container Registry
https://my-sertif.ru/ee/user/packages/container_registry/
Залогиниться пользователем,который создан в Gitlab, в Registry( например, my-gitlab-user-name)

Перетегировать образ в формат, поддерживаемый Gitlab-ом

Загрузить образ в Registry

Удалить локальный образ

Загрузить образ с Registry

Troubleshooting Registry
https://my-sertif.ru/13.6/ee/administration/packages/container_registry.html#troubleshooting

Лог файл Registry

Лог файл Gitlab

Источник:

Установка
https://my-sertif.ru/13.6/omnibus/installation

Настройка
https://my-sertif.ru/omnibus/settings/configuration.html
https://my-sertif.ru/13.6/omnibus/README.html#configuring

Nginx
https://my-sertif.ru/13.6/omnibus/settings/nginx.html

Комментирование и размещение ссылок запрещено.

§

§

Установка сервера nginx с сертификатом let’s encrypt

Мы будем использовать установку GitLab CE, которая работает за сервером Nginx, который будет выполнять обратное проксирование и осуществлять обработку SSL-трафика. Для настройки базового сервера воспользуйтесь руководством из списка ниже, подходящим для вашей операционной системы.

На данный момент у вас должен быть развернут сервер с Nginx и сертификатом Let’s Encrypt. Теперь установим GitLab CE.

Оцените статью
Мой сертификат
Добавить комментарий