url
stringlengths 24
122
| repo_url
stringlengths 60
156
| date_extracted
stringdate 2025-08-13 00:00:00
2025-08-13 00:00:00
| root
stringlengths 3
85
| breadcrumbs
listlengths 1
6
| filename
stringlengths 6
60
| stage
stringclasses 33
values | group
stringclasses 81
values | info
stringclasses 22
values | title
stringlengths 3
110
⌀ | description
stringlengths 11
359
⌀ | clean_text
stringlengths 47
3.32M
| rich_text
stringlengths 321
3.32M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://docs.gitlab.com/administration/geo/disaster_recovery
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/_index.md
|
2025-08-13
|
doc/administration/geo/disaster_recovery
|
[
"doc",
"administration",
"geo",
"disaster_recovery"
] |
_index.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Disaster Recovery (Geo)
|
Recover from a disaster, using a Geo instance.
|
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Geo replicates your database, your Git repositories, and other assets.
Some [known issues](../_index.md#known-issues) exist.
{{< alert type="warning" >}}
Multi-secondary configurations require the complete re-synchronization and re-configuration of all non-promoted secondaries and
causes downtime.
{{< /alert >}}
## Promoting a **secondary** Geo site in single-secondary configurations
While you can't automatically promote a Geo replica and do a failover,
you can promote it manually if you have `root` access to the machine.
This process promotes a **secondary** Geo site to a **primary** site. To regain
geographic redundancy as quickly as possible, you should add a new **secondary** site
immediately after following these instructions.
### Step 1. Allow replication to finish if possible
If the **secondary** site is still replicating data from the **primary** site, follow
[the planned failover docs](planned_failover.md) as closely as possible in
order to avoid unnecessary data loss.
### Step 2. Permanently disable the **primary** site
{{< alert type="warning" >}}
If the **primary** site goes offline, there may be data saved on the **primary** site
that have not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
If an outage on the **primary** site happens, you should do everything possible to
avoid a split-brain situation where writes can occur in two different GitLab
instances, complicating recovery efforts. So to prepare for the failover, we
must disable the **primary** site.
- If you have SSH access:
1. SSH into the **primary** site to stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
1. Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting by any means at your disposal.
You might need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the primary DNS record to the
**secondary** site to stop usage of the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
If you plan to [update the primary domain DNS record](#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to maintain a low TTL to ensure fast propagation of DNS changes.
{{< alert type="note" >}}
The primary site's `/etc/gitlab/gitlab.rb` file is not copied to the secondary sites automatically during this process. Make sure that you back up the primary's `/etc/gitlab/gitlab.rb` file, so that you can later restore any needed values on your secondary sites.
{{< /alert >}}
### Step 3. Promoting a **secondary** site
Note the following when promoting a secondary:
- If the secondary site [has been paused](../replication/pause_resume_replication.md), the promotion
performs a point-in-time recovery to the last known state.
Data that was created on the primary while the secondary was paused is lost.
- A new **secondary** should not be added at this time. If you want to add a new
**secondary**, do this after you have completed the entire process of promoting
the **secondary** to the **primary**.
- If you encounter an `ActiveRecord::RecordInvalid: Validation failed: Name has already been taken`
error message during this process, for more information, see this
[troubleshooting advice](failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
- If you are using separate URLs, you should [point the primary domain DNS at the newly promoted site](#step-4-optional-updating-the-primary-domain-dns-record). Otherwise, runners must be registered again with the newly promoted site, and all Git remotes, bookmarks, and external integrations must be updated.
- If you are using [location-aware DNS](../secondary_proxy/_index.md#configure-location-aware-dns), the runners should automatically connect to the new primary after the old primary is removed from the DNS entry.
- If you don't expect the runners connected to the previous primary to come back, you should remove them:
- Through the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners** and remove them.
- Using the [Runners API](../../../api/runners.md).
#### Promoting a **secondary** site running on a single node
1. SSH in to your **secondary** site and execute:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with multiple nodes
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the node on the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with a Patroni standby cluster
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with an external PostgreSQL database
The `gitlab-ctl geo promote` command can be used in conjunction with an external PostgreSQL database.
In this case, you must first manually promote the replica database associated
with the **secondary** site:
1. Promote the replica database associated with the **secondary** site. This
sets the database to read-write. The instructions vary depending on where your database is hosted:
- [Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html#USER_ReadRepl.Promote)
- [Azure PostgreSQL](https://learn.microsoft.com/en-us/azure/postgresql/single-server/how-to-read-replicas-portal#stop-replication)
- [Google Cloud SQL](https://cloud.google.com/sql/docs/mysql/replication/manage-replicas#promote-replica)
- For other external PostgreSQL databases, save the following script in your
secondary site, for example `/tmp/geo_promote.sh`, and modify the connection
parameters to match your environment. Then, execute it to promote the replica:
```shell
#!/bin/bash
PG_SUPERUSER=postgres
# The path to your pg_ctl binary. You may need to adjust this path to match
# your PostgreSQL installation
PG_CTL_BINARY=/usr/lib/postgresql/10/bin/pg_ctl
# The path to your PostgreSQL data directory. You may need to adjust this
# path to match your PostgreSQL installation. You can also run
# `SHOW data_directory;` from PostgreSQL to find your data directory
PG_DATA_DIRECTORY=/etc/postgresql/10/main
# Promote the PostgreSQL database and allow read/write operations
sudo -u $PG_SUPERUSER $PG_CTL_BINARY -D $PG_DATA_DIRECTORY promote
```
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
### Step 4. (Optional) Updating the primary domain DNS record
Update DNS records for the primary domain to point to the **secondary** site.
This removes the need to update all references to the primary domain, for example
changing Git remotes and API URLs.
1. SSH into the **secondary** site and login as root:
```shell
sudo -i
```
1. Update the primary domain's DNS record. After updating the primary domain's
DNS records to point to the **secondary** site, edit `/etc/gitlab/gitlab.rb` on the
**secondary** site to reflect the new URL:
```ruby
# Change the existing external_url configuration
external_url 'https://<new_external_url>'
```
{{< alert type="note" >}}
Changing `external_url` does not prevent access through the old secondary URL, as
long as the secondary DNS records are still intact.
{{< /alert >}}
1. Update the **secondary**'s SSL certificate:
- If you use the [Let's Encrypt integration](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
the certificate updates automatically.
- If you had [manually set up](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
the **secondary**'s certificate, copy the certificate from the **primary** to the **secondary**.
If you don't have access to the **primary**, issue a new certificate and make sure it contains
both the **primary** and **secondary** URLs in the subject alternative names. You can check with:
```shell
/opt/gitlab/embedded/bin/openssl x509 -noout -dates -subject -issuer \
-nameopt multiline -ext subjectAltName -in /etc/gitlab/ssl/new-gitlab.new-example.com.crt
```
1. Reconfigure the **secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
```
1. Execute the command below to update the newly promoted **primary** site URL:
```shell
gitlab-rake geo:update_primary_node_url
```
This command uses the changed `external_url` configuration defined
in `/etc/gitlab/gitlab.rb`.
1. Verify you can connect to the newly promoted **primary** using its URL.
If you updated the DNS records for the primary domain, these changes may
not have yet propagated depending on the previous DNS records TTL.
### Step 5. (Optional) Add **secondary** Geo site to a promoted **primary** site
Promoting a **secondary** site to **primary** site using the previous process does not enable
Geo on the new **primary** site.
To bring a new **secondary** site online, follow the [Geo setup instructions](../setup/_index.md).
### Step 6. Removing the former secondary's tracking database
Every **secondary** has a special tracking database that is used to save the status of the synchronization of all the items from the **primary**.
Because the **secondary** is already promoted, that data in the tracking database is no longer required.
You can remove the data with the following command:
```shell
sudo rm -rf /var/opt/gitlab/geo-postgresql
```
If you have any `geo_secondary[]` configuration options enabled in your `gitlab.rb`
file, comment them out or remove them, and then [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
At this point, your promoted site is a normal GitLab site without Geo configured. Optionally, you can [bring the old site back as a secondary](bring_primary_back.md#configure-the-former-primary-site-to-be-a-secondary-site).
## Promoting secondary Geo replica in multi-secondary configurations
If you have more than one **secondary** site and you need to promote one of them, we suggest you follow
[Promoting a **secondary** Geo site in single-secondary configurations](#promoting-a-secondary-geo-site-in-single-secondary-configurations)
and after that you also need two extra steps.
### Step 1. Prepare the new **primary** site to serve one or more **secondary** sites
1. SSH into the new **primary** site and login as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
## Enable a Geo Primary role (if you haven't yet)
roles ['geo_primary_role']
##
# Allow PostgreSQL client authentication from the primary and secondary IPs. These IPs may be
# public or VPC addresses in CIDR format, for example ['198.51.100.1/32', '198.51.100.2/32']
##
postgresql['md5_auth_cidr_addresses'] = ['<primary_site_ip>/32', '<secondary_site_ip>/32']
# Every secondary site needs to have its own slot so specify the number of secondary sites you're going to have
# postgresql['max_replication_slots'] = 1 # Set this to be the number of Geo secondary nodes if you have more than one
##
## Disable automatic database migrations temporarily
## (until PostgreSQL is restarted and listening on the private address).
##
gitlab_rails['auto_migrate'] = false
```
(For more details about these settings you can read [Configure the primary server](../setup/database.md#step-1-configure-the-primary-site))
1. Save the file and reconfigure GitLab for the database listen changes and
the replication slot changes to be applied:
```shell
gitlab-ctl reconfigure
```
Restart PostgreSQL for its changes to take effect:
```shell
gitlab-ctl restart postgresql
```
1. Re-enable migrations now that PostgreSQL is restarted and listening on the
private address.
Edit `/etc/gitlab/gitlab.rb` and **change** the configuration to `true`:
```ruby
gitlab_rails['auto_migrate'] = true
```
Save the file and reconfigure GitLab:
```shell
gitlab-ctl reconfigure
```
### Step 2. Initiate the replication process
Now we need to make each **secondary** site listen to changes on the new **primary** site. To do that you need
to [initiate the replication process](../setup/database.md#step-3-initiate-the-replication-process) again but this time
for another **primary** site. All the old replication settings are overwritten.
Existing secondary sites will all have populated databases so you may see a message like this:
```shell
Found data inside the gitlabhq_production database! If you are sure you are in the secondary server, override with --force
```
After you have confirmed that you are on the appropriate secondary site, initiate the replication with `--force`.
{{< alert type="warning" >}}
Using `--force` causes **all existing data in the database on that secondary server to be deleted**.
{{< /alert >}}
## Promoting a secondary Geo cluster in the GitLab Helm chart
When updating a cloud-native Geo deployment, the process for updating any node that is external to the secondary Kubernetes cluster does not differ from the non cloud-native approach. As such, you can always defer to [Promoting a secondary Geo site in single-secondary configurations](#promoting-a-secondary-geo-site-in-single-secondary-configurations) for more information.
The following sections assume you are using the `gitlab` namespace. If you used a different namespace when setting up your cluster, you should also replace `--namespace gitlab` with your namespace.
### Step 1. Permanently disable the **primary** cluster
{{< alert type="warning" >}}
If the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
If an outage on the **primary** site happens, you should do everything possible to
avoid a split-brain situation where writes can occur in two different GitLab
instances, complicating recovery efforts. So to prepare for the failover, you
must disable the **primary** site:
- If you have access to the **primary** Kubernetes cluster, connect to it and disable the GitLab `webservice` and `Sidekiq` pods:
```shell
kubectl --namespace gitlab scale deploy gitlab-geo-webservice-default --replicas=0
kubectl --namespace gitlab scale deploy gitlab-geo-sidekiq-all-in-1-v1 --replicas=0
```
- If you do not have access to the **primary** Kubernetes cluster, take the cluster offline and
prevent it from coming back online by any means at your disposal.
You might need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the primary DNS record to the
**secondary** site to stop usage of the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Step 2. Promote all **secondary** site nodes external to the cluster
{{< alert type="warning" >}}
If the secondary site [has been paused](../_index.md#pausing-and-resuming-replication), this performs
a point-in-time recovery to the last known state.
Data that was created on the primary while the secondary was paused is lost.
{{< /alert >}}
1. For each node (such as PostgreSQL or Gitaly) outside of the **secondary** Kubernetes cluster using the Linux
package, SSH into the node and run one of the following commands:
- To promote the **secondary** site node external to the Kubernetes cluster to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the **secondary** site node external to the Kubernetes cluster to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Find the `toolbox` pod:
```shell
kubectl --namespace gitlab get pods -lapp=toolbox
```
1. Promote the secondary:
```shell
kubectl --namespace gitlab exec -ti gitlab-geo-toolbox-XXX -- gitlab-rake geo:set_secondary_as_primary
```
Environment variables can be provided to modify the behavior of the task. The
available variables are:
| Name | Default value | Description |
| ---- | ------------- | ------- |
| `ENABLE_SILENT_MODE` | `false` | If `true`, enables [Silent Mode](../../silent_mode/_index.md) before promotion (GitLab 16.4 and later) |
### Step 3. Promote the **secondary** cluster
1. Update the existing cluster configuration.
You can retrieve the existing configuration with Helm:
```shell
helm --namespace gitlab get values gitlab-geo > gitlab.yaml
```
The existing configuration contains a section for Geo that should resemble:
```yaml
geo:
enabled: true
role: secondary
nodeName: secondary.example.com
psql:
host: geo-2.db.example.com
port: 5431
password:
secret: geo
key: geo-postgresql-password
```
To promote the **secondary** cluster to a **primary** cluster, update `role: secondary` to `role: primary`.
If the cluster remains as a primary site, you can remove the entire `psql` section; it refers to the tracking database and is ignored while the cluster is acting as a primary site.
Update the cluster with the new configuration:
```shell
helm upgrade --install --version <current Chart version> gitlab-geo gitlab/gitlab --namespace gitlab -f gitlab.yaml
```
1. Verify you can connect to the newly promoted primary using the URL used previously for the secondary.
1. Success! The secondary has now been promoted to primary.
## Troubleshooting
This section was moved to [another location](failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Disaster Recovery (Geo)
description: Recover from a disaster, using a Geo instance.
breadcrumbs:
- doc
- administration
- geo
- disaster_recovery
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Geo replicates your database, your Git repositories, and other assets.
Some [known issues](../_index.md#known-issues) exist.
{{< alert type="warning" >}}
Multi-secondary configurations require the complete re-synchronization and re-configuration of all non-promoted secondaries and
causes downtime.
{{< /alert >}}
## Promoting a **secondary** Geo site in single-secondary configurations
While you can't automatically promote a Geo replica and do a failover,
you can promote it manually if you have `root` access to the machine.
This process promotes a **secondary** Geo site to a **primary** site. To regain
geographic redundancy as quickly as possible, you should add a new **secondary** site
immediately after following these instructions.
### Step 1. Allow replication to finish if possible
If the **secondary** site is still replicating data from the **primary** site, follow
[the planned failover docs](planned_failover.md) as closely as possible in
order to avoid unnecessary data loss.
### Step 2. Permanently disable the **primary** site
{{< alert type="warning" >}}
If the **primary** site goes offline, there may be data saved on the **primary** site
that have not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
If an outage on the **primary** site happens, you should do everything possible to
avoid a split-brain situation where writes can occur in two different GitLab
instances, complicating recovery efforts. So to prepare for the failover, we
must disable the **primary** site.
- If you have SSH access:
1. SSH into the **primary** site to stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
1. Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting by any means at your disposal.
You might need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the primary DNS record to the
**secondary** site to stop usage of the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
If you plan to [update the primary domain DNS record](#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to maintain a low TTL to ensure fast propagation of DNS changes.
{{< alert type="note" >}}
The primary site's `/etc/gitlab/gitlab.rb` file is not copied to the secondary sites automatically during this process. Make sure that you back up the primary's `/etc/gitlab/gitlab.rb` file, so that you can later restore any needed values on your secondary sites.
{{< /alert >}}
### Step 3. Promoting a **secondary** site
Note the following when promoting a secondary:
- If the secondary site [has been paused](../replication/pause_resume_replication.md), the promotion
performs a point-in-time recovery to the last known state.
Data that was created on the primary while the secondary was paused is lost.
- A new **secondary** should not be added at this time. If you want to add a new
**secondary**, do this after you have completed the entire process of promoting
the **secondary** to the **primary**.
- If you encounter an `ActiveRecord::RecordInvalid: Validation failed: Name has already been taken`
error message during this process, for more information, see this
[troubleshooting advice](failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
- If you are using separate URLs, you should [point the primary domain DNS at the newly promoted site](#step-4-optional-updating-the-primary-domain-dns-record). Otherwise, runners must be registered again with the newly promoted site, and all Git remotes, bookmarks, and external integrations must be updated.
- If you are using [location-aware DNS](../secondary_proxy/_index.md#configure-location-aware-dns), the runners should automatically connect to the new primary after the old primary is removed from the DNS entry.
- If you don't expect the runners connected to the previous primary to come back, you should remove them:
- Through the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners** and remove them.
- Using the [Runners API](../../../api/runners.md).
#### Promoting a **secondary** site running on a single node
1. SSH in to your **secondary** site and execute:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with multiple nodes
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the node on the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with a Patroni standby cluster
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
#### Promoting a **secondary** site with an external PostgreSQL database
The `gitlab-ctl geo promote` command can be used in conjunction with an external PostgreSQL database.
In this case, you must first manually promote the replica database associated
with the **secondary** site:
1. Promote the replica database associated with the **secondary** site. This
sets the database to read-write. The instructions vary depending on where your database is hosted:
- [Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html#USER_ReadRepl.Promote)
- [Azure PostgreSQL](https://learn.microsoft.com/en-us/azure/postgresql/single-server/how-to-read-replicas-portal#stop-replication)
- [Google Cloud SQL](https://cloud.google.com/sql/docs/mysql/replication/manage-replicas#promote-replica)
- For other external PostgreSQL databases, save the following script in your
secondary site, for example `/tmp/geo_promote.sh`, and modify the connection
parameters to match your environment. Then, execute it to promote the replica:
```shell
#!/bin/bash
PG_SUPERUSER=postgres
# The path to your pg_ctl binary. You may need to adjust this path to match
# your PostgreSQL installation
PG_CTL_BINARY=/usr/lib/postgresql/10/bin/pg_ctl
# The path to your PostgreSQL data directory. You may need to adjust this
# path to match your PostgreSQL installation. You can also run
# `SHOW data_directory;` from PostgreSQL to find your data directory
PG_DATA_DIRECTORY=/etc/postgresql/10/main
# Promote the PostgreSQL database and allow read/write operations
sudo -u $PG_SUPERUSER $PG_CTL_BINARY -D $PG_DATA_DIRECTORY promote
```
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly-promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
### Step 4. (Optional) Updating the primary domain DNS record
Update DNS records for the primary domain to point to the **secondary** site.
This removes the need to update all references to the primary domain, for example
changing Git remotes and API URLs.
1. SSH into the **secondary** site and login as root:
```shell
sudo -i
```
1. Update the primary domain's DNS record. After updating the primary domain's
DNS records to point to the **secondary** site, edit `/etc/gitlab/gitlab.rb` on the
**secondary** site to reflect the new URL:
```ruby
# Change the existing external_url configuration
external_url 'https://<new_external_url>'
```
{{< alert type="note" >}}
Changing `external_url` does not prevent access through the old secondary URL, as
long as the secondary DNS records are still intact.
{{< /alert >}}
1. Update the **secondary**'s SSL certificate:
- If you use the [Let's Encrypt integration](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
the certificate updates automatically.
- If you had [manually set up](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
the **secondary**'s certificate, copy the certificate from the **primary** to the **secondary**.
If you don't have access to the **primary**, issue a new certificate and make sure it contains
both the **primary** and **secondary** URLs in the subject alternative names. You can check with:
```shell
/opt/gitlab/embedded/bin/openssl x509 -noout -dates -subject -issuer \
-nameopt multiline -ext subjectAltName -in /etc/gitlab/ssl/new-gitlab.new-example.com.crt
```
1. Reconfigure the **secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
```
1. Execute the command below to update the newly promoted **primary** site URL:
```shell
gitlab-rake geo:update_primary_node_url
```
This command uses the changed `external_url` configuration defined
in `/etc/gitlab/gitlab.rb`.
1. Verify you can connect to the newly promoted **primary** using its URL.
If you updated the DNS records for the primary domain, these changes may
not have yet propagated depending on the previous DNS records TTL.
### Step 5. (Optional) Add **secondary** Geo site to a promoted **primary** site
Promoting a **secondary** site to **primary** site using the previous process does not enable
Geo on the new **primary** site.
To bring a new **secondary** site online, follow the [Geo setup instructions](../setup/_index.md).
### Step 6. Removing the former secondary's tracking database
Every **secondary** has a special tracking database that is used to save the status of the synchronization of all the items from the **primary**.
Because the **secondary** is already promoted, that data in the tracking database is no longer required.
You can remove the data with the following command:
```shell
sudo rm -rf /var/opt/gitlab/geo-postgresql
```
If you have any `geo_secondary[]` configuration options enabled in your `gitlab.rb`
file, comment them out or remove them, and then [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
At this point, your promoted site is a normal GitLab site without Geo configured. Optionally, you can [bring the old site back as a secondary](bring_primary_back.md#configure-the-former-primary-site-to-be-a-secondary-site).
## Promoting secondary Geo replica in multi-secondary configurations
If you have more than one **secondary** site and you need to promote one of them, we suggest you follow
[Promoting a **secondary** Geo site in single-secondary configurations](#promoting-a-secondary-geo-site-in-single-secondary-configurations)
and after that you also need two extra steps.
### Step 1. Prepare the new **primary** site to serve one or more **secondary** sites
1. SSH into the new **primary** site and login as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
## Enable a Geo Primary role (if you haven't yet)
roles ['geo_primary_role']
##
# Allow PostgreSQL client authentication from the primary and secondary IPs. These IPs may be
# public or VPC addresses in CIDR format, for example ['198.51.100.1/32', '198.51.100.2/32']
##
postgresql['md5_auth_cidr_addresses'] = ['<primary_site_ip>/32', '<secondary_site_ip>/32']
# Every secondary site needs to have its own slot so specify the number of secondary sites you're going to have
# postgresql['max_replication_slots'] = 1 # Set this to be the number of Geo secondary nodes if you have more than one
##
## Disable automatic database migrations temporarily
## (until PostgreSQL is restarted and listening on the private address).
##
gitlab_rails['auto_migrate'] = false
```
(For more details about these settings you can read [Configure the primary server](../setup/database.md#step-1-configure-the-primary-site))
1. Save the file and reconfigure GitLab for the database listen changes and
the replication slot changes to be applied:
```shell
gitlab-ctl reconfigure
```
Restart PostgreSQL for its changes to take effect:
```shell
gitlab-ctl restart postgresql
```
1. Re-enable migrations now that PostgreSQL is restarted and listening on the
private address.
Edit `/etc/gitlab/gitlab.rb` and **change** the configuration to `true`:
```ruby
gitlab_rails['auto_migrate'] = true
```
Save the file and reconfigure GitLab:
```shell
gitlab-ctl reconfigure
```
### Step 2. Initiate the replication process
Now we need to make each **secondary** site listen to changes on the new **primary** site. To do that you need
to [initiate the replication process](../setup/database.md#step-3-initiate-the-replication-process) again but this time
for another **primary** site. All the old replication settings are overwritten.
Existing secondary sites will all have populated databases so you may see a message like this:
```shell
Found data inside the gitlabhq_production database! If you are sure you are in the secondary server, override with --force
```
After you have confirmed that you are on the appropriate secondary site, initiate the replication with `--force`.
{{< alert type="warning" >}}
Using `--force` causes **all existing data in the database on that secondary server to be deleted**.
{{< /alert >}}
## Promoting a secondary Geo cluster in the GitLab Helm chart
When updating a cloud-native Geo deployment, the process for updating any node that is external to the secondary Kubernetes cluster does not differ from the non cloud-native approach. As such, you can always defer to [Promoting a secondary Geo site in single-secondary configurations](#promoting-a-secondary-geo-site-in-single-secondary-configurations) for more information.
The following sections assume you are using the `gitlab` namespace. If you used a different namespace when setting up your cluster, you should also replace `--namespace gitlab` with your namespace.
### Step 1. Permanently disable the **primary** cluster
{{< alert type="warning" >}}
If the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
If an outage on the **primary** site happens, you should do everything possible to
avoid a split-brain situation where writes can occur in two different GitLab
instances, complicating recovery efforts. So to prepare for the failover, you
must disable the **primary** site:
- If you have access to the **primary** Kubernetes cluster, connect to it and disable the GitLab `webservice` and `Sidekiq` pods:
```shell
kubectl --namespace gitlab scale deploy gitlab-geo-webservice-default --replicas=0
kubectl --namespace gitlab scale deploy gitlab-geo-sidekiq-all-in-1-v1 --replicas=0
```
- If you do not have access to the **primary** Kubernetes cluster, take the cluster offline and
prevent it from coming back online by any means at your disposal.
You might need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the primary DNS record to the
**secondary** site to stop usage of the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Step 2. Promote all **secondary** site nodes external to the cluster
{{< alert type="warning" >}}
If the secondary site [has been paused](../_index.md#pausing-and-resuming-replication), this performs
a point-in-time recovery to the last known state.
Data that was created on the primary while the secondary was paused is lost.
{{< /alert >}}
1. For each node (such as PostgreSQL or Gitaly) outside of the **secondary** Kubernetes cluster using the Linux
package, SSH into the node and run one of the following commands:
- To promote the **secondary** site node external to the Kubernetes cluster to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the **secondary** site node external to the Kubernetes cluster to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Find the `toolbox` pod:
```shell
kubectl --namespace gitlab get pods -lapp=toolbox
```
1. Promote the secondary:
```shell
kubectl --namespace gitlab exec -ti gitlab-geo-toolbox-XXX -- gitlab-rake geo:set_secondary_as_primary
```
Environment variables can be provided to modify the behavior of the task. The
available variables are:
| Name | Default value | Description |
| ---- | ------------- | ------- |
| `ENABLE_SILENT_MODE` | `false` | If `true`, enables [Silent Mode](../../silent_mode/_index.md) before promotion (GitLab 16.4 and later) |
### Step 3. Promote the **secondary** cluster
1. Update the existing cluster configuration.
You can retrieve the existing configuration with Helm:
```shell
helm --namespace gitlab get values gitlab-geo > gitlab.yaml
```
The existing configuration contains a section for Geo that should resemble:
```yaml
geo:
enabled: true
role: secondary
nodeName: secondary.example.com
psql:
host: geo-2.db.example.com
port: 5431
password:
secret: geo
key: geo-postgresql-password
```
To promote the **secondary** cluster to a **primary** cluster, update `role: secondary` to `role: primary`.
If the cluster remains as a primary site, you can remove the entire `psql` section; it refers to the tracking database and is ignored while the cluster is acting as a primary site.
Update the cluster with the new configuration:
```shell
helm upgrade --install --version <current Chart version> gitlab-geo gitlab/gitlab --namespace gitlab -f gitlab.yaml
```
1. Verify you can connect to the newly promoted primary using the URL used previously for the secondary.
1. Success! The secondary has now been promoted to primary.
## Troubleshooting
This section was moved to [another location](failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
|
https://docs.gitlab.com/administration/geo/bring_primary_back
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/bring_primary_back.md
|
2025-08-13
|
doc/administration/geo/disaster_recovery
|
[
"doc",
"administration",
"geo",
"disaster_recovery"
] |
bring_primary_back.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Bring a demoted primary site back online
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
After a failover, it is possible to fail back to the demoted **primary** site to
restore your original configuration. This process consists of two steps:
1. Making the old **primary** site a **secondary** site.
1. Promoting a **secondary** site to a **primary** site.
{{< alert type="warning" >}}
If you have any doubts about the consistency of the data on this site, we recommend setting it up from scratch.
{{< /alert >}}
## Configure the former **primary** site to be a **secondary** site
Because the former **primary** site is out of sync with the current **primary** site, the first step is to bring the former **primary** site up to date. Note, deletion of data stored on disk like
repositories and uploads is not replayed when bringing the former **primary** site back
into sync, which may result in increased disk usage.
Alternatively, you can [set up a new **secondary** GitLab instance](../setup/_index.md) to avoid this.
To bring the former **primary** site up to date:
1. SSH into the former **primary** site that has fallen behind.
1. Remove `/etc/gitlab/gitlab-cluster.json` if it exists.
If the site to be re-added as a **secondary** site was promoted with the `gitlab-ctl geo promote` command, then it may contain a `/etc/gitlab/gitlab-cluster.json` file. For example during `gitlab-ctl reconfigure`, you may notice output like:
```plaintext
The 'geo_primary_role' is defined in /etc/gitlab/gitlab-cluster.json as 'true' and overrides the setting in the /etc/gitlab/gitlab.rb
```
If so, then `/etc/gitlab/gitlab-cluster.json` must be deleted from every Sidekiq, PostgreSQL, Gitaly, and Rails node in the site, to make `/etc/gitlab/gitlab.rb` the single source of truth again.
1. Make sure all the services are up:
```shell
sudo gitlab-ctl start
```
{{< alert type="note" >}}
If you [disabled the **primary** site permanently](_index.md#step-2-permanently-disable-the-primary-site),
you need to undo those steps now. For distributions with systemd, such as Debian/Ubuntu/CentOS7+, you must run
`sudo systemctl enable gitlab-runsvdir`. For distributions without systemd, such as CentOS 6, you need to install
the GitLab instance from scratch and set it up as a **secondary** site by
following [Setup instructions](../setup/_index.md). In this case, you don't need to follow the next step.
{{< /alert >}}
{{< alert type="note" >}}
If you [changed the DNS records](_index.md#step-4-optional-updating-the-primary-domain-dns-record)
for this site during disaster recovery procedure you may need to
[block all the writes to this site](planned_failover.md#prevent-updates-to-the-primary-site)
during this procedure.
{{< /alert >}}
1. [Set up Geo](../setup/_index.md). In this case, the **secondary** site
refers to the former **primary** site.
1. If [PgBouncer](../../postgresql/pgbouncer.md) was enabled on the **current secondary** site
(when it was a primary site) disable it by editing `/etc/gitlab/gitlab.rb`
and running `sudo gitlab-ctl reconfigure`.
1. You can then set up database replication on the **secondary** site.
If you have lost your original **primary** site, follow the
[setup instructions](../setup/_index.md) to set up a new **secondary** site.
## Promote the **secondary** site to **primary** site
When the initial replication is complete and the **primary** site and **secondary** site are
closely in sync, you can do a [planned failover](planned_failover.md).
## Restore the **secondary** site
If your objective is to have two sites again, you need to bring your **secondary**
site back online as well by repeating the first step
([configure the former **primary** site to be a **secondary** site](#configure-the-former-primary-site-to-be-a-secondary-site))
for the **secondary** site.
### Restoring additional **secondary** sites
If there is more than one **secondary** site, the remaining sites can be brought online now. For each of the remaining sites, [initiate the replication process](../setup/database.md#step-3-initiate-the-replication-process) with the **primary** site.
## Skipping re-transfer of data on a **secondary** site
When a secondary site is added, if it contains data that would otherwise be synced from the primary, then Geo avoids re-transferring the data.
- Git repositories are transferred by `git fetch`, which only transfers missing refs.
- Geo's container registry sync code compares tuples of tags and digests, and only pulls missing ones.
- [Blobs](#skipping-re-transfer-of-blobs) are skipped if they exist on the first sync.
Use-cases:
- You do a planned failover and demote the old primary site by attaching it as a secondary site without rebuilding it.
- You have multiple secondary Geo sites. You do a planned failover and reattach the other secondary Geo sites without rebuilding them.
- You do a failover test by promoting and demoting a secondary site and reattach it without rebuilding it.
- You restore a backup and attach the site as a secondary site.
- You manually copy data to a secondary site to workaround a sync problem.
- You delete or truncate registry table rows in the Geo tracking database to workaround a problem.
- You reset the Geo tracking database to workaround a problem.
### Skipping re-transfer of blobs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/352530) in GitLab 16.8 [with a flag](../../feature_flags/_index.md) named `geo_skip_download_if_exists`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/435788) in GitLab 16.9. Feature flag `geo_skip_download_if_exists` removed.
{{< /history >}}
When you add a secondary site which has preexisting blobs data, then the secondary Geo site will avoid re-transferring that data. This applies to:
- CI job artifacts
- CI pipeline artifacts
- CI secure files
- LFS objects
- Merge request diffs
- Package files
- Pages deployments
- Terraform state versions
- Uploads
- Dependency proxy manifests
- Dependency proxy blobs
If the secondary site's copy is actually corrupted, then background verification will eventually fail, and the blob will be resynced.
Blobs will only be skipped in this manner if they do not have a corresponding registry record in the Geo tracking database. The conditions are strict because resyncing is almost always intentional, and we cannot risk mistakenly skipping a transfer.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Bring a demoted primary site back online
breadcrumbs:
- doc
- administration
- geo
- disaster_recovery
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
After a failover, it is possible to fail back to the demoted **primary** site to
restore your original configuration. This process consists of two steps:
1. Making the old **primary** site a **secondary** site.
1. Promoting a **secondary** site to a **primary** site.
{{< alert type="warning" >}}
If you have any doubts about the consistency of the data on this site, we recommend setting it up from scratch.
{{< /alert >}}
## Configure the former **primary** site to be a **secondary** site
Because the former **primary** site is out of sync with the current **primary** site, the first step is to bring the former **primary** site up to date. Note, deletion of data stored on disk like
repositories and uploads is not replayed when bringing the former **primary** site back
into sync, which may result in increased disk usage.
Alternatively, you can [set up a new **secondary** GitLab instance](../setup/_index.md) to avoid this.
To bring the former **primary** site up to date:
1. SSH into the former **primary** site that has fallen behind.
1. Remove `/etc/gitlab/gitlab-cluster.json` if it exists.
If the site to be re-added as a **secondary** site was promoted with the `gitlab-ctl geo promote` command, then it may contain a `/etc/gitlab/gitlab-cluster.json` file. For example during `gitlab-ctl reconfigure`, you may notice output like:
```plaintext
The 'geo_primary_role' is defined in /etc/gitlab/gitlab-cluster.json as 'true' and overrides the setting in the /etc/gitlab/gitlab.rb
```
If so, then `/etc/gitlab/gitlab-cluster.json` must be deleted from every Sidekiq, PostgreSQL, Gitaly, and Rails node in the site, to make `/etc/gitlab/gitlab.rb` the single source of truth again.
1. Make sure all the services are up:
```shell
sudo gitlab-ctl start
```
{{< alert type="note" >}}
If you [disabled the **primary** site permanently](_index.md#step-2-permanently-disable-the-primary-site),
you need to undo those steps now. For distributions with systemd, such as Debian/Ubuntu/CentOS7+, you must run
`sudo systemctl enable gitlab-runsvdir`. For distributions without systemd, such as CentOS 6, you need to install
the GitLab instance from scratch and set it up as a **secondary** site by
following [Setup instructions](../setup/_index.md). In this case, you don't need to follow the next step.
{{< /alert >}}
{{< alert type="note" >}}
If you [changed the DNS records](_index.md#step-4-optional-updating-the-primary-domain-dns-record)
for this site during disaster recovery procedure you may need to
[block all the writes to this site](planned_failover.md#prevent-updates-to-the-primary-site)
during this procedure.
{{< /alert >}}
1. [Set up Geo](../setup/_index.md). In this case, the **secondary** site
refers to the former **primary** site.
1. If [PgBouncer](../../postgresql/pgbouncer.md) was enabled on the **current secondary** site
(when it was a primary site) disable it by editing `/etc/gitlab/gitlab.rb`
and running `sudo gitlab-ctl reconfigure`.
1. You can then set up database replication on the **secondary** site.
If you have lost your original **primary** site, follow the
[setup instructions](../setup/_index.md) to set up a new **secondary** site.
## Promote the **secondary** site to **primary** site
When the initial replication is complete and the **primary** site and **secondary** site are
closely in sync, you can do a [planned failover](planned_failover.md).
## Restore the **secondary** site
If your objective is to have two sites again, you need to bring your **secondary**
site back online as well by repeating the first step
([configure the former **primary** site to be a **secondary** site](#configure-the-former-primary-site-to-be-a-secondary-site))
for the **secondary** site.
### Restoring additional **secondary** sites
If there is more than one **secondary** site, the remaining sites can be brought online now. For each of the remaining sites, [initiate the replication process](../setup/database.md#step-3-initiate-the-replication-process) with the **primary** site.
## Skipping re-transfer of data on a **secondary** site
When a secondary site is added, if it contains data that would otherwise be synced from the primary, then Geo avoids re-transferring the data.
- Git repositories are transferred by `git fetch`, which only transfers missing refs.
- Geo's container registry sync code compares tuples of tags and digests, and only pulls missing ones.
- [Blobs](#skipping-re-transfer-of-blobs) are skipped if they exist on the first sync.
Use-cases:
- You do a planned failover and demote the old primary site by attaching it as a secondary site without rebuilding it.
- You have multiple secondary Geo sites. You do a planned failover and reattach the other secondary Geo sites without rebuilding them.
- You do a failover test by promoting and demoting a secondary site and reattach it without rebuilding it.
- You restore a backup and attach the site as a secondary site.
- You manually copy data to a secondary site to workaround a sync problem.
- You delete or truncate registry table rows in the Geo tracking database to workaround a problem.
- You reset the Geo tracking database to workaround a problem.
### Skipping re-transfer of blobs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/352530) in GitLab 16.8 [with a flag](../../feature_flags/_index.md) named `geo_skip_download_if_exists`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/435788) in GitLab 16.9. Feature flag `geo_skip_download_if_exists` removed.
{{< /history >}}
When you add a secondary site which has preexisting blobs data, then the secondary Geo site will avoid re-transferring that data. This applies to:
- CI job artifacts
- CI pipeline artifacts
- CI secure files
- LFS objects
- Merge request diffs
- Package files
- Pages deployments
- Terraform state versions
- Uploads
- Dependency proxy manifests
- Dependency proxy blobs
If the secondary site's copy is actually corrupted, then background verification will eventually fail, and the blob will be resynced.
Blobs will only be skipped in this manner if they do not have a corresponding registry record in the Geo tracking database. The conditions are strict because resyncing is almost always intentional, and we cannot risk mistakenly skipping a transfer.
|
https://docs.gitlab.com/administration/geo/disaster_recovery/planned_failover_single_node
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/disaster_recovery/planned_failover_single_node.md
|
2025-08-13
|
doc/administration/geo/disaster_recovery/runbooks
|
[
"doc",
"administration",
"geo",
"disaster_recovery",
"runbooks"
] |
planned_failover_single_node.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Disaster Recovery (Geo) promotion runbooks
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
Disaster Recovery (Geo) promotion runbooks.
{{< alert type="warning" >}}
This runbook is an [experiment](../../../../policy/development_stages_support.md#experiment). For complete, production-ready documentation, see the
[disaster recovery documentation](../_index.md).
{{< /alert >}}
## Geo planned failover for a single-node configuration
| Component | Configuration |
|:------------|:-----------------------------|
| PostgreSQL | Managed by the Linux package |
| Geo site | Single-node |
| Secondaries | One |
This runbook guides you through a planned failover of a single-node Geo site
with one secondary. The following general architecture is assumed:
```mermaid
graph TD
subgraph main[Geo deployment]
subgraph Primary[Primary site]
Node_1[(GitLab node)]
end
subgraph Secondary1[Secondary site]
Node_2[(GitLab node)]
end
end
```
This guide results in the following:
1. An offline primary.
1. A promoted secondary that is now the new primary.
What is not covered:
1. Re-adding the old **primary** as a secondary.
1. Adding a new secondary.
### Preparation
{{< alert type="note" >}}
Before following any of those steps, make sure you have `root` access to the
**secondary** to promote it because there isn't an automated way to
promote a Geo replica and perform a failover.
{{< /alert >}}
On the **secondary** site, go to the **Admin area > Geo** dashboard to
review its status. Replicated objects (shown in green) should be close to 100%,
and there should be no failures (shown in red). If a large proportion of
objects aren't yet replicated (shown in gray), consider giving the site more
time to complete.

If any objects are failing to replicate, this should be investigated before
scheduling the maintenance window. After a planned failover, anything that
failed to replicate is **lost**.
A common cause of replication failures is the data being missing on the
**primary** site - you can resolve these failures by restoring the data from backup,
or removing references to the missing data.
The maintenance window does not end until Geo replication and verification is
completely finished. To keep the window as short as possible, you should
ensure these processes are close to 100% as possible during active use.
If the **secondary** site is still replicating data from the **primary** site,
follow these steps to avoid unnecessary data loss:
1. Until a [read-only mode](https://gitlab.com/gitlab-org/gitlab/-/issues/14609)
is implemented, updates must be prevented from happening manually to the
**primary**. Your **secondary** site still needs read-only
access to the **primary** site during the maintenance window:
1. At the scheduled time, using your cloud provider or your site's firewall, block
all HTTP, HTTPS and SSH traffic to/from the **primary** site, **except** for your IP and
the **secondary** site's IP.
For instance, you can run the following commands on the **primary** site:
```shell
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 22 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 22 -j ACCEPT
sudo iptables -A INPUT --destination-port 22 -j REJECT
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 80 -j ACCEPT
sudo iptables -A INPUT --tcp-dport 80 -j REJECT
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 443 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 443 -j ACCEPT
sudo iptables -A INPUT --tcp-dport 443 -j REJECT
```
From this point, users are unable to view their data or make changes on the
**primary** site. They are also unable to sign in to the **secondary** site.
However, existing sessions need to work for the remainder of the maintenance period, and
so public data is accessible throughout.
1. Verify the **primary** site is blocked to HTTP traffic by visiting it in browser via
another IP. The server should refuse connection.
1. Verify the **primary** site is blocked to Git over SSH traffic by attempting to pull an
existing Git repository with an SSH remote URL. The server should refuse
connection.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**..
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Cron**.
1. Select `Disable All` to disable any non-Geo periodic background jobs.
1. Select `Enable` for the `geo_sidekiq_cron_config_worker` cron job.
This job re-enables several other cron jobs that are essential for planned
failover to complete successfully.
1. Finish replicating and verifying all data:
{{< alert type="warning" >}}
Not all data is automatically replicated. Read more about
[what is excluded](../planned_failover.md#not-all-data-is-automatically-replicated).
{{< /alert >}}
1. If you are manually replicating any
[data not managed by Geo](../../replication/datatypes.md#replicated-data-types),
trigger the final replication process now.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all queues except
those with `geo` in the name to drop to 0.
These queues contain work that has been submitted by your users; failing over
before it is completed, causes the work to be lost.
1. On the left sidebar, select **Geo > Sites** and wait for the
following conditions to be true of the **secondary** site you are failing over to:
- All replication meters reach 100% replicated, 0% failures.
- All verification meters reach 100% verified, 0% failures.
- Database replication lag is 0 ms.
- The Geo log cursor is up to date (0 events behind).
1. On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all the `geo`
queues to drop to 0 queued and 0 running jobs.
1. [Run an integrity check](../../../raketasks/check.md) to verify the integrity
of CI artifacts, LFS objects, and uploads in file storage.
At this point, your **secondary** site contains an up-to-date copy of everything the
**primary** site has, meaning nothing is lost when you fail over.
1. In this final step, you need to permanently disable the **primary** site.
{{< alert type="warning" >}}
When the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
{{< alert type="note" >}}
If you plan to [update the **primary** domain DNS record](../_index.md#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to lower the TTL now to speed up propagation.
{{< /alert >}}
When performing a failover, we want to avoid a split-brain situation where
writes can occur in two different GitLab instances. So to prepare for the
failover, you must disable the **primary** site:
- If you have SSH access to the **primary** site, stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
{{< alert type="note" >}}
(**CentOS only**) In CentOS 6 or older, there is no easy way to prevent GitLab from being
started if the machine reboots isn't available (see [issue 3058](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3058)).
It may be safest to uninstall the GitLab package completely with `sudo yum remove gitlab-ee`.
{{< /alert >}}
{{< alert type="note" >}}
(**Ubuntu 14.04 LTS**) If you are using an older version of Ubuntu
or any other distribution based on the Upstart init system, you can prevent GitLab
from starting if the machine reboots as `root` with
`initctl stop gitlab-runsvvdir && echo 'manual' > /etc/init/gitlab-runsvdir.override && initctl reload-configuration`.
{{< /alert >}}
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting. Because there are many ways you may prefer to accomplish
this, we avoid a single recommendation. You may need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the **primary** DNS record to the
**secondary** site to stop using the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Promoting the **secondary** site
Note the following when promoting a secondary:
- A new **secondary** should not be added at this time. If you want to add a new
**secondary**, do this after you have completed the entire process of promoting
the **secondary** to the **primary**.
- If you encounter an `ActiveRecord::RecordInvalid: Validation failed: Name has already been taken`
error during this process, read
[the troubleshooting advice](../failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
To promote the secondary site:
1. SSH in to your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly promoted **primary** site using the URL used
previously for the **secondary** site.
If successful, the **secondary** site is now promoted to the **primary** site.
### Next steps
To regain geographic redundancy as quickly as possible, you should
[add a new **secondary** site](../../setup/_index.md). To
do that, you can re-add the old **primary** as a new secondary and bring it back
online.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
ignore_in_report: true
title: Disaster Recovery (Geo) promotion runbooks
breadcrumbs:
- doc
- administration
- geo
- disaster_recovery
- runbooks
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
Disaster Recovery (Geo) promotion runbooks.
{{< alert type="warning" >}}
This runbook is an [experiment](../../../../policy/development_stages_support.md#experiment). For complete, production-ready documentation, see the
[disaster recovery documentation](../_index.md).
{{< /alert >}}
## Geo planned failover for a single-node configuration
| Component | Configuration |
|:------------|:-----------------------------|
| PostgreSQL | Managed by the Linux package |
| Geo site | Single-node |
| Secondaries | One |
This runbook guides you through a planned failover of a single-node Geo site
with one secondary. The following general architecture is assumed:
```mermaid
graph TD
subgraph main[Geo deployment]
subgraph Primary[Primary site]
Node_1[(GitLab node)]
end
subgraph Secondary1[Secondary site]
Node_2[(GitLab node)]
end
end
```
This guide results in the following:
1. An offline primary.
1. A promoted secondary that is now the new primary.
What is not covered:
1. Re-adding the old **primary** as a secondary.
1. Adding a new secondary.
### Preparation
{{< alert type="note" >}}
Before following any of those steps, make sure you have `root` access to the
**secondary** to promote it because there isn't an automated way to
promote a Geo replica and perform a failover.
{{< /alert >}}
On the **secondary** site, go to the **Admin area > Geo** dashboard to
review its status. Replicated objects (shown in green) should be close to 100%,
and there should be no failures (shown in red). If a large proportion of
objects aren't yet replicated (shown in gray), consider giving the site more
time to complete.

If any objects are failing to replicate, this should be investigated before
scheduling the maintenance window. After a planned failover, anything that
failed to replicate is **lost**.
A common cause of replication failures is the data being missing on the
**primary** site - you can resolve these failures by restoring the data from backup,
or removing references to the missing data.
The maintenance window does not end until Geo replication and verification is
completely finished. To keep the window as short as possible, you should
ensure these processes are close to 100% as possible during active use.
If the **secondary** site is still replicating data from the **primary** site,
follow these steps to avoid unnecessary data loss:
1. Until a [read-only mode](https://gitlab.com/gitlab-org/gitlab/-/issues/14609)
is implemented, updates must be prevented from happening manually to the
**primary**. Your **secondary** site still needs read-only
access to the **primary** site during the maintenance window:
1. At the scheduled time, using your cloud provider or your site's firewall, block
all HTTP, HTTPS and SSH traffic to/from the **primary** site, **except** for your IP and
the **secondary** site's IP.
For instance, you can run the following commands on the **primary** site:
```shell
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 22 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 22 -j ACCEPT
sudo iptables -A INPUT --destination-port 22 -j REJECT
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 80 -j ACCEPT
sudo iptables -A INPUT --tcp-dport 80 -j REJECT
sudo iptables -A INPUT -p tcp -s <secondary_site_ip> --destination-port 443 -j ACCEPT
sudo iptables -A INPUT -p tcp -s <your_ip> --destination-port 443 -j ACCEPT
sudo iptables -A INPUT --tcp-dport 443 -j REJECT
```
From this point, users are unable to view their data or make changes on the
**primary** site. They are also unable to sign in to the **secondary** site.
However, existing sessions need to work for the remainder of the maintenance period, and
so public data is accessible throughout.
1. Verify the **primary** site is blocked to HTTP traffic by visiting it in browser via
another IP. The server should refuse connection.
1. Verify the **primary** site is blocked to Git over SSH traffic by attempting to pull an
existing Git repository with an SSH remote URL. The server should refuse
connection.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**..
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Cron**.
1. Select `Disable All` to disable any non-Geo periodic background jobs.
1. Select `Enable` for the `geo_sidekiq_cron_config_worker` cron job.
This job re-enables several other cron jobs that are essential for planned
failover to complete successfully.
1. Finish replicating and verifying all data:
{{< alert type="warning" >}}
Not all data is automatically replicated. Read more about
[what is excluded](../planned_failover.md#not-all-data-is-automatically-replicated).
{{< /alert >}}
1. If you are manually replicating any
[data not managed by Geo](../../replication/datatypes.md#replicated-data-types),
trigger the final replication process now.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all queues except
those with `geo` in the name to drop to 0.
These queues contain work that has been submitted by your users; failing over
before it is completed, causes the work to be lost.
1. On the left sidebar, select **Geo > Sites** and wait for the
following conditions to be true of the **secondary** site you are failing over to:
- All replication meters reach 100% replicated, 0% failures.
- All verification meters reach 100% verified, 0% failures.
- Database replication lag is 0 ms.
- The Geo log cursor is up to date (0 events behind).
1. On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all the `geo`
queues to drop to 0 queued and 0 running jobs.
1. [Run an integrity check](../../../raketasks/check.md) to verify the integrity
of CI artifacts, LFS objects, and uploads in file storage.
At this point, your **secondary** site contains an up-to-date copy of everything the
**primary** site has, meaning nothing is lost when you fail over.
1. In this final step, you need to permanently disable the **primary** site.
{{< alert type="warning" >}}
When the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
{{< alert type="note" >}}
If you plan to [update the **primary** domain DNS record](../_index.md#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to lower the TTL now to speed up propagation.
{{< /alert >}}
When performing a failover, we want to avoid a split-brain situation where
writes can occur in two different GitLab instances. So to prepare for the
failover, you must disable the **primary** site:
- If you have SSH access to the **primary** site, stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
{{< alert type="note" >}}
(**CentOS only**) In CentOS 6 or older, there is no easy way to prevent GitLab from being
started if the machine reboots isn't available (see [issue 3058](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3058)).
It may be safest to uninstall the GitLab package completely with `sudo yum remove gitlab-ee`.
{{< /alert >}}
{{< alert type="note" >}}
(**Ubuntu 14.04 LTS**) If you are using an older version of Ubuntu
or any other distribution based on the Upstart init system, you can prevent GitLab
from starting if the machine reboots as `root` with
`initctl stop gitlab-runsvvdir && echo 'manual' > /etc/init/gitlab-runsvdir.override && initctl reload-configuration`.
{{< /alert >}}
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting. Because there are many ways you may prefer to accomplish
this, we avoid a single recommendation. You may need to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the **primary** DNS record to the
**secondary** site to stop using the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Promoting the **secondary** site
Note the following when promoting a secondary:
- A new **secondary** should not be added at this time. If you want to add a new
**secondary**, do this after you have completed the entire process of promoting
the **secondary** to the **primary**.
- If you encounter an `ActiveRecord::RecordInvalid: Validation failed: Name has already been taken`
error during this process, read
[the troubleshooting advice](../failover_troubleshooting.md#fixing-errors-during-a-failover-or-when-promoting-a-secondary-to-a-primary-site).
To promote the secondary site:
1. SSH in to your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly promoted **primary** site using the URL used
previously for the **secondary** site.
If successful, the **secondary** site is now promoted to the **primary** site.
### Next steps
To regain geographic redundancy as quickly as possible, you should
[add a new **secondary** site](../../setup/_index.md). To
do that, you can re-add the old **primary** as a new secondary and bring it back
online.
|
https://docs.gitlab.com/administration/geo/disaster_recovery/planned_failover_multi_node
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/disaster_recovery/planned_failover_multi_node.md
|
2025-08-13
|
doc/administration/geo/disaster_recovery/runbooks
|
[
"doc",
"administration",
"geo",
"disaster_recovery",
"runbooks"
] |
planned_failover_multi_node.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Disaster Recovery (Geo) promotion runbooks
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
Disaster Recovery (Geo) promotion runbooks.
{{< alert type="warning" >}}
This runbook is an [experiment](../../../../policy/development_stages_support.md#experiment). For complete, production-ready documentation, see the
[disaster recovery documentation](../_index.md).
{{< /alert >}}
## Geo planned failover for a multi-node configuration
| Component | Configuration |
|:------------|:-----------------------------|
| PostgreSQL | Managed by the Linux package |
| Geo site | Multi-node |
| Secondaries | One |
This runbook guides you through a planned failover of a multi-node Geo site
with one secondary. The following [40 RPS / 2,000 user reference architecture](../../../reference_architectures/2k_users.md) is assumed:
```mermaid
graph TD
subgraph main[Geo deployment]
subgraph Primary[Primary site, multi-node]
Node_1[Rails node 1]
Node_2[Rails node 2]
Node_3[PostgreSQL node]
Node_4[Gitaly node]
Node_5[Redis node]
Node_6[Monitoring node]
end
subgraph Secondary[Secondary site, multi-node]
Node_7[Rails node 1]
Node_8[Rails node 2]
Node_9[PostgreSQL node]
Node_10[Gitaly node]
Node_11[Redis node]
Node_12[Monitoring node]
end
end
```
The load balancer node and optional NFS server are omitted for clarity.
This guide results in the following:
1. An offline primary.
1. A promoted secondary that is now the new primary.
What is not covered:
1. Re-adding the old **primary** as a secondary.
1. Adding a new secondary.
### Preparation
{{< alert type="note" >}}
Before following any of those steps, make sure you have `root` access to the
**secondary** to promote it, because there isn't provided an automated way to
promote a Geo replica and perform a failover.
{{< /alert >}}
On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites** to see its status.
Replicated objects (shown in green) should be close to 100%,
and there should be no failures (shown in red). If a large proportion of
objects aren't replicated (shown in gray), consider giving the site more
time to complete.

If any objects are failing to replicate, this should be investigated before
scheduling the maintenance window. After a planned failover, anything that
failed to replicate is **lost**.
A common cause of replication failures is data that is missing on the
**primary** site - you can resolve these failures by restoring the data from backup,
or removing references to the missing data.
The maintenance window doesn't end until Geo replication and verification is
completely finished. To keep the window as short as possible, you should
ensure these processes are close to 100% as possible during active use.
If the **secondary** site is still replicating data from the **primary** site,
follow these steps to avoid unnecessary data loss:
1. Enable [maintenance mode](../../../maintenance_mode/_index.md) on the **primary** site,
and make sure to stop any [background jobs](../../../maintenance_mode/_index.md#background-jobs).
1. Finish replicating and verifying all data:
{{< alert type="warning" >}}
Not all data is automatically replicated. Read more about
[what is excluded](../planned_failover.md#not-all-data-is-automatically-replicated).
{{< /alert >}}
1. If you are manually replicating any
[data not managed by Geo](../../replication/datatypes.md#replicated-data-types),
trigger the final replication process now.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all queues except
those with `geo` in the name to drop to 0.
These queues contain work that has been submitted by your users; failing over
before it is completed, causes the work to be lost.
1. On the left sidebar, select **Geo > Sites** and wait for the
following conditions to be true of the **secondary** site you are failing over to:
- All replication meters reach 100% replicated, 0% failures.
- All verification meters reach 100% verified, 0% failures.
- Database replication lag is 0 ms.
- The Geo log cursor is up to date (0 events behind).
1. On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all the `geo`
queues to drop to 0 queued and 0 running jobs.
1. [Run an integrity check](../../../raketasks/check.md) to verify the integrity
of CI artifacts, LFS objects, and uploads in file storage.
At this point, your **secondary** site contains an up-to-date copy of everything the
**primary** site has, meaning nothing is lost when you fail over.
1. In this final step, you must permanently disable the **primary** site.
{{< alert type="warning" >}}
When the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
{{< alert type="note" >}}
If you plan to [update the **primary** domain DNS record](../_index.md#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to lower the TTL now to speed up propagation.
{{< /alert >}}
When performing a failover, we want to avoid a split-brain situation where
writes can occur in two different GitLab instances. So to prepare for the
failover, you must disable the **primary** site:
- If you have SSH access to the **primary** site, stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
{{< alert type="note" >}}
(**CentOS only**) In CentOS 6 or older, it is challenging to prevent GitLab from being
started if the machine reboots isn't available (see [issue 3058](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3058)).
It may be safest to uninstall the GitLab package completely with `sudo yum remove gitlab-ee`.
{{< /alert >}}
{{< alert type="note" >}}
(**Ubuntu 14.04 LTS**) If you are using an older version of Ubuntu
or any other distribution based on the Upstart init system, you can prevent GitLab
from starting if the machine reboots as `root` with
`initctl stop gitlab-runsvvdir && echo 'manual' > /etc/init/gitlab-runsvdir.override && initctl reload-configuration`.
{{< /alert >}}
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting. As there are many ways you may prefer to accomplish
this, we avoid a single recommendation. You may have to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the **primary** DNS record to the
**secondary** site to stop using the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Promoting the **secondary** site
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
### Next steps
To regain geographic redundancy as quickly as possible, you should
[add a new **secondary** site](../../setup/_index.md). To
do that, you can re-add the old **primary** as a new secondary and bring it back
online.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
ignore_in_report: true
title: Disaster Recovery (Geo) promotion runbooks
breadcrumbs:
- doc
- administration
- geo
- disaster_recovery
- runbooks
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
Disaster Recovery (Geo) promotion runbooks.
{{< alert type="warning" >}}
This runbook is an [experiment](../../../../policy/development_stages_support.md#experiment). For complete, production-ready documentation, see the
[disaster recovery documentation](../_index.md).
{{< /alert >}}
## Geo planned failover for a multi-node configuration
| Component | Configuration |
|:------------|:-----------------------------|
| PostgreSQL | Managed by the Linux package |
| Geo site | Multi-node |
| Secondaries | One |
This runbook guides you through a planned failover of a multi-node Geo site
with one secondary. The following [40 RPS / 2,000 user reference architecture](../../../reference_architectures/2k_users.md) is assumed:
```mermaid
graph TD
subgraph main[Geo deployment]
subgraph Primary[Primary site, multi-node]
Node_1[Rails node 1]
Node_2[Rails node 2]
Node_3[PostgreSQL node]
Node_4[Gitaly node]
Node_5[Redis node]
Node_6[Monitoring node]
end
subgraph Secondary[Secondary site, multi-node]
Node_7[Rails node 1]
Node_8[Rails node 2]
Node_9[PostgreSQL node]
Node_10[Gitaly node]
Node_11[Redis node]
Node_12[Monitoring node]
end
end
```
The load balancer node and optional NFS server are omitted for clarity.
This guide results in the following:
1. An offline primary.
1. A promoted secondary that is now the new primary.
What is not covered:
1. Re-adding the old **primary** as a secondary.
1. Adding a new secondary.
### Preparation
{{< alert type="note" >}}
Before following any of those steps, make sure you have `root` access to the
**secondary** to promote it, because there isn't provided an automated way to
promote a Geo replica and perform a failover.
{{< /alert >}}
On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites** to see its status.
Replicated objects (shown in green) should be close to 100%,
and there should be no failures (shown in red). If a large proportion of
objects aren't replicated (shown in gray), consider giving the site more
time to complete.

If any objects are failing to replicate, this should be investigated before
scheduling the maintenance window. After a planned failover, anything that
failed to replicate is **lost**.
A common cause of replication failures is data that is missing on the
**primary** site - you can resolve these failures by restoring the data from backup,
or removing references to the missing data.
The maintenance window doesn't end until Geo replication and verification is
completely finished. To keep the window as short as possible, you should
ensure these processes are close to 100% as possible during active use.
If the **secondary** site is still replicating data from the **primary** site,
follow these steps to avoid unnecessary data loss:
1. Enable [maintenance mode](../../../maintenance_mode/_index.md) on the **primary** site,
and make sure to stop any [background jobs](../../../maintenance_mode/_index.md#background-jobs).
1. Finish replicating and verifying all data:
{{< alert type="warning" >}}
Not all data is automatically replicated. Read more about
[what is excluded](../planned_failover.md#not-all-data-is-automatically-replicated).
{{< /alert >}}
1. If you are manually replicating any
[data not managed by Geo](../../replication/datatypes.md#replicated-data-types),
trigger the final replication process now.
1. On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all queues except
those with `geo` in the name to drop to 0.
These queues contain work that has been submitted by your users; failing over
before it is completed, causes the work to be lost.
1. On the left sidebar, select **Geo > Sites** and wait for the
following conditions to be true of the **secondary** site you are failing over to:
- All replication meters reach 100% replicated, 0% failures.
- All verification meters reach 100% verified, 0% failures.
- Database replication lag is 0 ms.
- The Geo log cursor is up to date (0 events behind).
1. On the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Monitoring > Background jobs**.
1. On the Sidekiq dashboard, select **Queues**, and wait for all the `geo`
queues to drop to 0 queued and 0 running jobs.
1. [Run an integrity check](../../../raketasks/check.md) to verify the integrity
of CI artifacts, LFS objects, and uploads in file storage.
At this point, your **secondary** site contains an up-to-date copy of everything the
**primary** site has, meaning nothing is lost when you fail over.
1. In this final step, you must permanently disable the **primary** site.
{{< alert type="warning" >}}
When the **primary** site goes offline, there may be data saved on the **primary** site
that has not been replicated to the **secondary** site. This data should be treated
as lost if you proceed.
{{< /alert >}}
{{< alert type="note" >}}
If you plan to [update the **primary** domain DNS record](../_index.md#step-4-optional-updating-the-primary-domain-dns-record),
you may wish to lower the TTL now to speed up propagation.
{{< /alert >}}
When performing a failover, we want to avoid a split-brain situation where
writes can occur in two different GitLab instances. So to prepare for the
failover, you must disable the **primary** site:
- If you have SSH access to the **primary** site, stop and disable GitLab:
```shell
sudo gitlab-ctl stop
```
Prevent GitLab from starting up again if the server unexpectedly reboots:
```shell
sudo systemctl disable gitlab-runsvdir
```
{{< alert type="note" >}}
(**CentOS only**) In CentOS 6 or older, it is challenging to prevent GitLab from being
started if the machine reboots isn't available (see [issue 3058](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3058)).
It may be safest to uninstall the GitLab package completely with `sudo yum remove gitlab-ee`.
{{< /alert >}}
{{< alert type="note" >}}
(**Ubuntu 14.04 LTS**) If you are using an older version of Ubuntu
or any other distribution based on the Upstart init system, you can prevent GitLab
from starting if the machine reboots as `root` with
`initctl stop gitlab-runsvvdir && echo 'manual' > /etc/init/gitlab-runsvdir.override && initctl reload-configuration`.
{{< /alert >}}
- If you do not have SSH access to the **primary** site, take the machine offline and
prevent it from rebooting. As there are many ways you may prefer to accomplish
this, we avoid a single recommendation. You may have to:
- Reconfigure the load balancers.
- Change DNS records (for example, point the **primary** DNS record to the
**secondary** site to stop using the **primary** site).
- Stop the virtual servers.
- Block traffic through a firewall.
- Revoke object storage permissions from the **primary** site.
- Physically disconnect a machine.
### Promoting the **secondary** site
1. SSH to every Sidekiq, PostgreSQL, and Gitaly node in the **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. SSH into each Rails node on your **secondary** site and run one of the following commands:
- To promote the secondary site to primary:
```shell
sudo gitlab-ctl geo promote
```
- To promote the secondary site to primary **without any further confirmation**:
```shell
sudo gitlab-ctl geo promote --force
```
1. Verify you can connect to the newly promoted **primary** site using the URL used
previously for the **secondary** site.
1. If successful, the **secondary** site is now promoted to the **primary** site.
### Next steps
To regain geographic redundancy as quickly as possible, you should
[add a new **secondary** site](../../setup/_index.md). To
do that, you can re-add the old **primary** as a new secondary and bring it back
online.
|
https://docs.gitlab.com/administration/geo/faq
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/faq.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
faq.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo Frequently Asked Questions
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## What are the minimum requirements to run Geo?
The requirements are listed [on the index page](../_index.md#requirements-for-running-geo)
## How does Geo know which projects to sync?
On each **secondary** site, there is a read-only replicated copy of the GitLab database.
A **secondary** site also has a tracking database where it stores which projects have been synced.
Geo compares the two databases to find projects that are not yet tracked.
At the start, this tracking database is empty, so Geo tries to update from every project that it can see in the GitLab database.
For each project to sync:
1. Geo issues a `git fetch geo --mirror` to get the latest information from the **primary** site.
If there are no changes, the sync is fast. Otherwise, it has to pull the latest commits.
1. The **secondary** site updates the tracking database to store the fact that it has synced projects by name.
1. Repeat until all projects are synced.
When someone pushes a commit to the **primary** site, it generates an event in the GitLab database that the repository has changed.
The **secondary** site sees this event, marks the project in question as dirty, and schedules the project to be resynced.
To ensure that problems with pipelines (for example, syncs failing too many times or jobs being lost) don't permanently stop projects syncing, Geo also periodically checks the tracking database for projects that are marked as dirty. This check happens when
the number of concurrent syncs falls below `repos_max_capacity` and there are no new projects waiting to be synced.
Geo also has a checksum feature which runs a SHA256 sum across all the Git references to the SHA values.
If the refs don't match between the **primary** site and the **secondary** site, then the **secondary** site marks that project as dirty and try to resync it.
So even if we have an outdated tracking database, the validation should activate and find discrepancies in the repository state and resync.
## Can you use Geo in a disaster recovery situation?
Yes, but there are limitations to what we replicate (see
[What data is replicated to a **secondary** site?](#what-data-is-replicated-to-a-secondary-site)).
Read the documentation for [Disaster Recovery](../disaster_recovery/_index.md).
## What data is replicated to a **secondary** site?
We replicate the whole rails database, project repositories, LFS objects, generated
attachments, avatars and more. This means information such as user accounts,
issues, merge requests, groups, and project data are available for
query.
For a comprehensive list of data replicated by Geo, see the [supported Geo data types page](datatypes.md).
## Can I `git push` to a **secondary** site?
Pushing directly to a **secondary** site (for both HTTP and SSH, including Git LFS) is supported.
## How long does it take to have a commit replicated to a **secondary** site?
All replication operations are asynchronous and are queued to be dispatched. Therefore, it depends on a lot of
factors such as the amount of traffic, how big your commit is, the
connectivity between your sites, and your hardware.
## What if the SSH server runs at a different port?
That's totally fine. We use HTTP(s) to fetch repository changes from the **primary** site to all **secondary** sites.
## Can I make a container registry for a secondary site to mirror the primary?
Yes, however, we only support this for Disaster Recovery scenarios. See [container registry for a **secondary** site](container_registry.md).
## Can you sign in to a secondary site?
Yes, but secondary sites receive all authentication data (like user accounts and logins) from the primary instance. This means you are re-directed to the primary for authentication and then routed back.
## Do all Geo sites need to be the same as the primary?
No, Geo sites can be based on different reference architectures. For example, you can have the primary site based on a 3K reference architecture, one secondary site based 3K reference architecture, and another one based on a 1K reference architecture.
## Does Geo replicate archived projects?
Yes, provided they are not excluded through [selective sync](selective_synchronization.md).
## Does Geo replicate personal projects?
Yes, provided they are not excluded through [selective sync](selective_synchronization.md).
## Are delayed deletion projects replicated to secondary sites?
Yes, projects scheduled for deletion by [delayed deletion](../../settings/visibility_and_access_controls.md#delayed-project-deletion), but are yet to be permanently deleted, are replicated to secondary sites.
## What happens to my secondary sites with when my primary site goes down?
When a primary site goes down,
[your secondary will not be accessible through the UI](../secondary_proxy/_index.md#behavior-of-secondary-sites-when-the-primary-geo-site-is-down)
unless your restore the services on your primary site or you perform a promotion
on your secondary site.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Geo Frequently Asked Questions
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## What are the minimum requirements to run Geo?
The requirements are listed [on the index page](../_index.md#requirements-for-running-geo)
## How does Geo know which projects to sync?
On each **secondary** site, there is a read-only replicated copy of the GitLab database.
A **secondary** site also has a tracking database where it stores which projects have been synced.
Geo compares the two databases to find projects that are not yet tracked.
At the start, this tracking database is empty, so Geo tries to update from every project that it can see in the GitLab database.
For each project to sync:
1. Geo issues a `git fetch geo --mirror` to get the latest information from the **primary** site.
If there are no changes, the sync is fast. Otherwise, it has to pull the latest commits.
1. The **secondary** site updates the tracking database to store the fact that it has synced projects by name.
1. Repeat until all projects are synced.
When someone pushes a commit to the **primary** site, it generates an event in the GitLab database that the repository has changed.
The **secondary** site sees this event, marks the project in question as dirty, and schedules the project to be resynced.
To ensure that problems with pipelines (for example, syncs failing too many times or jobs being lost) don't permanently stop projects syncing, Geo also periodically checks the tracking database for projects that are marked as dirty. This check happens when
the number of concurrent syncs falls below `repos_max_capacity` and there are no new projects waiting to be synced.
Geo also has a checksum feature which runs a SHA256 sum across all the Git references to the SHA values.
If the refs don't match between the **primary** site and the **secondary** site, then the **secondary** site marks that project as dirty and try to resync it.
So even if we have an outdated tracking database, the validation should activate and find discrepancies in the repository state and resync.
## Can you use Geo in a disaster recovery situation?
Yes, but there are limitations to what we replicate (see
[What data is replicated to a **secondary** site?](#what-data-is-replicated-to-a-secondary-site)).
Read the documentation for [Disaster Recovery](../disaster_recovery/_index.md).
## What data is replicated to a **secondary** site?
We replicate the whole rails database, project repositories, LFS objects, generated
attachments, avatars and more. This means information such as user accounts,
issues, merge requests, groups, and project data are available for
query.
For a comprehensive list of data replicated by Geo, see the [supported Geo data types page](datatypes.md).
## Can I `git push` to a **secondary** site?
Pushing directly to a **secondary** site (for both HTTP and SSH, including Git LFS) is supported.
## How long does it take to have a commit replicated to a **secondary** site?
All replication operations are asynchronous and are queued to be dispatched. Therefore, it depends on a lot of
factors such as the amount of traffic, how big your commit is, the
connectivity between your sites, and your hardware.
## What if the SSH server runs at a different port?
That's totally fine. We use HTTP(s) to fetch repository changes from the **primary** site to all **secondary** sites.
## Can I make a container registry for a secondary site to mirror the primary?
Yes, however, we only support this for Disaster Recovery scenarios. See [container registry for a **secondary** site](container_registry.md).
## Can you sign in to a secondary site?
Yes, but secondary sites receive all authentication data (like user accounts and logins) from the primary instance. This means you are re-directed to the primary for authentication and then routed back.
## Do all Geo sites need to be the same as the primary?
No, Geo sites can be based on different reference architectures. For example, you can have the primary site based on a 3K reference architecture, one secondary site based 3K reference architecture, and another one based on a 1K reference architecture.
## Does Geo replicate archived projects?
Yes, provided they are not excluded through [selective sync](selective_synchronization.md).
## Does Geo replicate personal projects?
Yes, provided they are not excluded through [selective sync](selective_synchronization.md).
## Are delayed deletion projects replicated to secondary sites?
Yes, projects scheduled for deletion by [delayed deletion](../../settings/visibility_and_access_controls.md#delayed-project-deletion), but are yet to be permanently deleted, are replicated to secondary sites.
## What happens to my secondary sites with when my primary site goes down?
When a primary site goes down,
[your secondary will not be accessible through the UI](../secondary_proxy/_index.md#behavior-of-secondary-sites-when-the-primary-geo-site-is-down)
unless your restore the services on your primary site or you perform a promotion
on your secondary site.
|
https://docs.gitlab.com/administration/geo/upgrading_the_geo_sites
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/upgrading_the_geo_sites.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
upgrading_the_geo_sites.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Upgrading the Geo sites
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="warning" >}}
Read these sections carefully before updating your Geo sites. Not following
version-specific upgrade steps may result in unexpected downtime. If you have
any specific questions, [contact Support](https://about.gitlab.com/support/#contact-support).
A database major version upgrade requires [re-initializing the PostgreSQL replication](https://docs.gitlab.com/omnibus/settings/database.html#upgrading-a-geo-instance)
to Geo secondaries. This applies to both Linux-packaged and externally-managed databases.
This may result in a larger than expected downtime.
{{< /alert >}}
Upgrading Geo sites involves performing:
1. Version-specific upgrade steps, depending on the version being upgraded to or from:
- [GitLab 18 upgrade notes](../../../update/versions/gitlab_18_changes.md)
- [GitLab 17 upgrade notes](../../../update/versions/gitlab_17_changes.md)
- [GitLab 16 upgrade notes](../../../update/versions/gitlab_16_changes.md)
- [GitLab 15 upgrade notes](../../../update/versions/gitlab_15_changes.md)
1. [General upgrade steps](#general-upgrade-steps), for all upgrades.
## General upgrade steps
{{< alert type="note" >}}
These general upgrade steps require downtime in a multi-node setup.
If you want to avoid downtime, consider using [zero-downtime upgrades](../../../update/zero_downtime.md#multi-node--ha-deployment-with-geo).
{{< /alert >}}
To upgrade the Geo sites when a new GitLab version is released, upgrade **primary**
and all **secondary** sites:
1. Optional. [Pause replication on each **secondary** site](pause_resume_replication.md)
to protect the disaster recovery (DR) capability of the **secondary** sites.
1. SSH into each node of the **primary** site.
1. [Upgrade GitLab on the **primary** site](../../../update/package/_index.md#by-using-the-official-repositories-recommended).
1. Perform testing on the **primary** site, particularly if you paused replication in step 1 to protect DR.
For more information about post-upgrade testing, see [pre-upgrade and post-upgrade checks](../../../update/upgrade.md#pre-upgrade-and-post-upgrade-checks).
1. Ensure that the secrets in the `/etc/gitlab/gitlab-secrets.json` file of both the primary site and the secondary site are the same. The file must be the same on all of a site's nodes.
1. SSH into each node of **secondary** sites.
1. [Upgrade GitLab on each **secondary** site](../../../update/package/_index.md#by-using-the-official-repositories-recommended).
1. If you paused replication in step 1, [resume replication on each **secondary**](../_index.md#pausing-and-resuming-replication).
Then, restart Puma and Sidekiq on each **secondary** site. This is to ensure they
are initialized against the newer database schema that is now replicated from
the previously upgraded **primary** site.
```shell
sudo gitlab-ctl restart sidekiq
sudo gitlab-ctl restart puma
```
1. [Test](#check-status-after-upgrading) **primary** and **secondary** sites, and check version in each.
### Check status after upgrading
Now that the upgrade process is complete, you may want to check whether
everything is working correctly:
1. Run the Geo Rake task on an application node for the primary and secondary sites. Everything should be green:
```shell
sudo gitlab-rake gitlab:geo:check
```
1. Check the **primary** site's Geo dashboard for any errors.
1. Test the data replication by pushing code to the **primary** site and see if it
is received by **secondary** sites.
If you encounter any issues, see the [Geo troubleshooting guide](troubleshooting/_index.md).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Upgrading the Geo sites
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="warning" >}}
Read these sections carefully before updating your Geo sites. Not following
version-specific upgrade steps may result in unexpected downtime. If you have
any specific questions, [contact Support](https://about.gitlab.com/support/#contact-support).
A database major version upgrade requires [re-initializing the PostgreSQL replication](https://docs.gitlab.com/omnibus/settings/database.html#upgrading-a-geo-instance)
to Geo secondaries. This applies to both Linux-packaged and externally-managed databases.
This may result in a larger than expected downtime.
{{< /alert >}}
Upgrading Geo sites involves performing:
1. Version-specific upgrade steps, depending on the version being upgraded to or from:
- [GitLab 18 upgrade notes](../../../update/versions/gitlab_18_changes.md)
- [GitLab 17 upgrade notes](../../../update/versions/gitlab_17_changes.md)
- [GitLab 16 upgrade notes](../../../update/versions/gitlab_16_changes.md)
- [GitLab 15 upgrade notes](../../../update/versions/gitlab_15_changes.md)
1. [General upgrade steps](#general-upgrade-steps), for all upgrades.
## General upgrade steps
{{< alert type="note" >}}
These general upgrade steps require downtime in a multi-node setup.
If you want to avoid downtime, consider using [zero-downtime upgrades](../../../update/zero_downtime.md#multi-node--ha-deployment-with-geo).
{{< /alert >}}
To upgrade the Geo sites when a new GitLab version is released, upgrade **primary**
and all **secondary** sites:
1. Optional. [Pause replication on each **secondary** site](pause_resume_replication.md)
to protect the disaster recovery (DR) capability of the **secondary** sites.
1. SSH into each node of the **primary** site.
1. [Upgrade GitLab on the **primary** site](../../../update/package/_index.md#by-using-the-official-repositories-recommended).
1. Perform testing on the **primary** site, particularly if you paused replication in step 1 to protect DR.
For more information about post-upgrade testing, see [pre-upgrade and post-upgrade checks](../../../update/upgrade.md#pre-upgrade-and-post-upgrade-checks).
1. Ensure that the secrets in the `/etc/gitlab/gitlab-secrets.json` file of both the primary site and the secondary site are the same. The file must be the same on all of a site's nodes.
1. SSH into each node of **secondary** sites.
1. [Upgrade GitLab on each **secondary** site](../../../update/package/_index.md#by-using-the-official-repositories-recommended).
1. If you paused replication in step 1, [resume replication on each **secondary**](../_index.md#pausing-and-resuming-replication).
Then, restart Puma and Sidekiq on each **secondary** site. This is to ensure they
are initialized against the newer database schema that is now replicated from
the previously upgraded **primary** site.
```shell
sudo gitlab-ctl restart sidekiq
sudo gitlab-ctl restart puma
```
1. [Test](#check-status-after-upgrading) **primary** and **secondary** sites, and check version in each.
### Check status after upgrading
Now that the upgrade process is complete, you may want to check whether
everything is working correctly:
1. Run the Geo Rake task on an application node for the primary and secondary sites. Everything should be green:
```shell
sudo gitlab-rake gitlab:geo:check
```
1. Check the **primary** site's Geo dashboard for any errors.
1. Test the data replication by pushing code to the **primary** site and see if it
is received by **secondary** sites.
If you encounter any issues, see the [Geo troubleshooting guide](troubleshooting/_index.md).
|
https://docs.gitlab.com/administration/geo/remove_geo_site
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/remove_geo_site.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
remove_geo_site.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Removing secondary Geo sites
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
**Secondary** sites can be removed from the Geo cluster using the Geo administration page of the **primary** site. To remove a **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Nodes**.
1. For the **secondary** site you want to remove, select **Remove**.
1. Confirm by selecting **Remove** when the prompt appears.
After the **secondary** site is removed from the Geo administration page, you must
stop and uninstall this site. For each node on your secondary Geo site:
1. Stop GitLab:
```shell
sudo gitlab-ctl stop
```
1. Uninstall GitLab:
{{< alert type="note" >}}
If GitLab data has to be cleaned from the instance as well, see how to [uninstall the Linux package and all its data](https://docs.gitlab.com/omnibus/installation/#uninstall-the-linux-package-omnibus).
{{< /alert >}}
```shell
# Stop gitlab and remove its supervision process
sudo gitlab-ctl uninstall
# Debian/Ubuntu
sudo dpkg --remove gitlab-ee
# Redhat/Centos
sudo rpm --erase gitlab-ee
```
When GitLab has been uninstalled from each node on the **secondary** site, the replication slot must be dropped from the **primary** site's database as follows:
1. On the **primary** site's database node, start a PostgreSQL console session:
```shell
sudo gitlab-psql
```
{{< alert type="note" >}}
Using `gitlab-rails dbconsole` does not work, because managing replication slots requires superuser permissions.
{{< /alert >}}
1. Find the name of the relevant replication slot. This is the slot that is specified with `--slot-name` when running the replicate command: `gitlab-ctl replicate-geo-database`.
```sql
SELECT * FROM pg_replication_slots;
```
1. Remove the replication slot for the **secondary** site:
```sql
SELECT pg_drop_replication_slot('<name_of_slot>');
```
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Removing secondary Geo sites
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
**Secondary** sites can be removed from the Geo cluster using the Geo administration page of the **primary** site. To remove a **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Nodes**.
1. For the **secondary** site you want to remove, select **Remove**.
1. Confirm by selecting **Remove** when the prompt appears.
After the **secondary** site is removed from the Geo administration page, you must
stop and uninstall this site. For each node on your secondary Geo site:
1. Stop GitLab:
```shell
sudo gitlab-ctl stop
```
1. Uninstall GitLab:
{{< alert type="note" >}}
If GitLab data has to be cleaned from the instance as well, see how to [uninstall the Linux package and all its data](https://docs.gitlab.com/omnibus/installation/#uninstall-the-linux-package-omnibus).
{{< /alert >}}
```shell
# Stop gitlab and remove its supervision process
sudo gitlab-ctl uninstall
# Debian/Ubuntu
sudo dpkg --remove gitlab-ee
# Redhat/Centos
sudo rpm --erase gitlab-ee
```
When GitLab has been uninstalled from each node on the **secondary** site, the replication slot must be dropped from the **primary** site's database as follows:
1. On the **primary** site's database node, start a PostgreSQL console session:
```shell
sudo gitlab-psql
```
{{< alert type="note" >}}
Using `gitlab-rails dbconsole` does not work, because managing replication slots requires superuser permissions.
{{< /alert >}}
1. Find the name of the relevant replication slot. This is the slot that is specified with `--slot-name` when running the replicate command: `gitlab-ctl replicate-geo-database`.
```sql
SELECT * FROM pg_replication_slots;
```
1. Remove the replication slot for the **secondary** site:
```sql
SELECT pg_drop_replication_slot('<name_of_slot>');
```
|
https://docs.gitlab.com/administration/geo/geo_validation_tests
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/geo_validation_tests.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
geo_validation_tests.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
This document was moved to [another location](../../../development/geo/geo_validation_tests.md).
<!-- This redirect file can be deleted after 2025-11-03. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
---
redirect_to: ../../../development/geo/geo_validation_tests.md
remove_date: '2025-11-03'
breadcrumbs:
- doc
- administration
- geo
- replication
---
<!-- markdownlint-disable -->
This document was moved to [another location](../../../development/geo/geo_validation_tests.md).
<!-- This redirect file can be deleted after 2025-11-03. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
https://docs.gitlab.com/administration/geo/datatypes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/datatypes.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
datatypes.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Supported Geo data types
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
A Geo data type is a specific class of data that is required by one or more GitLab features to
store relevant information.
To replicate data produced by these features with Geo, we use several strategies to access, transfer, and verify them.
## Data types
We distinguish between the following different data types:
- [Git repositories](#git-repositories)
- [Container repositories](#container-repositories)
- [Blobs](#blobs)
- [Databases](#databases)
See the list below of each feature or component we replicate, its corresponding data type, replication, and
verification methods:
| Type | Feature / component | Replication method | Verification method |
|:---------------------|:------------------------------------------------|:---------------------------------------------|:------------------------------|
| Database | Application data in PostgreSQL | Native | Native |
| Database | Redis | Not applicable <sup>1</sup> | Not applicable |
| Database | Advanced search (Elasticsearch or OpenSearch) | Native | Native |
| Database | Exact code search (Zoekt) | Native | Native |
| Database | SSH public keys | PostgreSQL Replication | PostgreSQL Replication |
| Git | Project repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project wiki repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project designs repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project Snippets | Geo with Gitaly | Gitaly Checksum |
| Git | Personal Snippets | Geo with Gitaly | Gitaly Checksum |
| Git | Group wiki repository | Geo with Gitaly | Gitaly Checksum |
| Blob | User uploads _(file system)_ | Geo with API | SHA256 checksum |
| Blob | User uploads _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | LFS objects _(file system)_ | Geo with API | SHA256 checksum |
| Blob | LFS objects _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | CI job artifacts _(file system)_ | Geo with API | SHA256 checksum |
| Blob | CI job artifacts _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Archived CI build traces _(file system)_ | Geo with API | Not implemented |
| Blob | Archived CI build traces _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Container registry _(file system)_ | Geo with API/Docker API | SHA256 checksum |
| Blob | Container registry _(object storage)_ | Geo with API/Managed/Docker API <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Package registry _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Package registry _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Terraform Module Registry _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Terraform Module Registry _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Versioned Terraform State _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Versioned Terraform State _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | External merge request diffs _(file system)_ | Geo with API | SHA256 checksum |
| Blob | External merge request diffs _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Pipeline artifacts _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Pipeline artifacts _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Pages _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Pages _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | CI Secure Files _(file system)_ | Geo with API | SHA256 checksum |
| Blob | CI Secure Files _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Incident Metric Images _(file system)_ | Geo with API/Managed | SHA256 checksum |
| Blob | Incident Metric Images _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Alert Metric Images _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Alert Metric Images _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Dependency Proxy Images _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Dependency Proxy Images _(object storage)_ | Geo with API/managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Container Repository | Container registry _(file system)_ | Geo with API/Docker API | SHA256 checksum |
| Container Repository | Container registry _(object storage)_ | Geo with API/Managed/Docker API <sup>2</sup> | SHA256 checksum <sup>3</sup> |
**Footnotes**:
1. Redis replication can be used as part of HA with Redis sentinel. It's not used between Geo sites.
1. Object storage replication can be performed by Geo or by your object storage provider/appliance
native replication feature.
1. Object Storage verification is behind a [feature flag](../../feature_flags/_index.md), `geo_object_storage_verification`, [introduced in 16.4](https://gitlab.com/groups/gitlab-org/-/epics/8056) and enabled by default. It uses a checksum of the file size to verify the files.
### Git repositories
A GitLab instance can have one or more repository shards. Each shard has a Gitaly instance that
is responsible for allowing access and operations on the locally stored Git repositories. It can run
on a machine:
- With a single disk.
- With multiple disks mounted as a single mount-point (like with a RAID array).
- Using LVM.
GitLab does not require a special file system and can work with a mounted Storage Appliance. However, there can be
performance limitations and consistency issues when using a remote file system.
Geo triggers garbage collection in Gitaly to deduplicate forked repositories on Geo secondary sites.
The Gitaly gRPC API does the communication, with three possible ways of synchronization:
- Using regular Git clone/fetch from one Geo site to another (with special authentication).
- Using repository snapshots (for when the first method fails or repository is corrupt).
- Manual trigger from the **Admin** area (combines the other listed possible ways).
Each project can have at most 3 different repositories:
- A project repository, where the source code is stored.
- A wiki repository, where the wiki content is stored.
- A design repository, where design artifacts are indexed (assets are actually in LFS).
They all live in the same shard and share the same base name with a `-wiki` and `-design` suffix
for Wiki and Design Repository cases.
Besides that, there are snippet repositories. They can be connected to a project or to some specific user.
Both types are synced to a secondary site.
### Container repositories
Container repositories are stored in the container registry. They are a
GitLab-specific concept built on top of a container registry as the datastore.
### Blobs
GitLab stores files and blobs such as Issue attachments or LFS objects into either:
- The file system in a specific location.
- An [Object Storage](../../object_storage.md) solution. Object Storage solutions can be:
- Cloud based like Amazon S3 and Google Cloud Storage.
- Hosted by you (like MinIO).
- A Storage Appliance that exposes an Object Storage-compatible API.
When using the file system store instead of Object Storage, use network mounted file systems
to run GitLab when using more than one node.
With respect to replication and verification:
- We transfer files and blobs using an internal API request.
- With Object Storage, you can either:
- Use a cloud provider replication functionality.
- Have GitLab replicate it for you.
### Databases
GitLab relies on data stored in multiple databases, for different use-cases.
PostgreSQL is the single point of truth for user-generated content in the Web interface, like issues content, comments
as well as permissions and credentials.
PostgreSQL can also hold some level of cached data like HTML-rendered Markdown and cached merge-requests diff.
This can also be configured to be offloaded to object storage.
We use PostgreSQL's own replication functionality to replicate data from the **primary** to **secondary** sites.
We use Redis both as a cache store and to hold persistent data for our background jobs system. Because both
use-cases have data that are exclusive to the same Geo site, we don't replicate it between sites.
Elasticsearch is an optional database for advanced search. It can improve search
in both source-code level, and user generated content in issues, merge requests, and discussions.
Elasticsearch is not supported in Geo.
## Replicated data types
### Replicated data types behind a feature flag
{{< history >}}
- They're deployed behind a feature flag, enabled by default.
- They're enabled on GitLab.com.
- They can't be enabled or disabled per-project.
- They are recommended for production use.
- For a GitLab Self-Managed instance, GitLab administrators can opt to [disable them](#enable-or-disable-replication-for-some-data-types).
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
{{< /alert >}}
#### Enable or disable replication (for some data types)
Replication for some data types are released behind feature flags that are **enabled by default**.
[GitLab administrators with access to the GitLab Rails console](../../feature_flags/_index.md) can opt to disable it for your instance. You can find feature flag names of each of those data types in the notes column of the table below.
To disable, such as for package file replication:
```ruby
Feature.disable(:geo_package_file_replication)
```
To enable, such as for package file replication:
```ruby
Feature.enable(:geo_package_file_replication)
```
{{< alert type="warning" >}}
Features not on this list, or with **No** in the **Replicated** column,
are not replicated to a **secondary** site. Failing over without manually
replicating data from those features causes the data to be **lost**.
To use those features on a **secondary** site, or to execute a failover
successfully, you must replicate their data using some other means.
{{< /alert >}}
| Feature | Replicated (added in GitLab version) | Verified (added in GitLab version) | GitLab-managed object storage replication (added in GitLab version) | GitLab-managed object storage verification (added in GitLab version) | Notes |
|:----------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------|:------------------------------------------------------------------------------|:--------------------------------------------------------------------------------|:--------------------------------------------------------------------------------|:------|
| [Application data in PostgreSQL](../../postgresql/_index.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [Project repository](../../../user/project/repository/_index.md) | **Yes** (10.2) | **Yes** (10.7) | Not applicable | Not applicable | Migrated to self-service framework in 16.2. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.<br /><br />Behind feature flag `geo_project_repository_replication`, enabled by default in (16.3).<br /><br /> All projects, including [archived projects](../../../user/project/working_with_projects.md#archive-a-project), are replicated. |
| [Project wiki repository](../../../user/project/wiki/_index.md) | **Yes** (10.2)<sup>2</sup> | **Yes** (10.7)<sup>2</sup> | Not applicable | Not applicable | Migrated to self-service framework in 15.11. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.<br /><br />Behind feature flag `geo_project_wiki_repository_replication`, enabled by default in (15.11). |
| [Group wiki repository](../../../user/project/wiki/group.md) | [**Yes** (13.10)](https://gitlab.com/gitlab-org/gitlab/-/issues/208147) | [**Yes** (16.3)](https://gitlab.com/gitlab-org/gitlab/-/issues/323897) | Not applicable | Not applicable | Behind feature flag `geo_group_wiki_repository_replication`, enabled by default. |
| [User uploads](../../uploads.md) | **Yes** (10.2) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_upload_replication`, enabled by default. Verification was behind the feature flag `geo_upload_verification`, removed in 14.8. |
| [LFS objects](../../lfs/_index.md) | **Yes** (10.2) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | GitLab versions 11.11.x and 12.0.x are affected by [a bug that prevents any new LFS objects from replicating](https://gitlab.com/gitlab-org/gitlab/-/issues/32696).<br /><br />Replication is behind the feature flag `geo_lfs_object_replication`, enabled by default. Verification was behind the feature flag `geo_lfs_object_verification`, removed in 14.7. |
| [Personal Snippets](../../../user/snippets.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [Project Snippets](../../../user/snippets.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [CI job artifacts](../../../ci/jobs/job_artifacts.md) | **Yes** (10.4) | **Yes** (14.10) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification is behind the feature flag `geo_job_artifact_replication`, enabled by default in 14.10. |
| [Pipeline artifacts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/ci/pipeline_artifact.rb) | [**Yes** (13.11)](https://gitlab.com/gitlab-org/gitlab/-/issues/238464) | [**Yes** (13.11)](https://gitlab.com/gitlab-org/gitlab/-/issues/238464) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Persists additional artifacts after a pipeline completes. |
| [CI Secure Files](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/ci/secure_file.rb) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification is behind the feature flag `geo_ci_secure_file_replication`, enabled by default in 15.3. |
| [Container registry](../../packages/container_registry.md) | **Yes** (12.3)<sup>1</sup> | **Yes** (15.10) | **Yes** (12.3)<sup>1</sup> | **Yes** (15.10) | See [instructions](container_registry.md) to set up the container registry replication. |
| [Terraform Module Registry](../../../user/packages/terraform_module_registry/_index.md) | **Yes** (14.0) | **Yes** (14.0) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_package_file_replication`, enabled by default. |
| [Project designs repository](../../../user/project/issues/design_management.md) | **Yes** (12.7) | **Yes** (16.1) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Designs also require replication of LFS objects and Uploads. |
| [Package registry](../../../user/packages/package_registry/_index.md) | **Yes** (13.2) | **Yes** (13.10) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_package_file_replication`, enabled by default. |
| [Versioned Terraform State](../../terraform_state.md) | **Yes** (13.5) | **Yes** (13.12) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_terraform_state_version_replication`, enabled by default. Verification was behind the feature flag `geo_terraform_state_version_verification`, which was removed in 14.0. |
| [External merge request diffs](../../merge_request_diffs.md) | **Yes** (13.5) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_merge_request_diff_replication`, enabled by default. Verification was behind the feature flag `geo_merge_request_diff_verification`, removed in 14.7. |
| [Versioned Snippets](../../../user/snippets.md#versioned-snippets) | [**Yes** (13.7)](https://gitlab.com/groups/gitlab-org/-/epics/2809) | [**Yes** (14.2)](https://gitlab.com/groups/gitlab-org/-/epics/2810) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification was implemented behind the feature flag `geo_snippet_repository_verification` in 13.11, and the feature flag was removed in 14.2. |
| [Pages](../../pages/_index.md) | [**Yes** (14.3)](https://gitlab.com/groups/gitlab-org/-/epics/589) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_pages_deployment_replication`, enabled by default. Verification was behind the feature flag `geo_pages_deployment_verification`, removed in 14.7. |
| [Project-level CI Secure Files](../../../ci/secure_files/_index.md) | **Yes** (15.3) | **Yes** (15.3) | **Yes** (15.3) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | |
| [Incident Metric Images](../../../operations/incident_management/incidents.md#metrics) | **Yes** (15.5) | **Yes** (15.5) | **Yes** (15.5) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication/Verification is handled via the Uploads data type. |
| [Alert Metric Images](../../../operations/incident_management/alerts.md#metrics-tab) | **Yes** (15.5) | **Yes** (15.5) | **Yes** (15.5) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication/Verification is handled via the Uploads data type. |
| [Server-side Git hooks](../../server_hooks.md) | [Not planned](https://gitlab.com/groups/gitlab-org/-/epics/1867) | No | Not applicable | Not applicable | Not planned because of current implementation complexity, low customer interest, and availability of alternatives to hooks. |
| [Elasticsearch](../../../integration/advanced_search/elasticsearch.md) | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/1186) | No | No | No | Not planned because further product discovery is required and Elasticsearch (ES) clusters can be rebuilt. Secondaries use the same ES cluster as the primary. |
| [Dependency Proxy Images](../../../user/packages/dependency_proxy/_index.md) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | |
| [Vulnerability Export](../../../user/application_security/vulnerability_report/_index.md#exporting) | [Not planned](https://gitlab.com/groups/gitlab-org/-/epics/3111) | No | No | No | Not planned because they are ephemeral and sensitive information. They can be regenerated on demand. |
| Packages NPM metadata cache | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/408278) | No | No | No | Not planned because it would not notably improve disaster recovery capabilities nor response times at secondary sites. |
| Packages Debian GroupComponentFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556945) | No | No | No | |
| Packages Debian ProjectComponentFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/333611) | No | No | No | |
| Packages Debian GroupDistribution | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556947) | No | No | No | |
| Packages Debian ProjectDistribution | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556946) | No | No | No | |
| Packages RPM RepositoryFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/379055) | No | No | No | |
| Packages NuGet Symbol | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/422929) | No | No | No | |
| VirtualRegistries Maven Cache Entry | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/473033) | No | No | No | |
| SBOM Vulnerability Scan Data | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/398199) | No | No | No | Not planned because data is temporary and has a short lifespan with limited impact on disaster recovery capabilities at secondary sites. |
**Footnotes**:
1. Migrated to self-service framework in 15.5. See GitLab issue [#337436](https://gitlab.com/gitlab-org/gitlab/-/issues/337436) for more details.
1. Migrated to self-service framework in 15.11. Behind feature flag `geo_project_wiki_repository_replication`, enabled by default. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.
1. Verification of files stored in object storage was [introduced](https://gitlab.com/groups/gitlab-org/-/epics/8056) in GitLab 16.4 [with a feature flag](../../feature_flags/_index.md) named `geo_object_storage_verification`, enabled by default.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Supported Geo data types
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
A Geo data type is a specific class of data that is required by one or more GitLab features to
store relevant information.
To replicate data produced by these features with Geo, we use several strategies to access, transfer, and verify them.
## Data types
We distinguish between the following different data types:
- [Git repositories](#git-repositories)
- [Container repositories](#container-repositories)
- [Blobs](#blobs)
- [Databases](#databases)
See the list below of each feature or component we replicate, its corresponding data type, replication, and
verification methods:
| Type | Feature / component | Replication method | Verification method |
|:---------------------|:------------------------------------------------|:---------------------------------------------|:------------------------------|
| Database | Application data in PostgreSQL | Native | Native |
| Database | Redis | Not applicable <sup>1</sup> | Not applicable |
| Database | Advanced search (Elasticsearch or OpenSearch) | Native | Native |
| Database | Exact code search (Zoekt) | Native | Native |
| Database | SSH public keys | PostgreSQL Replication | PostgreSQL Replication |
| Git | Project repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project wiki repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project designs repository | Geo with Gitaly | Gitaly Checksum |
| Git | Project Snippets | Geo with Gitaly | Gitaly Checksum |
| Git | Personal Snippets | Geo with Gitaly | Gitaly Checksum |
| Git | Group wiki repository | Geo with Gitaly | Gitaly Checksum |
| Blob | User uploads _(file system)_ | Geo with API | SHA256 checksum |
| Blob | User uploads _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | LFS objects _(file system)_ | Geo with API | SHA256 checksum |
| Blob | LFS objects _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | CI job artifacts _(file system)_ | Geo with API | SHA256 checksum |
| Blob | CI job artifacts _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Archived CI build traces _(file system)_ | Geo with API | Not implemented |
| Blob | Archived CI build traces _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Container registry _(file system)_ | Geo with API/Docker API | SHA256 checksum |
| Blob | Container registry _(object storage)_ | Geo with API/Managed/Docker API <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Package registry _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Package registry _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Terraform Module Registry _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Terraform Module Registry _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Versioned Terraform State _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Versioned Terraform State _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | External merge request diffs _(file system)_ | Geo with API | SHA256 checksum |
| Blob | External merge request diffs _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Pipeline artifacts _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Pipeline artifacts _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Pages _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Pages _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | CI Secure Files _(file system)_ | Geo with API | SHA256 checksum |
| Blob | CI Secure Files _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Incident Metric Images _(file system)_ | Geo with API/Managed | SHA256 checksum |
| Blob | Incident Metric Images _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Alert Metric Images _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Alert Metric Images _(object storage)_ | Geo with API/Managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Blob | Dependency Proxy Images _(file system)_ | Geo with API | SHA256 checksum |
| Blob | Dependency Proxy Images _(object storage)_ | Geo with API/managed <sup>2</sup> | SHA256 checksum <sup>3</sup> |
| Container Repository | Container registry _(file system)_ | Geo with API/Docker API | SHA256 checksum |
| Container Repository | Container registry _(object storage)_ | Geo with API/Managed/Docker API <sup>2</sup> | SHA256 checksum <sup>3</sup> |
**Footnotes**:
1. Redis replication can be used as part of HA with Redis sentinel. It's not used between Geo sites.
1. Object storage replication can be performed by Geo or by your object storage provider/appliance
native replication feature.
1. Object Storage verification is behind a [feature flag](../../feature_flags/_index.md), `geo_object_storage_verification`, [introduced in 16.4](https://gitlab.com/groups/gitlab-org/-/epics/8056) and enabled by default. It uses a checksum of the file size to verify the files.
### Git repositories
A GitLab instance can have one or more repository shards. Each shard has a Gitaly instance that
is responsible for allowing access and operations on the locally stored Git repositories. It can run
on a machine:
- With a single disk.
- With multiple disks mounted as a single mount-point (like with a RAID array).
- Using LVM.
GitLab does not require a special file system and can work with a mounted Storage Appliance. However, there can be
performance limitations and consistency issues when using a remote file system.
Geo triggers garbage collection in Gitaly to deduplicate forked repositories on Geo secondary sites.
The Gitaly gRPC API does the communication, with three possible ways of synchronization:
- Using regular Git clone/fetch from one Geo site to another (with special authentication).
- Using repository snapshots (for when the first method fails or repository is corrupt).
- Manual trigger from the **Admin** area (combines the other listed possible ways).
Each project can have at most 3 different repositories:
- A project repository, where the source code is stored.
- A wiki repository, where the wiki content is stored.
- A design repository, where design artifacts are indexed (assets are actually in LFS).
They all live in the same shard and share the same base name with a `-wiki` and `-design` suffix
for Wiki and Design Repository cases.
Besides that, there are snippet repositories. They can be connected to a project or to some specific user.
Both types are synced to a secondary site.
### Container repositories
Container repositories are stored in the container registry. They are a
GitLab-specific concept built on top of a container registry as the datastore.
### Blobs
GitLab stores files and blobs such as Issue attachments or LFS objects into either:
- The file system in a specific location.
- An [Object Storage](../../object_storage.md) solution. Object Storage solutions can be:
- Cloud based like Amazon S3 and Google Cloud Storage.
- Hosted by you (like MinIO).
- A Storage Appliance that exposes an Object Storage-compatible API.
When using the file system store instead of Object Storage, use network mounted file systems
to run GitLab when using more than one node.
With respect to replication and verification:
- We transfer files and blobs using an internal API request.
- With Object Storage, you can either:
- Use a cloud provider replication functionality.
- Have GitLab replicate it for you.
### Databases
GitLab relies on data stored in multiple databases, for different use-cases.
PostgreSQL is the single point of truth for user-generated content in the Web interface, like issues content, comments
as well as permissions and credentials.
PostgreSQL can also hold some level of cached data like HTML-rendered Markdown and cached merge-requests diff.
This can also be configured to be offloaded to object storage.
We use PostgreSQL's own replication functionality to replicate data from the **primary** to **secondary** sites.
We use Redis both as a cache store and to hold persistent data for our background jobs system. Because both
use-cases have data that are exclusive to the same Geo site, we don't replicate it between sites.
Elasticsearch is an optional database for advanced search. It can improve search
in both source-code level, and user generated content in issues, merge requests, and discussions.
Elasticsearch is not supported in Geo.
## Replicated data types
### Replicated data types behind a feature flag
{{< history >}}
- They're deployed behind a feature flag, enabled by default.
- They're enabled on GitLab.com.
- They can't be enabled or disabled per-project.
- They are recommended for production use.
- For a GitLab Self-Managed instance, GitLab administrators can opt to [disable them](#enable-or-disable-replication-for-some-data-types).
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
{{< /alert >}}
#### Enable or disable replication (for some data types)
Replication for some data types are released behind feature flags that are **enabled by default**.
[GitLab administrators with access to the GitLab Rails console](../../feature_flags/_index.md) can opt to disable it for your instance. You can find feature flag names of each of those data types in the notes column of the table below.
To disable, such as for package file replication:
```ruby
Feature.disable(:geo_package_file_replication)
```
To enable, such as for package file replication:
```ruby
Feature.enable(:geo_package_file_replication)
```
{{< alert type="warning" >}}
Features not on this list, or with **No** in the **Replicated** column,
are not replicated to a **secondary** site. Failing over without manually
replicating data from those features causes the data to be **lost**.
To use those features on a **secondary** site, or to execute a failover
successfully, you must replicate their data using some other means.
{{< /alert >}}
| Feature | Replicated (added in GitLab version) | Verified (added in GitLab version) | GitLab-managed object storage replication (added in GitLab version) | GitLab-managed object storage verification (added in GitLab version) | Notes |
|:----------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------|:------------------------------------------------------------------------------|:--------------------------------------------------------------------------------|:--------------------------------------------------------------------------------|:------|
| [Application data in PostgreSQL](../../postgresql/_index.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [Project repository](../../../user/project/repository/_index.md) | **Yes** (10.2) | **Yes** (10.7) | Not applicable | Not applicable | Migrated to self-service framework in 16.2. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.<br /><br />Behind feature flag `geo_project_repository_replication`, enabled by default in (16.3).<br /><br /> All projects, including [archived projects](../../../user/project/working_with_projects.md#archive-a-project), are replicated. |
| [Project wiki repository](../../../user/project/wiki/_index.md) | **Yes** (10.2)<sup>2</sup> | **Yes** (10.7)<sup>2</sup> | Not applicable | Not applicable | Migrated to self-service framework in 15.11. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.<br /><br />Behind feature flag `geo_project_wiki_repository_replication`, enabled by default in (15.11). |
| [Group wiki repository](../../../user/project/wiki/group.md) | [**Yes** (13.10)](https://gitlab.com/gitlab-org/gitlab/-/issues/208147) | [**Yes** (16.3)](https://gitlab.com/gitlab-org/gitlab/-/issues/323897) | Not applicable | Not applicable | Behind feature flag `geo_group_wiki_repository_replication`, enabled by default. |
| [User uploads](../../uploads.md) | **Yes** (10.2) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_upload_replication`, enabled by default. Verification was behind the feature flag `geo_upload_verification`, removed in 14.8. |
| [LFS objects](../../lfs/_index.md) | **Yes** (10.2) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | GitLab versions 11.11.x and 12.0.x are affected by [a bug that prevents any new LFS objects from replicating](https://gitlab.com/gitlab-org/gitlab/-/issues/32696).<br /><br />Replication is behind the feature flag `geo_lfs_object_replication`, enabled by default. Verification was behind the feature flag `geo_lfs_object_verification`, removed in 14.7. |
| [Personal Snippets](../../../user/snippets.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [Project Snippets](../../../user/snippets.md) | **Yes** (10.2) | **Yes** (10.2) | Not applicable | Not applicable | |
| [CI job artifacts](../../../ci/jobs/job_artifacts.md) | **Yes** (10.4) | **Yes** (14.10) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification is behind the feature flag `geo_job_artifact_replication`, enabled by default in 14.10. |
| [Pipeline artifacts](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/ci/pipeline_artifact.rb) | [**Yes** (13.11)](https://gitlab.com/gitlab-org/gitlab/-/issues/238464) | [**Yes** (13.11)](https://gitlab.com/gitlab-org/gitlab/-/issues/238464) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Persists additional artifacts after a pipeline completes. |
| [CI Secure Files](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/models/ci/secure_file.rb) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (15.3)](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91430) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification is behind the feature flag `geo_ci_secure_file_replication`, enabled by default in 15.3. |
| [Container registry](../../packages/container_registry.md) | **Yes** (12.3)<sup>1</sup> | **Yes** (15.10) | **Yes** (12.3)<sup>1</sup> | **Yes** (15.10) | See [instructions](container_registry.md) to set up the container registry replication. |
| [Terraform Module Registry](../../../user/packages/terraform_module_registry/_index.md) | **Yes** (14.0) | **Yes** (14.0) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_package_file_replication`, enabled by default. |
| [Project designs repository](../../../user/project/issues/design_management.md) | **Yes** (12.7) | **Yes** (16.1) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Designs also require replication of LFS objects and Uploads. |
| [Package registry](../../../user/packages/package_registry/_index.md) | **Yes** (13.2) | **Yes** (13.10) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_package_file_replication`, enabled by default. |
| [Versioned Terraform State](../../terraform_state.md) | **Yes** (13.5) | **Yes** (13.12) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_terraform_state_version_replication`, enabled by default. Verification was behind the feature flag `geo_terraform_state_version_verification`, which was removed in 14.0. |
| [External merge request diffs](../../merge_request_diffs.md) | **Yes** (13.5) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication is behind the feature flag `geo_merge_request_diff_replication`, enabled by default. Verification was behind the feature flag `geo_merge_request_diff_verification`, removed in 14.7. |
| [Versioned Snippets](../../../user/snippets.md#versioned-snippets) | [**Yes** (13.7)](https://gitlab.com/groups/gitlab-org/-/epics/2809) | [**Yes** (14.2)](https://gitlab.com/groups/gitlab-org/-/epics/2810) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Verification was implemented behind the feature flag `geo_snippet_repository_verification` in 13.11, and the feature flag was removed in 14.2. |
| [Pages](../../pages/_index.md) | [**Yes** (14.3)](https://gitlab.com/groups/gitlab-org/-/epics/589) | **Yes** (14.6) | [**Yes** (15.1)](https://gitlab.com/groups/gitlab-org/-/epics/5551) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Behind feature flag `geo_pages_deployment_replication`, enabled by default. Verification was behind the feature flag `geo_pages_deployment_verification`, removed in 14.7. |
| [Project-level CI Secure Files](../../../ci/secure_files/_index.md) | **Yes** (15.3) | **Yes** (15.3) | **Yes** (15.3) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | |
| [Incident Metric Images](../../../operations/incident_management/incidents.md#metrics) | **Yes** (15.5) | **Yes** (15.5) | **Yes** (15.5) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication/Verification is handled via the Uploads data type. |
| [Alert Metric Images](../../../operations/incident_management/alerts.md#metrics-tab) | **Yes** (15.5) | **Yes** (15.5) | **Yes** (15.5) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | Replication/Verification is handled via the Uploads data type. |
| [Server-side Git hooks](../../server_hooks.md) | [Not planned](https://gitlab.com/groups/gitlab-org/-/epics/1867) | No | Not applicable | Not applicable | Not planned because of current implementation complexity, low customer interest, and availability of alternatives to hooks. |
| [Elasticsearch](../../../integration/advanced_search/elasticsearch.md) | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/1186) | No | No | No | Not planned because further product discovery is required and Elasticsearch (ES) clusters can be rebuilt. Secondaries use the same ES cluster as the primary. |
| [Dependency Proxy Images](../../../user/packages/dependency_proxy/_index.md) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (15.7)](https://gitlab.com/groups/gitlab-org/-/epics/8833) | [**Yes** (16.4)<sup>3</sup>](https://gitlab.com/groups/gitlab-org/-/epics/8056) | |
| [Vulnerability Export](../../../user/application_security/vulnerability_report/_index.md#exporting) | [Not planned](https://gitlab.com/groups/gitlab-org/-/epics/3111) | No | No | No | Not planned because they are ephemeral and sensitive information. They can be regenerated on demand. |
| Packages NPM metadata cache | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/408278) | No | No | No | Not planned because it would not notably improve disaster recovery capabilities nor response times at secondary sites. |
| Packages Debian GroupComponentFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556945) | No | No | No | |
| Packages Debian ProjectComponentFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/333611) | No | No | No | |
| Packages Debian GroupDistribution | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556947) | No | No | No | |
| Packages Debian ProjectDistribution | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/556946) | No | No | No | |
| Packages RPM RepositoryFile | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/379055) | No | No | No | |
| Packages NuGet Symbol | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/422929) | No | No | No | |
| VirtualRegistries Maven Cache Entry | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/473033) | No | No | No | |
| SBOM Vulnerability Scan Data | [Not planned](https://gitlab.com/gitlab-org/gitlab/-/issues/398199) | No | No | No | Not planned because data is temporary and has a short lifespan with limited impact on disaster recovery capabilities at secondary sites. |
**Footnotes**:
1. Migrated to self-service framework in 15.5. See GitLab issue [#337436](https://gitlab.com/gitlab-org/gitlab/-/issues/337436) for more details.
1. Migrated to self-service framework in 15.11. Behind feature flag `geo_project_wiki_repository_replication`, enabled by default. See GitLab issue [#367925](https://gitlab.com/gitlab-org/gitlab/-/issues/367925) for more details.
1. Verification of files stored in object storage was [introduced](https://gitlab.com/groups/gitlab-org/-/epics/8056) in GitLab 16.4 [with a feature flag](../../feature_flags/_index.md) named `geo_object_storage_verification`, enabled by default.
|
https://docs.gitlab.com/administration/geo/configuration
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/configuration.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
configuration.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configure a new **secondary** site
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
This is the final step in setting up a **secondary** Geo site. Stages of the
setup process must be completed in the documented order.
If not, [complete all prior stages](../setup/_index.md#using-linux-package-installations) before proceeding.
{{< /alert >}}
The basic steps of configuring a **secondary** site are to:
1. Replicate required configurations between the **primary** and the **secondary** site.
1. Configure a tracking database on each **secondary** site.
1. Start GitLab on each **secondary** site.
This document focuses on the first item. You are encouraged to first read
through all the steps before executing them in your testing/production
environment.
Prerequisites for **both primary and secondary sites**:
- [Set up the database replication](../setup/database.md)
- [Configure fast lookup of authorized SSH keys](../../operations/fast_ssh_key_lookup.md)
{{< alert type="note" >}}
**Do not** set up any custom authentication for the **secondary** site. This is handled by the **primary** site.
Any change that requires access to the **Admin area** needs to be done in the
**primary** site because the **secondary** site is a read-only replica.
{{< /alert >}}
## Step 1. Manually replicate secret GitLab values
GitLab stores a number of secret values in the `/etc/gitlab/gitlab-secrets.json`
file which must be the same on all of a site's nodes. Until there is
a means of automatically replicating these between sites (see [issue #3789](https://gitlab.com/gitlab-org/gitlab/-/issues/3789)),
they must be manually replicated to **all nodes of the secondary site**.
1. SSH into a **Rails node on your primary** site, and execute the command below:
```shell
sudo cat /etc/gitlab/gitlab-secrets.json
```
This displays the secrets that need to be replicated, in JSON format.
1. SSH **into each node on your secondary Geo site** and login as the `root` user:
```shell
sudo -i
```
1. Make a backup of any existing secrets:
```shell
mv /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.`date +%F`
```
1. Copy `/etc/gitlab/gitlab-secrets.json` from the **Rails node on your primary** site to **each node on your secondary** site, or
copy-and-paste the file contents between nodes:
```shell
sudo editor /etc/gitlab/gitlab-secrets.json
# paste the output of the `cat` command you ran on the primary
# save and exit
```
1. Ensure the file permissions are correct:
```shell
chown root:root /etc/gitlab/gitlab-secrets.json
chmod 0600 /etc/gitlab/gitlab-secrets.json
```
1. Reconfigure **each Rails, Sidekiq and Gitaly nodes on your secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
gitlab-ctl restart
```
## Step 2. Manually replicate the **primary** site's SSH host keys
GitLab integrates with the system-installed SSH daemon, designating a user
(typically named `git`) through which all access requests are handled.
In a [Disaster Recovery](../disaster_recovery/_index.md) situation, GitLab system
administrators promote a **secondary** site to the **primary** site. DNS records for the
**primary** domain should also be updated to point to the new **primary** site
(previously a **secondary** site). Doing so avoids the need to update Git remotes and API URLs.
This causes all SSH requests to the newly promoted **primary** site to
fail due to SSH host key mismatch. To prevent this, the primary SSH host
keys must be manually replicated to the **secondary** site.
The SSH host key path depends on the used software:
- If you use OpenSSH, the path is `/etc/ssh`.
- If you use [`gitlab-sshd`](../../operations/gitlab_sshd.md), the path is `/var/opt/gitlab/gitlab-sshd`.
In the following steps, replace `<ssh_host_key_path>` with the one you're using:
1. SSH into **each Rails node on your secondary** site and sign in as the `root` user:
```shell
sudo -i
```
1. Make a backup of any existing SSH host keys:
```shell
find <ssh_host_key_path> -iname 'ssh_host_*' -exec cp {} {}.backup.`date +%F` \;
```
1. Copy the SSH host keys from the **primary** site:
If you can access one of the **nodes on your primary** site serving SSH traffic (usually, the main GitLab Rails application nodes) using the **root** user:
```shell
# Run this from the secondary site, change `<primary_site_fqdn>` for the IP or FQDN of the server
scp root@<primary_node_fqdn>:<ssh_host_key_path>/ssh_host_*_key* <ssh_host_key_path>
```
If you only have access through a user with `sudo` privileges:
```shell
# Run this from the node on your primary site:
sudo tar --transform 's/.*\///g' -zcvf ~/geo-host-key.tar.gz <ssh_host_key_path>/ssh_host_*_key*
# Run this on each node on your secondary site:
scp <user_with_sudo>@<primary_site_fqdn>:geo-host-key.tar.gz .
tar zxvf ~/geo-host-key.tar.gz -C <ssh_host_key_path>
```
1. On **each Rails node on your secondary** site, ensure the file permissions are correct:
```shell
chown root:root <ssh_host_key_path>/ssh_host_*_key*
chmod 0600 <ssh_host_key_path>/ssh_host_*_key
```
1. To verify key fingerprint matches, execute the following command on both primary and secondary nodes on each site:
```shell
for file in <ssh_host_key_path>/ssh_host_*_key; do ssh-keygen -lf $file; done
```
You should get an output similar to this one and they should be identical on both nodes:
```shell
1024 SHA256:FEZX2jQa2bcsd/fn/uxBzxhKdx4Imc4raXrHwsbtP0M root@serverhostname (DSA)
256 SHA256:uw98R35Uf+fYEQ/UnJD9Br4NXUFPv7JAUln5uHlgSeY root@serverhostname (ECDSA)
256 SHA256:sqOUWcraZQKd89y/QQv/iynPTOGQxcOTIXU/LsoPmnM root@serverhostname (ED25519)
2048 SHA256:qwa+rgir2Oy86QI+PZi/QVR+MSmrdrpsuH7YyKknC+s root@serverhostname (RSA)
```
1. Verify that you have the correct public keys for the existing private keys:
```shell
# This will print the fingerprint for private keys:
for file in <ssh_host_key_path>/ssh_host_*_key; do ssh-keygen -lf $file; done
# This will print the fingerprint for public keys:
for file in <ssh_host_key_path>/ssh_host_*_key.pub; do ssh-keygen -lf $file; done
```
{{< alert type="note" >}}
The output for private keys and public keys command should generate the same fingerprint.
{{< /alert >}}
1. Restart either `sshd` for OpenSSH or the `gitlab-sshd` service on **each Rails node on your secondary** site:
- For OpenSSH:
```shell
# Debian or Ubuntu installations
sudo service ssh reload
# CentOS installations
sudo service sshd reload
```
- For `gitlab-sshd`:
```shell
sudo gitlab-ctl restart gitlab-sshd
```
1. Verify SSH is still functional.
SSH into your GitLab **secondary** server in a new terminal. If you are unable to connect,
verify the permissions are correct according to the previous steps.
## Step 3. Add the **secondary** site
1. SSH into **each Rails and Sidekiq node on your secondary** site and login as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb` and add a **unique** name for your site. You need this in the next steps:
```ruby
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
```
1. Reconfigure **each Rails and Sidekiq node on your secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
```
1. Go to the primary node GitLab instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Geo** > **Sites**.
1. Select **Add site**.

1. In **Name**, enter the value for `gitlab_rails['geo_node_name']` in
`/etc/gitlab/gitlab.rb`. These values must always match **exactly**, character
for character.
1. In **External URL**, enter the value for `external_url` in `/etc/gitlab/gitlab.rb`. These
values must always match, but it doesn't matter if one ends with a `/` and
the other doesn't.
1. Optional. In **Internal URL (optional)**, enter an internal URL for the secondary site.
1. Optional. Select which groups or storage shards should be replicated by the
**secondary** site. Leave blank to replicate all. For more information, see
[selective synchronization](selective_synchronization.md).
1. Select **Save changes** to add the **secondary** site.
1. SSH into **each Rails, and Sidekiq node on your secondary** site and restart the services:
```shell
gitlab-ctl restart
```
Check if there are any common issues with your Geo setup by running:
```shell
gitlab-rake gitlab:geo:check
```
If any of the checks fail, check the [troubleshooting documentation](troubleshooting/_index.md).
1. SSH into a **Rails or Sidekiq server on your primary** site and login as root to verify the
**secondary** site is reachable or there are any common issues with your Geo setup:
```shell
gitlab-rake gitlab:geo:check
```
If any of the checks fail, check the [troubleshooting documentation](troubleshooting/_index.md).
After the **secondary** site is added to the Geo administration page and restarted,
the site automatically starts replicating missing data from the **primary** site
in a process known as **backfill**.
Meanwhile, the **primary** site starts to notify each **secondary** site of any changes, so
that the **secondary** site can act on those notifications immediately.
Be sure the secondary site is running and accessible. You can sign in to the
secondary site with the same credentials as were used with the primary site.
## Step 4. (Optional) Using custom certificates
You can safely skip this step if:
- Your **primary** site uses a public CA-issued HTTPS certificate.
- Your **primary** site only connects to external services with CA-issued (not self-signed) HTTPS certificates.
### Custom or self-signed certificate for inbound connections
If your GitLab Geo **primary** site uses a custom or [self-signed certificate to secure inbound HTTPS connections](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates), this can be either a single-domain or multi-domain certificate.
Install the correct certificate based on your certificate type:
- **Multi-domain certificate** that includes both primary and secondary site domains: Install the certificate at `/etc/gitlab/ssl` on all **Rails, Sidekiq, and Gitaly** nodes in the **secondary** site.
- **Single-domain certificate** where the certificates are specific to each Geo site domain: Generate a valid certificate for your **secondary** site's domain and install it at `/etc/gitlab/ssl` following [these instructions](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) on all **Rails, Sidekiq, and Gitaly** nodes in the **secondary** site.
### Connecting to external services that use custom certificates
A copy of the self-signed certificate for the external service needs to be added to the trust store on all the **primary** site's nodes that require access to the service.
For the **secondary** site to be able to access the same external services, these certificates must be added to the **secondary** site's trust store.
If your **primary** site is using a [custom or self-signed certificate for inbound HTTPS connections](#custom-or-self-signed-certificate-for-inbound-connections), the **primary** site's certificate needs to be added to the **secondary** site's trust store:
1. SSH into each **Rails, Sidekiq, and Gitaly node on your secondary** site and login as root:
```shell
sudo -i
```
1. Copy the trusted certs from the **primary** site:
If you can access one of the nodes on your **primary** site serving SSH traffic using the root user:
```shell
scp root@<primary_site_node_fqdn>:/etc/gitlab/trusted-certs/* /etc/gitlab/trusted-certs
```
If you only have access through a user with sudo privileges:
```shell
# Run this from the node on your primary site:
sudo tar --transform 's/.*\///g' -zcvf ~/geo-trusted-certs.tar.gz /etc/gitlab/trusted-certs/*
# Run this on each node on your secondary site:
scp <user_with_sudo>@<primary_site_node_fqdn>:geo-trusted-certs.tar.gz .
tar zxvf ~/geo-trusted-certs.tar.gz -C /etc/gitlab/trusted-certs
```
1. Reconfigure each updated **Rails, Sidekiq, and Gitaly node in your secondary** site:
```shell
sudo gitlab-ctl reconfigure
```
## Step 5. Enable Git access over HTTP/HTTPS and SSH
Geo synchronizes repositories over HTTP/HTTPS, and therefore requires this clone
method to be enabled. This is enabled by default, but if converting an existing site to Geo it should be checked:
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings** > **General**.
1. Expand **Visibility and access controls**.
1. If using Git over SSH, then:
1. Ensure "Enabled Git access protocols" is set to "Both SSH and HTTP(S)".
1. Follow the steps to configure
[fast lookup of authorized SSH keys in the database](../../operations/fast_ssh_key_lookup.md) on
**all primary and secondary** sites.
1. If not using Git over SSH, then set "Enabled Git access protocols" to "Only HTTP(S)".
## Step 6. Verify proper functioning of the **secondary** site
You can sign in to the **secondary** site with the same credentials you used with
the **primary** site. After you sign in:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Verify that it's correctly identified as a **secondary** Geo site, and that
Geo is enabled.
The initial replication may take some time. The status of the site or the 'backfill' may still in progress. You
can monitor the synchronization process on each Geo site from the **primary**
site's **Geo Sites** dashboard in your browser.

If your installation isn't working properly, check the
[troubleshooting document](troubleshooting/_index.md).
The two most obvious issues that can become apparent in the dashboard are:
1. Database replication not working well.
1. Instance to instance notification not working. In that case, it can be
something of the following:
- You are using a custom certificate or custom CA (see the [troubleshooting document](troubleshooting/_index.md)).
- The instance is firewalled (check your firewall rules).
Disabling a **secondary** site stops the synchronization process.
If repository storages are customized on the **primary** site for multiple
repository shards you must duplicate the same configuration on each **secondary** site.
Point your users to the [Using a Geo Site guide](usage.md).
Currently, this is what is synced:
- Git repositories.
- Wikis.
- LFS objects.
- Issues, merge requests, snippets, and comment attachments.
- Users, groups, and project avatars.
## Troubleshooting
See the [troubleshooting document](troubleshooting/_index.md).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Configure a new **secondary** site
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
This is the final step in setting up a **secondary** Geo site. Stages of the
setup process must be completed in the documented order.
If not, [complete all prior stages](../setup/_index.md#using-linux-package-installations) before proceeding.
{{< /alert >}}
The basic steps of configuring a **secondary** site are to:
1. Replicate required configurations between the **primary** and the **secondary** site.
1. Configure a tracking database on each **secondary** site.
1. Start GitLab on each **secondary** site.
This document focuses on the first item. You are encouraged to first read
through all the steps before executing them in your testing/production
environment.
Prerequisites for **both primary and secondary sites**:
- [Set up the database replication](../setup/database.md)
- [Configure fast lookup of authorized SSH keys](../../operations/fast_ssh_key_lookup.md)
{{< alert type="note" >}}
**Do not** set up any custom authentication for the **secondary** site. This is handled by the **primary** site.
Any change that requires access to the **Admin area** needs to be done in the
**primary** site because the **secondary** site is a read-only replica.
{{< /alert >}}
## Step 1. Manually replicate secret GitLab values
GitLab stores a number of secret values in the `/etc/gitlab/gitlab-secrets.json`
file which must be the same on all of a site's nodes. Until there is
a means of automatically replicating these between sites (see [issue #3789](https://gitlab.com/gitlab-org/gitlab/-/issues/3789)),
they must be manually replicated to **all nodes of the secondary site**.
1. SSH into a **Rails node on your primary** site, and execute the command below:
```shell
sudo cat /etc/gitlab/gitlab-secrets.json
```
This displays the secrets that need to be replicated, in JSON format.
1. SSH **into each node on your secondary Geo site** and login as the `root` user:
```shell
sudo -i
```
1. Make a backup of any existing secrets:
```shell
mv /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.`date +%F`
```
1. Copy `/etc/gitlab/gitlab-secrets.json` from the **Rails node on your primary** site to **each node on your secondary** site, or
copy-and-paste the file contents between nodes:
```shell
sudo editor /etc/gitlab/gitlab-secrets.json
# paste the output of the `cat` command you ran on the primary
# save and exit
```
1. Ensure the file permissions are correct:
```shell
chown root:root /etc/gitlab/gitlab-secrets.json
chmod 0600 /etc/gitlab/gitlab-secrets.json
```
1. Reconfigure **each Rails, Sidekiq and Gitaly nodes on your secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
gitlab-ctl restart
```
## Step 2. Manually replicate the **primary** site's SSH host keys
GitLab integrates with the system-installed SSH daemon, designating a user
(typically named `git`) through which all access requests are handled.
In a [Disaster Recovery](../disaster_recovery/_index.md) situation, GitLab system
administrators promote a **secondary** site to the **primary** site. DNS records for the
**primary** domain should also be updated to point to the new **primary** site
(previously a **secondary** site). Doing so avoids the need to update Git remotes and API URLs.
This causes all SSH requests to the newly promoted **primary** site to
fail due to SSH host key mismatch. To prevent this, the primary SSH host
keys must be manually replicated to the **secondary** site.
The SSH host key path depends on the used software:
- If you use OpenSSH, the path is `/etc/ssh`.
- If you use [`gitlab-sshd`](../../operations/gitlab_sshd.md), the path is `/var/opt/gitlab/gitlab-sshd`.
In the following steps, replace `<ssh_host_key_path>` with the one you're using:
1. SSH into **each Rails node on your secondary** site and sign in as the `root` user:
```shell
sudo -i
```
1. Make a backup of any existing SSH host keys:
```shell
find <ssh_host_key_path> -iname 'ssh_host_*' -exec cp {} {}.backup.`date +%F` \;
```
1. Copy the SSH host keys from the **primary** site:
If you can access one of the **nodes on your primary** site serving SSH traffic (usually, the main GitLab Rails application nodes) using the **root** user:
```shell
# Run this from the secondary site, change `<primary_site_fqdn>` for the IP or FQDN of the server
scp root@<primary_node_fqdn>:<ssh_host_key_path>/ssh_host_*_key* <ssh_host_key_path>
```
If you only have access through a user with `sudo` privileges:
```shell
# Run this from the node on your primary site:
sudo tar --transform 's/.*\///g' -zcvf ~/geo-host-key.tar.gz <ssh_host_key_path>/ssh_host_*_key*
# Run this on each node on your secondary site:
scp <user_with_sudo>@<primary_site_fqdn>:geo-host-key.tar.gz .
tar zxvf ~/geo-host-key.tar.gz -C <ssh_host_key_path>
```
1. On **each Rails node on your secondary** site, ensure the file permissions are correct:
```shell
chown root:root <ssh_host_key_path>/ssh_host_*_key*
chmod 0600 <ssh_host_key_path>/ssh_host_*_key
```
1. To verify key fingerprint matches, execute the following command on both primary and secondary nodes on each site:
```shell
for file in <ssh_host_key_path>/ssh_host_*_key; do ssh-keygen -lf $file; done
```
You should get an output similar to this one and they should be identical on both nodes:
```shell
1024 SHA256:FEZX2jQa2bcsd/fn/uxBzxhKdx4Imc4raXrHwsbtP0M root@serverhostname (DSA)
256 SHA256:uw98R35Uf+fYEQ/UnJD9Br4NXUFPv7JAUln5uHlgSeY root@serverhostname (ECDSA)
256 SHA256:sqOUWcraZQKd89y/QQv/iynPTOGQxcOTIXU/LsoPmnM root@serverhostname (ED25519)
2048 SHA256:qwa+rgir2Oy86QI+PZi/QVR+MSmrdrpsuH7YyKknC+s root@serverhostname (RSA)
```
1. Verify that you have the correct public keys for the existing private keys:
```shell
# This will print the fingerprint for private keys:
for file in <ssh_host_key_path>/ssh_host_*_key; do ssh-keygen -lf $file; done
# This will print the fingerprint for public keys:
for file in <ssh_host_key_path>/ssh_host_*_key.pub; do ssh-keygen -lf $file; done
```
{{< alert type="note" >}}
The output for private keys and public keys command should generate the same fingerprint.
{{< /alert >}}
1. Restart either `sshd` for OpenSSH or the `gitlab-sshd` service on **each Rails node on your secondary** site:
- For OpenSSH:
```shell
# Debian or Ubuntu installations
sudo service ssh reload
# CentOS installations
sudo service sshd reload
```
- For `gitlab-sshd`:
```shell
sudo gitlab-ctl restart gitlab-sshd
```
1. Verify SSH is still functional.
SSH into your GitLab **secondary** server in a new terminal. If you are unable to connect,
verify the permissions are correct according to the previous steps.
## Step 3. Add the **secondary** site
1. SSH into **each Rails and Sidekiq node on your secondary** site and login as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb` and add a **unique** name for your site. You need this in the next steps:
```ruby
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
```
1. Reconfigure **each Rails and Sidekiq node on your secondary** site for the change to take effect:
```shell
gitlab-ctl reconfigure
```
1. Go to the primary node GitLab instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Geo** > **Sites**.
1. Select **Add site**.

1. In **Name**, enter the value for `gitlab_rails['geo_node_name']` in
`/etc/gitlab/gitlab.rb`. These values must always match **exactly**, character
for character.
1. In **External URL**, enter the value for `external_url` in `/etc/gitlab/gitlab.rb`. These
values must always match, but it doesn't matter if one ends with a `/` and
the other doesn't.
1. Optional. In **Internal URL (optional)**, enter an internal URL for the secondary site.
1. Optional. Select which groups or storage shards should be replicated by the
**secondary** site. Leave blank to replicate all. For more information, see
[selective synchronization](selective_synchronization.md).
1. Select **Save changes** to add the **secondary** site.
1. SSH into **each Rails, and Sidekiq node on your secondary** site and restart the services:
```shell
gitlab-ctl restart
```
Check if there are any common issues with your Geo setup by running:
```shell
gitlab-rake gitlab:geo:check
```
If any of the checks fail, check the [troubleshooting documentation](troubleshooting/_index.md).
1. SSH into a **Rails or Sidekiq server on your primary** site and login as root to verify the
**secondary** site is reachable or there are any common issues with your Geo setup:
```shell
gitlab-rake gitlab:geo:check
```
If any of the checks fail, check the [troubleshooting documentation](troubleshooting/_index.md).
After the **secondary** site is added to the Geo administration page and restarted,
the site automatically starts replicating missing data from the **primary** site
in a process known as **backfill**.
Meanwhile, the **primary** site starts to notify each **secondary** site of any changes, so
that the **secondary** site can act on those notifications immediately.
Be sure the secondary site is running and accessible. You can sign in to the
secondary site with the same credentials as were used with the primary site.
## Step 4. (Optional) Using custom certificates
You can safely skip this step if:
- Your **primary** site uses a public CA-issued HTTPS certificate.
- Your **primary** site only connects to external services with CA-issued (not self-signed) HTTPS certificates.
### Custom or self-signed certificate for inbound connections
If your GitLab Geo **primary** site uses a custom or [self-signed certificate to secure inbound HTTPS connections](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates), this can be either a single-domain or multi-domain certificate.
Install the correct certificate based on your certificate type:
- **Multi-domain certificate** that includes both primary and secondary site domains: Install the certificate at `/etc/gitlab/ssl` on all **Rails, Sidekiq, and Gitaly** nodes in the **secondary** site.
- **Single-domain certificate** where the certificates are specific to each Geo site domain: Generate a valid certificate for your **secondary** site's domain and install it at `/etc/gitlab/ssl` following [these instructions](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) on all **Rails, Sidekiq, and Gitaly** nodes in the **secondary** site.
### Connecting to external services that use custom certificates
A copy of the self-signed certificate for the external service needs to be added to the trust store on all the **primary** site's nodes that require access to the service.
For the **secondary** site to be able to access the same external services, these certificates must be added to the **secondary** site's trust store.
If your **primary** site is using a [custom or self-signed certificate for inbound HTTPS connections](#custom-or-self-signed-certificate-for-inbound-connections), the **primary** site's certificate needs to be added to the **secondary** site's trust store:
1. SSH into each **Rails, Sidekiq, and Gitaly node on your secondary** site and login as root:
```shell
sudo -i
```
1. Copy the trusted certs from the **primary** site:
If you can access one of the nodes on your **primary** site serving SSH traffic using the root user:
```shell
scp root@<primary_site_node_fqdn>:/etc/gitlab/trusted-certs/* /etc/gitlab/trusted-certs
```
If you only have access through a user with sudo privileges:
```shell
# Run this from the node on your primary site:
sudo tar --transform 's/.*\///g' -zcvf ~/geo-trusted-certs.tar.gz /etc/gitlab/trusted-certs/*
# Run this on each node on your secondary site:
scp <user_with_sudo>@<primary_site_node_fqdn>:geo-trusted-certs.tar.gz .
tar zxvf ~/geo-trusted-certs.tar.gz -C /etc/gitlab/trusted-certs
```
1. Reconfigure each updated **Rails, Sidekiq, and Gitaly node in your secondary** site:
```shell
sudo gitlab-ctl reconfigure
```
## Step 5. Enable Git access over HTTP/HTTPS and SSH
Geo synchronizes repositories over HTTP/HTTPS, and therefore requires this clone
method to be enabled. This is enabled by default, but if converting an existing site to Geo it should be checked:
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings** > **General**.
1. Expand **Visibility and access controls**.
1. If using Git over SSH, then:
1. Ensure "Enabled Git access protocols" is set to "Both SSH and HTTP(S)".
1. Follow the steps to configure
[fast lookup of authorized SSH keys in the database](../../operations/fast_ssh_key_lookup.md) on
**all primary and secondary** sites.
1. If not using Git over SSH, then set "Enabled Git access protocols" to "Only HTTP(S)".
## Step 6. Verify proper functioning of the **secondary** site
You can sign in to the **secondary** site with the same credentials you used with
the **primary** site. After you sign in:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Verify that it's correctly identified as a **secondary** Geo site, and that
Geo is enabled.
The initial replication may take some time. The status of the site or the 'backfill' may still in progress. You
can monitor the synchronization process on each Geo site from the **primary**
site's **Geo Sites** dashboard in your browser.

If your installation isn't working properly, check the
[troubleshooting document](troubleshooting/_index.md).
The two most obvious issues that can become apparent in the dashboard are:
1. Database replication not working well.
1. Instance to instance notification not working. In that case, it can be
something of the following:
- You are using a custom certificate or custom CA (see the [troubleshooting document](troubleshooting/_index.md)).
- The instance is firewalled (check your firewall rules).
Disabling a **secondary** site stops the synchronization process.
If repository storages are customized on the **primary** site for multiple
repository shards you must duplicate the same configuration on each **secondary** site.
Point your users to the [Using a Geo Site guide](usage.md).
Currently, this is what is synced:
- Git repositories.
- Wikis.
- LFS objects.
- Issues, merge requests, snippets, and comment attachments.
- Users, groups, and project avatars.
## Troubleshooting
See the [troubleshooting document](troubleshooting/_index.md).
|
https://docs.gitlab.com/administration/geo/single_sign_on
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/single_sign_on.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
single_sign_on.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo with Single Sign On (SSO)
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This documentation only discusses Geo-specific SSO considerations and configuration. For more information on general authentication, see [GitLab authentication and authorization](../../auth/_index.md).
## Configuring instance-wide SAML
### Prerequisites
[Instance-wide SAML](../../../integration/saml.md) must be working on your primary Geo site.
You only configure SAML on the primary site. Configuring `gitlab_rails['omniauth_providers']` in `gitlab.rb` in a secondary site has no effect. The secondary site authenticates against the SAML provider configured on the primary site. Depending on the [URL type](#determine-the-type-of-url-your-secondary-site-uses) of the secondary site, [additional configuration](#saml-with-separate-url-with-proxying-enabled) might be needed on the primary site.
### Determine the type of URL your secondary site uses
How you configure instance-wide SAML differs depending on your secondary site configuration. Determine if your secondary site uses a:
- [Unified URL](../secondary_proxy/_index.md#set-up-a-unified-url-for-geo-sites), meaning the `external_url` exactly matches the `external_url` of the primary site.
- [Separate URL](../secondary_proxy/_index.md#set-up-a-separate-url-for-a-secondary-geo-site) with proxying enabled. Proxying is enabled by default in GitLab 15.1 and later.
- [Separate URL](../secondary_proxy/_index.md#set-up-a-separate-url-for-a-secondary-geo-site) with proxying disabled.
### SAML with Unified URL
If you have configured SAML on the primary site correctly, then it should work on the secondary site without additional configuration.
### SAML with separate URL with proxying enabled
{{< alert type="note" >}}
When proxying is enabled, SAML can only be used to sign in the secondary site if your SAML Identity Provider (IdP) allows an
application to have multiple callback URLs configured. Check with your IdP provider support team to confirm if this is the case.
{{< /alert >}}
If a secondary site uses a different `external_url` to the primary site, then configure your SAML Identity Provider (IdP) to allow the secondary site's SAML callback URL. For example, to configure Okta:
1. [Sign in to Okta](https://login.okta.com/).
1. Go to **Okta Admin Dashboard** > **Applications** > **Your App Name** > **General**.
1. In **SAML Settings**, select **Edit**.
1. In **General Settings**, select **Next** to go to **SAML Settings**.
1. In **SAML Settings > General**, make sure the **Single sign-on URL** is your primary site's SAML callback URL. For example, `https://gitlab-primary.example.com/users/auth/saml/callback`. If it is not, enter your primary site's SAML callback URL into this field.
1. Select **Show Advanced Settings**.
1. In **Other Requestable SSO URLs**, enter your secondary site's SAML callback URL. For example, `https://gitlab-secondary.example.com/users/auth/saml/callback`. You can set **Index** to anything.
1. Select **Next** and then **Finish**.
You must not specify `assertion_consumer_service_url` in the SAML provider configuration in `gitlab_rails['omniauth_providers']` in `gitlab.rb` of the primary site. For example:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "saml",
label: "Okta", # optional label for login button, defaults to "Saml"
args: {
idp_cert_fingerprint: "B5:AD:AA:9E:3C:05:68:AD:3B:78:ED:31:99:96:96:43:9E:6D:79:96",
idp_sso_target_url: "https://<dev-account>.okta.com/app/dev-account_gitlabprimary_1/exk7k2gft2VFpVFXa5d1/sso/saml",
issuer: "https://<gitlab-primary>",
name_identifier_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
}
}
]
```
This configuration causes:
- Both your sites to use `/users/auth/saml/callback` as their assertion consumer service (ACS) URL.
- The URL's host to be set to the corresponding site's host.
You can check this by visiting each site's `/users/auth/saml/metadata` path. For example, visiting `https://gitlab-primary.example.com/users/auth/saml/metadata` may respond with:
```xml
<md:EntityDescriptor ID="_b9e00d84-d34e-4e3d-95de-122e3c361617" entityID="https://gitlab-primary.example.com"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://gitlab-primary.example.com/users/auth/saml/callback" index="0" isDefault="true"/>
<md:AttributeConsumingService index="1" isDefault="true">
<md:ServiceName xml:lang="en">Required attributes</md:ServiceName>
<md:RequestedAttribute FriendlyName="Email address" Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Full name" Name="name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Given name" Name="first_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Family name" Name="last_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
</md:AttributeConsumingService>
</md:SPSSODescriptor>
</md:EntityDescriptor>
```
Visiting `https://gitlab-secondary.example.com/users/auth/saml/metadata` may respond with:
```xml
<md:EntityDescriptor ID="_bf71eb57-7490-4024-bfe2-54cec716d4bf" entityID="https://gitlab-primary.example.com"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://gitlab-secondary.example.com/users/auth/saml/callback" index="0" isDefault="true"/>
<md:AttributeConsumingService index="1" isDefault="true">
<md:ServiceName xml:lang="en">Required attributes</md:ServiceName>
<md:RequestedAttribute FriendlyName="Email address" Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Full name" Name="name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Given name" Name="first_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Family name" Name="last_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
</md:AttributeConsumingService>
</md:SPSSODescriptor>
</md:EntityDescriptor>
```
The `Location` attribute of the `md:AssertionConsumerService` field points to `gitlab-secondary.example.com`.
After configuring your SAML IdP to allow the secondary site's SAML callback URL, you should be able to sign in with SAML on your primary site as well as your secondary site.
### SAML with separate URL with proxying disabled
If you have configured SAML on the primary site correctly, then it should work on the secondary site without additional configuration.
## OpenID Connect
If you use an [OpenID Connect (OIDC)](../../auth/oidc.md) OmniAuth provider,
in most cases, it should work without an issue:
- **OIDC with Unified URL**: If you have configured OIDC on the primary site correctly, then it should work on the secondary site without additional configuration.
- **OIDC with separate URL with proxying disabled**: If you have configured OIDC on the primary site correctly, then it should work on the secondary site without additional configuration.
- **OIDC with separate URL with proxying enabled**: Geo with separate URL with proxying enabled does not support [OpenID Connect](../../auth/oidc.md). For more information, see [issue 396745](https://gitlab.com/gitlab-org/gitlab/-/issues/396745).
## LDAP
If you use LDAP on your **primary** site, you should also set up secondary LDAP servers on each **secondary** site. Otherwise, users cannot perform Git operations over HTTP(s) on the **secondary** site using HTTP basic authentication. However, users can still use Git with SSH and personal access tokens.
{{< alert type="note" >}}
It is possible for all **secondary** sites to share an LDAP server, but additional latency can be an issue. Also, consider what LDAP server is available in a [disaster recovery](../disaster_recovery/_index.md) scenario if a **secondary** site is promoted to be a **primary** site.
{{< /alert >}}
Check your LDAP service documentation for instructions on how to set up replication in your LDAP service. The process differs depending on the software or service used. For example, OpenLDAP provides this [replication documentation](https://www.openldap.org/doc/admin24/replication.html).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Geo with Single Sign On (SSO)
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This documentation only discusses Geo-specific SSO considerations and configuration. For more information on general authentication, see [GitLab authentication and authorization](../../auth/_index.md).
## Configuring instance-wide SAML
### Prerequisites
[Instance-wide SAML](../../../integration/saml.md) must be working on your primary Geo site.
You only configure SAML on the primary site. Configuring `gitlab_rails['omniauth_providers']` in `gitlab.rb` in a secondary site has no effect. The secondary site authenticates against the SAML provider configured on the primary site. Depending on the [URL type](#determine-the-type-of-url-your-secondary-site-uses) of the secondary site, [additional configuration](#saml-with-separate-url-with-proxying-enabled) might be needed on the primary site.
### Determine the type of URL your secondary site uses
How you configure instance-wide SAML differs depending on your secondary site configuration. Determine if your secondary site uses a:
- [Unified URL](../secondary_proxy/_index.md#set-up-a-unified-url-for-geo-sites), meaning the `external_url` exactly matches the `external_url` of the primary site.
- [Separate URL](../secondary_proxy/_index.md#set-up-a-separate-url-for-a-secondary-geo-site) with proxying enabled. Proxying is enabled by default in GitLab 15.1 and later.
- [Separate URL](../secondary_proxy/_index.md#set-up-a-separate-url-for-a-secondary-geo-site) with proxying disabled.
### SAML with Unified URL
If you have configured SAML on the primary site correctly, then it should work on the secondary site without additional configuration.
### SAML with separate URL with proxying enabled
{{< alert type="note" >}}
When proxying is enabled, SAML can only be used to sign in the secondary site if your SAML Identity Provider (IdP) allows an
application to have multiple callback URLs configured. Check with your IdP provider support team to confirm if this is the case.
{{< /alert >}}
If a secondary site uses a different `external_url` to the primary site, then configure your SAML Identity Provider (IdP) to allow the secondary site's SAML callback URL. For example, to configure Okta:
1. [Sign in to Okta](https://login.okta.com/).
1. Go to **Okta Admin Dashboard** > **Applications** > **Your App Name** > **General**.
1. In **SAML Settings**, select **Edit**.
1. In **General Settings**, select **Next** to go to **SAML Settings**.
1. In **SAML Settings > General**, make sure the **Single sign-on URL** is your primary site's SAML callback URL. For example, `https://gitlab-primary.example.com/users/auth/saml/callback`. If it is not, enter your primary site's SAML callback URL into this field.
1. Select **Show Advanced Settings**.
1. In **Other Requestable SSO URLs**, enter your secondary site's SAML callback URL. For example, `https://gitlab-secondary.example.com/users/auth/saml/callback`. You can set **Index** to anything.
1. Select **Next** and then **Finish**.
You must not specify `assertion_consumer_service_url` in the SAML provider configuration in `gitlab_rails['omniauth_providers']` in `gitlab.rb` of the primary site. For example:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "saml",
label: "Okta", # optional label for login button, defaults to "Saml"
args: {
idp_cert_fingerprint: "B5:AD:AA:9E:3C:05:68:AD:3B:78:ED:31:99:96:96:43:9E:6D:79:96",
idp_sso_target_url: "https://<dev-account>.okta.com/app/dev-account_gitlabprimary_1/exk7k2gft2VFpVFXa5d1/sso/saml",
issuer: "https://<gitlab-primary>",
name_identifier_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
}
}
]
```
This configuration causes:
- Both your sites to use `/users/auth/saml/callback` as their assertion consumer service (ACS) URL.
- The URL's host to be set to the corresponding site's host.
You can check this by visiting each site's `/users/auth/saml/metadata` path. For example, visiting `https://gitlab-primary.example.com/users/auth/saml/metadata` may respond with:
```xml
<md:EntityDescriptor ID="_b9e00d84-d34e-4e3d-95de-122e3c361617" entityID="https://gitlab-primary.example.com"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://gitlab-primary.example.com/users/auth/saml/callback" index="0" isDefault="true"/>
<md:AttributeConsumingService index="1" isDefault="true">
<md:ServiceName xml:lang="en">Required attributes</md:ServiceName>
<md:RequestedAttribute FriendlyName="Email address" Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Full name" Name="name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Given name" Name="first_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Family name" Name="last_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
</md:AttributeConsumingService>
</md:SPSSODescriptor>
</md:EntityDescriptor>
```
Visiting `https://gitlab-secondary.example.com/users/auth/saml/metadata` may respond with:
```xml
<md:EntityDescriptor ID="_bf71eb57-7490-4024-bfe2-54cec716d4bf" entityID="https://gitlab-primary.example.com"
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
<md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://gitlab-secondary.example.com/users/auth/saml/callback" index="0" isDefault="true"/>
<md:AttributeConsumingService index="1" isDefault="true">
<md:ServiceName xml:lang="en">Required attributes</md:ServiceName>
<md:RequestedAttribute FriendlyName="Email address" Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Full name" Name="name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Given name" Name="first_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
<md:RequestedAttribute FriendlyName="Family name" Name="last_name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="false"/>
</md:AttributeConsumingService>
</md:SPSSODescriptor>
</md:EntityDescriptor>
```
The `Location` attribute of the `md:AssertionConsumerService` field points to `gitlab-secondary.example.com`.
After configuring your SAML IdP to allow the secondary site's SAML callback URL, you should be able to sign in with SAML on your primary site as well as your secondary site.
### SAML with separate URL with proxying disabled
If you have configured SAML on the primary site correctly, then it should work on the secondary site without additional configuration.
## OpenID Connect
If you use an [OpenID Connect (OIDC)](../../auth/oidc.md) OmniAuth provider,
in most cases, it should work without an issue:
- **OIDC with Unified URL**: If you have configured OIDC on the primary site correctly, then it should work on the secondary site without additional configuration.
- **OIDC with separate URL with proxying disabled**: If you have configured OIDC on the primary site correctly, then it should work on the secondary site without additional configuration.
- **OIDC with separate URL with proxying enabled**: Geo with separate URL with proxying enabled does not support [OpenID Connect](../../auth/oidc.md). For more information, see [issue 396745](https://gitlab.com/gitlab-org/gitlab/-/issues/396745).
## LDAP
If you use LDAP on your **primary** site, you should also set up secondary LDAP servers on each **secondary** site. Otherwise, users cannot perform Git operations over HTTP(s) on the **secondary** site using HTTP basic authentication. However, users can still use Git with SSH and personal access tokens.
{{< alert type="note" >}}
It is possible for all **secondary** sites to share an LDAP server, but additional latency can be an issue. Also, consider what LDAP server is available in a [disaster recovery](../disaster_recovery/_index.md) scenario if a **secondary** site is promoted to be a **primary** site.
{{< /alert >}}
Check your LDAP service documentation for instructions on how to set up replication in your LDAP service. The process differs depending on the software or service used. For example, OpenLDAP provides this [replication documentation](https://www.openldap.org/doc/admin24/replication.html).
|
https://docs.gitlab.com/administration/geo/security_review
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/security_review.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
security_review.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo security review (Q&A)
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following security review of the Geo feature set focuses on security aspects of
the feature as they apply to customers running their own GitLab instances. The review
questions are based in part on the [OWASP Application Security Verification Standard Project](https://owasp.org/www-project-application-security-verification-standard/)
from [owasp.org](https://owasp.org/).
## Business Model
### What geographic areas does the application service?
- This varies by customer. Geo allows customers to deploy to multiple areas,
and they get to choose where they are.
- Region and node selection is entirely manual.
## Data Essentials
### What data does the application receive, produce, and process?
- Geo streams almost all data held by a GitLab instance between sites. This
includes full database replication, most files such as user-uploaded attachments,
and repository + wiki data. In a typical configuration, this will
happen across the public Internet, and be TLS-encrypted.
- PostgreSQL replication is TLS-encrypted.
- See also: [only TLSv1.2 should be supported](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/2948)
### How can the data be classified into categories according to its sensitivity?
- The GitLab model of sensitivity is centered around public vs. internal vs.
private projects. Geo replicates them all indiscriminately. "Selective sync"
exists for files and repositories (but not database content), which would permit
only less-sensitive projects to be replicated to a **secondary** site if desired.
### What data backup and retention requirements have been defined for the application?
- Geo is designed to provide replication of a certain subset of the application
data. It is part of the solution, rather than part of the problem.
## End-Users
### Who are the application's end-users?
- **Secondary** sites are created in regions that are distant (in terms of
Internet latency) from the main GitLab installation (the **primary** site). They are
intended to be used by anyone who would ordinarily use the **primary** site, who finds
that the **secondary** site is closer to them (in terms of Internet latency).
### How do the end-users interact with the application?
- **Secondary** sites provide all the interfaces a **primary** site does
(notably an HTTP/HTTPS web application, and HTTP/HTTPS or SSH Git repository
access), but is constrained to read-only activities. The principal use case is
envisioned to be cloning Git repositories from the **secondary** site in favor of the
**primary** site, but end-users may use the GitLab web interface to view information like projects,
issues, merge requests, and snippets.
### What security expectations do the end-users have?
- The replication process must be secure. It would typically be unacceptable to
transmit the entire database contents or all files and repositories across the
public Internet in plaintext, for instance.
- **Secondary** sites must have the same access controls over its content as the
**primary** site - unauthenticated users must not be able to gain access to privileged
information on the **primary** site by querying the **secondary** site.
- Attackers must not be able to impersonate the **secondary** site to the **primary** site, and
thus gain access to privileged information.
## Administrators
### Who has administrative capabilities in the application?
- Nothing Geo-specific. Any user where `admin: true` is set in the database is
considered an administrator with super-user privileges.
- See also: [more granular access control](https://gitlab.com/gitlab-org/gitlab/-/issues/18242)
(not Geo-specific).
- Much of Geo's integration (database replication, for instance) must be
configured with the application, typically by system administrators.
### What administrative capabilities does the application offer?
- **Secondary** sites may be added, modified, or removed by users with
administrative access.
- The replication process may be controlled (start/stop) via the Sidekiq
administrative controls.
## Network
### What details regarding routing, switching, firewalling, and load-balancing have been defined?
- Geo requires the **primary** site and **secondary** site to be able to communicate with each
other across a TCP/IP network. In particular, the **secondary** sites must be able to
access HTTP/HTTPS and PostgreSQL services on the **primary** site.
### What core network devices support the application?
- Varies from customer to customer.
### What network performance requirements exist?
- Maximum replication speeds between **primary** site and **secondary** site is limited by the
available bandwidth between sites. No hard requirements exist - time to complete
replication (and ability to keep up with changes on the **primary** site) is a function
of the size of the data set, tolerance for latency, and available network
capacity.
### What private and public network links support the application?
- Customers choose their own networks. As sites are intended to be
geographically separated, it is envisioned that replication traffic passes
over the public Internet in a typical deployment, but this is not a requirement.
## Systems
### What operating systems support the application?
- Geo imposes no additional restrictions on operating system (see the
[GitLab installation](https://about.gitlab.com/install/) page for more
details), however we recommend using the operating systems listed in the [Geo documentation](../_index.md#requirements-for-running-geo).
### What details regarding required OS components and lock-down needs have been defined?
- The supported Linux package installation method packages most components itself.
- There are significant dependencies on the system-installed OpenSSH daemon (Geo
requires users to set up custom authentication methods) and the Linux package-provided or
system-provided PostgreSQL daemon (it must be configured to listen on TCP,
additional users and replication slots must be added, etc).
- The process for dealing with security updates (for example, if there is a
significant vulnerability in OpenSSH or other services, and the customer
wants to patch those services on the OS) is identical to the non-Geo
situation: security updates to OpenSSH would be provided to the user via the
usual distribution channels. Geo introduces no delay there.
## Infrastructure Monitoring
### What network and system performance monitoring requirements have been defined?
- None specific to Geo.
### What mechanisms exist to detect malicious code or compromised application components?
- None specific to Geo.
### What network and system security monitoring requirements have been defined?
- None specific to Geo.
## Virtualization and Externalization
### What aspects of the application lend themselves to virtualization?
- All.
## What virtualization requirements have been defined for the application?
- Nothing Geo-specific, but everything in GitLab needs to have full
functionality in such an environment.
### What aspects of the product may or may not be hosted via the cloud computing model?
- GitLab is "cloud native" and this applies to Geo as much as to the rest of the
product. Deployment in clouds is a common and supported scenario.
## If applicable, what approaches to cloud computing are taken?
- Whether to use these is to be decided by our customers, according to their operational needs:
- Managed hosting versus "pure" cloud
- A "full machine" approach, such as AWS-ED2, versus a "hosted database" approach such as AWS-RDS and Azure
## Environment
### What frameworks and programming languages have been used to create the application?
- Ruby on Rails, Ruby.
### What process, code, or infrastructure dependencies have been defined for the application?
- Nothing specific to Geo.
### What databases and application servers support the application?
- PostgreSQL >= 12, Redis, Sidekiq, Puma.
### How to protect database connection strings, encryption keys, and other sensitive components?
- There are some Geo-specific values. Some are shared secrets which must be
securely transmitted from the **primary** site to the **secondary** site at setup time. Our
documentation recommends transmitting them from the **primary** site to the system
administrator via SSH, and then back out to the **secondary** site in the same manner.
In particular, this includes the PostgreSQL replication credentials and a secret
key (`db_key_base`) which is used to decrypt certain columns in the database.
The `db_key_base` secret is stored unencrypted on the file system, in
`/etc/gitlab/gitlab-secrets.json`, along with a number of other secrets. There is
no at-rest protection for them.
## Data Processing
### What data entry paths does the application support?
- Data is entered via the web application exposed by GitLab itself. Some data is
also entered using system administration commands on the GitLab servers (for example
`gitlab-ctl set-primary-node`).
- **Secondary** sites also receive inputs via PostgreSQL streaming replication from the **primary** site.
### What data output paths does the application support?
- **Primary** sites output via PostgreSQL streaming replication to the **secondary** site.
Otherwise, principally via the web application exposed by GitLab itself, and via
SSH `git clone` operations initiated by the end-user.
### How does data flow across the application's internal components?
- **Secondary** sites and **primary** sites interact via HTTP/HTTPS (secured with JSON web
tokens) and via PostgreSQL streaming replication.
- Within a **primary** site or **secondary** site, the SSOT is the file system and the database
(including Geo tracking database on **secondary** site). The various internal components
are orchestrated to make alterations to these stores.
### What data input validation requirements have been defined?
- **Secondary** sites must have a faithful replication of the **primary** site's data.
### What data does the application store and how?
- Git repositories and files, tracking information related to them, and the GitLab database contents.
### What data should be encrypted? What key management requirements are defined?
- Neither **primary** sites or **secondary** sites encrypt Git repository or file system data at
rest. A subset of database columns are encrypted at rest using the `db_otp_key`.
- A static secret shared across all hosts in a GitLab deployment.
- In transit, data should be encrypted, although the application does permit
communication to proceed unencrypted. The two main transits are the **secondary** site's
replication process for PostgreSQL, and for Git repositories/files. Both should
be protected using TLS, with the keys for that managed by the Linux package per existing
configuration for end-user access to GitLab.
### What capabilities exist to detect the leakage of sensitive data?
- Comprehensive system logs exist, tracking every connection to GitLab and PostgreSQL.
### What encryption requirements have been defined for data in transit?
- (This includes transmission over WAN, LAN, SecureFTP, or publicly accessible protocols such as `http:` and `https:`.)
- Data must have the option to be encrypted in transit, and be secure against
both passive and active attack (for example, MITM attacks should not be possible).
## Access
### What user privilege levels does the application support?
- Geo adds one type of privilege: **secondary** sites can access a special Geo API to
download files over HTTP/HTTPS, and to clone repositories using HTTP/HTTPS.
### What user identification and authentication requirements have been defined?
- **Secondary** sites identify to Geo **primary** sites via OAuth or JWT authentication
based on the shared database (HTTP access) or a PostgreSQL replication user (for
database replication). The database replication also requires IP-based access
controls to be defined.
### What user authorization requirements have been defined?
- **Secondary** sites must only be able to read data. They cannot mutate data on the **primary** site.
### What session management requirements have been defined?
- Geo JWTs are defined to last for only two minutes before needing to be regenerated.
- Geo JWTs are generated for one of the following specific scopes:
- Geo API access.
- Git access.
- LFS and File ID.
- Upload and File ID.
- Job Artifact and File ID.
### What access requirements have been defined for URI and Service calls?
- **Secondary** sites make many calls to the **primary** site's API. This is how file
replication proceeds, for instance. This endpoint is only accessible with a JWT token.
- The **primary** site also makes calls to the **secondary** site to get status information.
## Application Monitoring
### How are audit and debug logs accessed, stored, and secured?
- Structured JSON log is written to the file system, and can also be ingested
into a Kibana installation for further analysis.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Geo security review (Q&A)
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following security review of the Geo feature set focuses on security aspects of
the feature as they apply to customers running their own GitLab instances. The review
questions are based in part on the [OWASP Application Security Verification Standard Project](https://owasp.org/www-project-application-security-verification-standard/)
from [owasp.org](https://owasp.org/).
## Business Model
### What geographic areas does the application service?
- This varies by customer. Geo allows customers to deploy to multiple areas,
and they get to choose where they are.
- Region and node selection is entirely manual.
## Data Essentials
### What data does the application receive, produce, and process?
- Geo streams almost all data held by a GitLab instance between sites. This
includes full database replication, most files such as user-uploaded attachments,
and repository + wiki data. In a typical configuration, this will
happen across the public Internet, and be TLS-encrypted.
- PostgreSQL replication is TLS-encrypted.
- See also: [only TLSv1.2 should be supported](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/2948)
### How can the data be classified into categories according to its sensitivity?
- The GitLab model of sensitivity is centered around public vs. internal vs.
private projects. Geo replicates them all indiscriminately. "Selective sync"
exists for files and repositories (but not database content), which would permit
only less-sensitive projects to be replicated to a **secondary** site if desired.
### What data backup and retention requirements have been defined for the application?
- Geo is designed to provide replication of a certain subset of the application
data. It is part of the solution, rather than part of the problem.
## End-Users
### Who are the application's end-users?
- **Secondary** sites are created in regions that are distant (in terms of
Internet latency) from the main GitLab installation (the **primary** site). They are
intended to be used by anyone who would ordinarily use the **primary** site, who finds
that the **secondary** site is closer to them (in terms of Internet latency).
### How do the end-users interact with the application?
- **Secondary** sites provide all the interfaces a **primary** site does
(notably an HTTP/HTTPS web application, and HTTP/HTTPS or SSH Git repository
access), but is constrained to read-only activities. The principal use case is
envisioned to be cloning Git repositories from the **secondary** site in favor of the
**primary** site, but end-users may use the GitLab web interface to view information like projects,
issues, merge requests, and snippets.
### What security expectations do the end-users have?
- The replication process must be secure. It would typically be unacceptable to
transmit the entire database contents or all files and repositories across the
public Internet in plaintext, for instance.
- **Secondary** sites must have the same access controls over its content as the
**primary** site - unauthenticated users must not be able to gain access to privileged
information on the **primary** site by querying the **secondary** site.
- Attackers must not be able to impersonate the **secondary** site to the **primary** site, and
thus gain access to privileged information.
## Administrators
### Who has administrative capabilities in the application?
- Nothing Geo-specific. Any user where `admin: true` is set in the database is
considered an administrator with super-user privileges.
- See also: [more granular access control](https://gitlab.com/gitlab-org/gitlab/-/issues/18242)
(not Geo-specific).
- Much of Geo's integration (database replication, for instance) must be
configured with the application, typically by system administrators.
### What administrative capabilities does the application offer?
- **Secondary** sites may be added, modified, or removed by users with
administrative access.
- The replication process may be controlled (start/stop) via the Sidekiq
administrative controls.
## Network
### What details regarding routing, switching, firewalling, and load-balancing have been defined?
- Geo requires the **primary** site and **secondary** site to be able to communicate with each
other across a TCP/IP network. In particular, the **secondary** sites must be able to
access HTTP/HTTPS and PostgreSQL services on the **primary** site.
### What core network devices support the application?
- Varies from customer to customer.
### What network performance requirements exist?
- Maximum replication speeds between **primary** site and **secondary** site is limited by the
available bandwidth between sites. No hard requirements exist - time to complete
replication (and ability to keep up with changes on the **primary** site) is a function
of the size of the data set, tolerance for latency, and available network
capacity.
### What private and public network links support the application?
- Customers choose their own networks. As sites are intended to be
geographically separated, it is envisioned that replication traffic passes
over the public Internet in a typical deployment, but this is not a requirement.
## Systems
### What operating systems support the application?
- Geo imposes no additional restrictions on operating system (see the
[GitLab installation](https://about.gitlab.com/install/) page for more
details), however we recommend using the operating systems listed in the [Geo documentation](../_index.md#requirements-for-running-geo).
### What details regarding required OS components and lock-down needs have been defined?
- The supported Linux package installation method packages most components itself.
- There are significant dependencies on the system-installed OpenSSH daemon (Geo
requires users to set up custom authentication methods) and the Linux package-provided or
system-provided PostgreSQL daemon (it must be configured to listen on TCP,
additional users and replication slots must be added, etc).
- The process for dealing with security updates (for example, if there is a
significant vulnerability in OpenSSH or other services, and the customer
wants to patch those services on the OS) is identical to the non-Geo
situation: security updates to OpenSSH would be provided to the user via the
usual distribution channels. Geo introduces no delay there.
## Infrastructure Monitoring
### What network and system performance monitoring requirements have been defined?
- None specific to Geo.
### What mechanisms exist to detect malicious code or compromised application components?
- None specific to Geo.
### What network and system security monitoring requirements have been defined?
- None specific to Geo.
## Virtualization and Externalization
### What aspects of the application lend themselves to virtualization?
- All.
## What virtualization requirements have been defined for the application?
- Nothing Geo-specific, but everything in GitLab needs to have full
functionality in such an environment.
### What aspects of the product may or may not be hosted via the cloud computing model?
- GitLab is "cloud native" and this applies to Geo as much as to the rest of the
product. Deployment in clouds is a common and supported scenario.
## If applicable, what approaches to cloud computing are taken?
- Whether to use these is to be decided by our customers, according to their operational needs:
- Managed hosting versus "pure" cloud
- A "full machine" approach, such as AWS-ED2, versus a "hosted database" approach such as AWS-RDS and Azure
## Environment
### What frameworks and programming languages have been used to create the application?
- Ruby on Rails, Ruby.
### What process, code, or infrastructure dependencies have been defined for the application?
- Nothing specific to Geo.
### What databases and application servers support the application?
- PostgreSQL >= 12, Redis, Sidekiq, Puma.
### How to protect database connection strings, encryption keys, and other sensitive components?
- There are some Geo-specific values. Some are shared secrets which must be
securely transmitted from the **primary** site to the **secondary** site at setup time. Our
documentation recommends transmitting them from the **primary** site to the system
administrator via SSH, and then back out to the **secondary** site in the same manner.
In particular, this includes the PostgreSQL replication credentials and a secret
key (`db_key_base`) which is used to decrypt certain columns in the database.
The `db_key_base` secret is stored unencrypted on the file system, in
`/etc/gitlab/gitlab-secrets.json`, along with a number of other secrets. There is
no at-rest protection for them.
## Data Processing
### What data entry paths does the application support?
- Data is entered via the web application exposed by GitLab itself. Some data is
also entered using system administration commands on the GitLab servers (for example
`gitlab-ctl set-primary-node`).
- **Secondary** sites also receive inputs via PostgreSQL streaming replication from the **primary** site.
### What data output paths does the application support?
- **Primary** sites output via PostgreSQL streaming replication to the **secondary** site.
Otherwise, principally via the web application exposed by GitLab itself, and via
SSH `git clone` operations initiated by the end-user.
### How does data flow across the application's internal components?
- **Secondary** sites and **primary** sites interact via HTTP/HTTPS (secured with JSON web
tokens) and via PostgreSQL streaming replication.
- Within a **primary** site or **secondary** site, the SSOT is the file system and the database
(including Geo tracking database on **secondary** site). The various internal components
are orchestrated to make alterations to these stores.
### What data input validation requirements have been defined?
- **Secondary** sites must have a faithful replication of the **primary** site's data.
### What data does the application store and how?
- Git repositories and files, tracking information related to them, and the GitLab database contents.
### What data should be encrypted? What key management requirements are defined?
- Neither **primary** sites or **secondary** sites encrypt Git repository or file system data at
rest. A subset of database columns are encrypted at rest using the `db_otp_key`.
- A static secret shared across all hosts in a GitLab deployment.
- In transit, data should be encrypted, although the application does permit
communication to proceed unencrypted. The two main transits are the **secondary** site's
replication process for PostgreSQL, and for Git repositories/files. Both should
be protected using TLS, with the keys for that managed by the Linux package per existing
configuration for end-user access to GitLab.
### What capabilities exist to detect the leakage of sensitive data?
- Comprehensive system logs exist, tracking every connection to GitLab and PostgreSQL.
### What encryption requirements have been defined for data in transit?
- (This includes transmission over WAN, LAN, SecureFTP, or publicly accessible protocols such as `http:` and `https:`.)
- Data must have the option to be encrypted in transit, and be secure against
both passive and active attack (for example, MITM attacks should not be possible).
## Access
### What user privilege levels does the application support?
- Geo adds one type of privilege: **secondary** sites can access a special Geo API to
download files over HTTP/HTTPS, and to clone repositories using HTTP/HTTPS.
### What user identification and authentication requirements have been defined?
- **Secondary** sites identify to Geo **primary** sites via OAuth or JWT authentication
based on the shared database (HTTP access) or a PostgreSQL replication user (for
database replication). The database replication also requires IP-based access
controls to be defined.
### What user authorization requirements have been defined?
- **Secondary** sites must only be able to read data. They cannot mutate data on the **primary** site.
### What session management requirements have been defined?
- Geo JWTs are defined to last for only two minutes before needing to be regenerated.
- Geo JWTs are generated for one of the following specific scopes:
- Geo API access.
- Git access.
- LFS and File ID.
- Upload and File ID.
- Job Artifact and File ID.
### What access requirements have been defined for URI and Service calls?
- **Secondary** sites make many calls to the **primary** site's API. This is how file
replication proceeds, for instance. This endpoint is only accessible with a JWT token.
- The **primary** site also makes calls to the **secondary** site to get status information.
## Application Monitoring
### How are audit and debug logs accessed, stored, and secured?
- Structured JSON log is written to the file system, and can also be ingested
into a Kibana installation for further analysis.
|
https://docs.gitlab.com/administration/geo/object_storage
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/object_storage.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
object_storage.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo with Object storage
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Verification of files stored in object storage was [introduced](https://gitlab.com/groups/gitlab-org/-/epics/8056) in GitLab 16.4 [with a flag](../../feature_flags/_index.md) named `geo_object_storage_verification`. Enabled by default.
{{< /history >}}
Geo can be used in combination with Object Storage (AWS S3, or other compatible object storage).
**Secondary** sites can use one of the following:
- The same storage bucket as the **primary** site.
- A replicated storage bucket.
- Local storage, if the primary uses local storage.
The storage method (local or object storage) for files is recorded in the database, and the database
is replicated from the **primary** Geo site to the **secondary** Geo site.
When accessing an uploaded object, we get its storage method (local or object storage) from the
database, so the **secondary** Geo site must match the storage method of the **primary** Geo site.
Therefore, if the **primary** Geo site uses object storage, the **secondary** Geo site must use it too.
To have:
- GitLab manage replication, follow [Enabling GitLab replication](#enabling-gitlab-managed-object-storage-replication).
- Third-party services manage replication, follow [Third-party replication services](#third-party-replication-services).
[Read more about using object storage with GitLab](../../object_storage.md).
## Enabling GitLab-managed object storage replication
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/5551) in GitLab 15.1.
{{< /history >}}
{{< alert type="warning" >}}
In case of issues, avoid manually deleting individual files as that can lead to [data inconsistencies](#inconsistencies-after-the-migration).
{{< /alert >}}
**Secondary** sites can replicate files stored on the **primary** site regardless of
whether they are stored on the local file system or in object storage.
To enable GitLab replication:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
1. Select **Edit** on the **secondary** site.
1. In the **Synchronization Settings** section, find the **Allow this secondary node to replicate content on Object Storage**
checkbox to enable it.
For LFS, follow the documentation to
[set up LFS object storage](../../lfs/_index.md#storing-lfs-objects-in-remote-object-storage).
For CI job artifacts, there is similar documentation to configure
[jobs artifact object storage](../../cicd/job_artifacts.md#using-object-storage).
For user uploads, there is similar documentation to configure [upload object storage](../../uploads.md#using-object-storage).
If you want to migrate the **primary** site's files to object storage, you can
configure the **secondary** in a few ways:
- Use the exact same object storage.
- Use a separate object store but leverage your object storage solution's built-in
replication.
- Use a separate object store and enable the **Allow this secondary node to replicate
content on Object Storage** setting.
{{< alert type="warning" >}}
To avoid data loss, you should only enable the **Allow this secondary node to replicate content on
Object Storage** setting if you are using separate object stores for the Primary and Secondary
sites.
{{< /alert >}}
GitLab does not support the case where both:
- The **primary** site uses local storage.
- A **secondary** site uses object storage.
### Inconsistencies after the migration
Data inconsistencies can occur when migrating from local to object storage,
which is further described in the [object storage troubleshooting section](../../object_storage.md#inconsistencies-after-migrating-to-object-storage).
## Third-party replication services
When using Amazon S3, you can use
[Cross-Region Replication (CRR)](https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) to
have automatic replication between the bucket used by the **primary** site and
the bucket used by **secondary** sites.
If you are using Google Cloud Storage, consider using
[Multi-Regional Storage](https://cloud.google.com/storage/docs/storage-classes#multi-regional).
Or you can use the [Storage Transfer Service](https://cloud.google.com/storage-transfer/docs/overview),
although this only supports daily synchronization.
For manual synchronization, or scheduled by `cron`, see:
- [`s3cmd sync`](https://s3tools.org/s3cmd-sync)
- [`gsutil rsync`](https://cloud.google.com/storage/docs/gsutil/commands/rsync)
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Geo with Object storage
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Verification of files stored in object storage was [introduced](https://gitlab.com/groups/gitlab-org/-/epics/8056) in GitLab 16.4 [with a flag](../../feature_flags/_index.md) named `geo_object_storage_verification`. Enabled by default.
{{< /history >}}
Geo can be used in combination with Object Storage (AWS S3, or other compatible object storage).
**Secondary** sites can use one of the following:
- The same storage bucket as the **primary** site.
- A replicated storage bucket.
- Local storage, if the primary uses local storage.
The storage method (local or object storage) for files is recorded in the database, and the database
is replicated from the **primary** Geo site to the **secondary** Geo site.
When accessing an uploaded object, we get its storage method (local or object storage) from the
database, so the **secondary** Geo site must match the storage method of the **primary** Geo site.
Therefore, if the **primary** Geo site uses object storage, the **secondary** Geo site must use it too.
To have:
- GitLab manage replication, follow [Enabling GitLab replication](#enabling-gitlab-managed-object-storage-replication).
- Third-party services manage replication, follow [Third-party replication services](#third-party-replication-services).
[Read more about using object storage with GitLab](../../object_storage.md).
## Enabling GitLab-managed object storage replication
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/5551) in GitLab 15.1.
{{< /history >}}
{{< alert type="warning" >}}
In case of issues, avoid manually deleting individual files as that can lead to [data inconsistencies](#inconsistencies-after-the-migration).
{{< /alert >}}
**Secondary** sites can replicate files stored on the **primary** site regardless of
whether they are stored on the local file system or in object storage.
To enable GitLab replication:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
1. Select **Edit** on the **secondary** site.
1. In the **Synchronization Settings** section, find the **Allow this secondary node to replicate content on Object Storage**
checkbox to enable it.
For LFS, follow the documentation to
[set up LFS object storage](../../lfs/_index.md#storing-lfs-objects-in-remote-object-storage).
For CI job artifacts, there is similar documentation to configure
[jobs artifact object storage](../../cicd/job_artifacts.md#using-object-storage).
For user uploads, there is similar documentation to configure [upload object storage](../../uploads.md#using-object-storage).
If you want to migrate the **primary** site's files to object storage, you can
configure the **secondary** in a few ways:
- Use the exact same object storage.
- Use a separate object store but leverage your object storage solution's built-in
replication.
- Use a separate object store and enable the **Allow this secondary node to replicate
content on Object Storage** setting.
{{< alert type="warning" >}}
To avoid data loss, you should only enable the **Allow this secondary node to replicate content on
Object Storage** setting if you are using separate object stores for the Primary and Secondary
sites.
{{< /alert >}}
GitLab does not support the case where both:
- The **primary** site uses local storage.
- A **secondary** site uses object storage.
### Inconsistencies after the migration
Data inconsistencies can occur when migrating from local to object storage,
which is further described in the [object storage troubleshooting section](../../object_storage.md#inconsistencies-after-migrating-to-object-storage).
## Third-party replication services
When using Amazon S3, you can use
[Cross-Region Replication (CRR)](https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) to
have automatic replication between the bucket used by the **primary** site and
the bucket used by **secondary** sites.
If you are using Google Cloud Storage, consider using
[Multi-Regional Storage](https://cloud.google.com/storage/docs/storage-classes#multi-regional).
Or you can use the [Storage Transfer Service](https://cloud.google.com/storage-transfer/docs/overview),
although this only supports daily synchronization.
For manual synchronization, or scheduled by `cron`, see:
- [`s3cmd sync`](https://s3tools.org/s3cmd-sync)
- [`gsutil rsync`](https://cloud.google.com/storage/docs/gsutil/commands/rsync)
|
https://docs.gitlab.com/administration/geo/location_aware_git_url
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/location_aware_git_url.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
location_aware_git_url.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Location-aware Git remote URL with AWS Route53
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
[GitLab Geo supports location-aware DNS including web UI and API traffic.](../secondary_proxy/_index.md#configure-location-aware-dns)
This configuration is recommended over the location-aware Git remote URL
described in this document.
{{< /alert >}}
You can provide GitLab users with a single remote URL that automatically uses
the Geo site closest to them. This means users don't need to update their Git
configuration to take advantage of closer Geo sites as they move.
This is possible because, Git push requests can be automatically redirected
(HTTP) or proxied (SSH) from **secondary** sites to the **primary** site.
Though these instructions use [AWS Route53](https://aws.amazon.com/route53/),
other services such as [Cloudflare](https://www.cloudflare.com/) could be used
as well.
## Prerequisites
In this example, we have already set up:
- `primary.example.com` as a Geo **primary** site.
- `secondary.example.com` as a Geo **secondary** site.
We create a `git.example.com` subdomain that automatically directs
requests:
- From Europe to the **secondary** site.
- From all other locations to the **primary** site.
In any case, you require:
- A working GitLab **primary** site that is accessible at its own address.
- A working GitLab **secondary** site.
- A Route53 Hosted Zone managing your domain.
If you haven't yet set up a Geo primary site and secondary site, see the
[Geo setup instructions](../setup/_index.md).
## Create a traffic policy
In a Route53 Hosted Zone, traffic policies can be used to set up a variety of
routing configurations.
1. Go to the
[Route53 dashboard](https://console.aws.amazon.com/route53/home) and select
**Traffic policies**.

1. Select **Create traffic policy**.

1. Fill in the **Policy Name** field with `Single Git Host` and select **Next**.

1. Leave **DNS type** as `A: IP Address in IPv4 format`.
1. Select **Connect to** and select **Geolocation rule**.

1. For the first **Location**, leave it as `Default`.
1. Select **Connect to** and select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **primary** IP address>`.
1. For the second **Location**, choose `Europe`.
1. Select **Connect to** and select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **secondary** IP address>`.

1. Select **Create traffic policy**.

1. Fill in **Policy record DNS name** with `git`.
1. Select **Create policy records**.

You have successfully set up a single host, for example, `git.example.com` which
distributes traffic to your Geo sites by geolocation!
## Configure Git clone URLs to use the special Git URL
When a user clones a repository for the first time, they typically copy the Git
remote URL from the project page. By default, these SSH and HTTP URLs are based
on the external URL of the current host. For example:
- `git@secondary.example.com:group1/project1.git`
- `https://secondary.example.com/group1/project1.git`

You can customize the:
- SSH remote URL to use the location-aware `git.example.com`. To do so, change the SSH remote URL
host by setting `gitlab_rails['gitlab_ssh_host']` in `gitlab.rb` of web nodes.
- HTTP remote URL as shown in
[Custom Git clone URL for HTTP(S)](../../settings/visibility_and_access_controls.md#customize-git-clone-url-for-https).
## Example Git request handling behavior
After following the configuration steps documented previously, handling for Git requests is now location aware.
For requests:
- Outside Europe, all requests are directed to the **primary** site.
- Within Europe, over:
- HTTP:
- `git clone http://git.example.com/foo/bar.git` is directed to the **secondary** site.
- `git push` is initially directed to the **secondary**, which automatically
redirects to `primary.example.com`.
- SSH:
- `git clone git@git.example.com:foo/bar.git` is directed to the **secondary**.
- `git push` is initially directed to the **secondary**, which automatically
proxies the request to `primary.example.com`.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Location-aware Git remote URL with AWS Route53
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
[GitLab Geo supports location-aware DNS including web UI and API traffic.](../secondary_proxy/_index.md#configure-location-aware-dns)
This configuration is recommended over the location-aware Git remote URL
described in this document.
{{< /alert >}}
You can provide GitLab users with a single remote URL that automatically uses
the Geo site closest to them. This means users don't need to update their Git
configuration to take advantage of closer Geo sites as they move.
This is possible because, Git push requests can be automatically redirected
(HTTP) or proxied (SSH) from **secondary** sites to the **primary** site.
Though these instructions use [AWS Route53](https://aws.amazon.com/route53/),
other services such as [Cloudflare](https://www.cloudflare.com/) could be used
as well.
## Prerequisites
In this example, we have already set up:
- `primary.example.com` as a Geo **primary** site.
- `secondary.example.com` as a Geo **secondary** site.
We create a `git.example.com` subdomain that automatically directs
requests:
- From Europe to the **secondary** site.
- From all other locations to the **primary** site.
In any case, you require:
- A working GitLab **primary** site that is accessible at its own address.
- A working GitLab **secondary** site.
- A Route53 Hosted Zone managing your domain.
If you haven't yet set up a Geo primary site and secondary site, see the
[Geo setup instructions](../setup/_index.md).
## Create a traffic policy
In a Route53 Hosted Zone, traffic policies can be used to set up a variety of
routing configurations.
1. Go to the
[Route53 dashboard](https://console.aws.amazon.com/route53/home) and select
**Traffic policies**.

1. Select **Create traffic policy**.

1. Fill in the **Policy Name** field with `Single Git Host` and select **Next**.

1. Leave **DNS type** as `A: IP Address in IPv4 format`.
1. Select **Connect to** and select **Geolocation rule**.

1. For the first **Location**, leave it as `Default`.
1. Select **Connect to** and select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **primary** IP address>`.
1. For the second **Location**, choose `Europe`.
1. Select **Connect to** and select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **secondary** IP address>`.

1. Select **Create traffic policy**.

1. Fill in **Policy record DNS name** with `git`.
1. Select **Create policy records**.

You have successfully set up a single host, for example, `git.example.com` which
distributes traffic to your Geo sites by geolocation!
## Configure Git clone URLs to use the special Git URL
When a user clones a repository for the first time, they typically copy the Git
remote URL from the project page. By default, these SSH and HTTP URLs are based
on the external URL of the current host. For example:
- `git@secondary.example.com:group1/project1.git`
- `https://secondary.example.com/group1/project1.git`

You can customize the:
- SSH remote URL to use the location-aware `git.example.com`. To do so, change the SSH remote URL
host by setting `gitlab_rails['gitlab_ssh_host']` in `gitlab.rb` of web nodes.
- HTTP remote URL as shown in
[Custom Git clone URL for HTTP(S)](../../settings/visibility_and_access_controls.md#customize-git-clone-url-for-https).
## Example Git request handling behavior
After following the configuration steps documented previously, handling for Git requests is now location aware.
For requests:
- Outside Europe, all requests are directed to the **primary** site.
- Within Europe, over:
- HTTP:
- `git clone http://git.example.com/foo/bar.git` is directed to the **secondary** site.
- `git push` is initially directed to the **secondary**, which automatically
redirects to `primary.example.com`.
- SSH:
- `git clone git@git.example.com:foo/bar.git` is directed to the **secondary**.
- `git push` is initially directed to the **secondary**, which automatically
proxies the request to `primary.example.com`.
|
https://docs.gitlab.com/administration/geo/tuning
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/tuning.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
tuning.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Tuning Geo
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can limit the number of concurrent operations the sites can run
in the background.
## Changing the sync/verification concurrency values
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Select **Edit** of the secondary site you want to tune.
1. Under **Tuning settings**, there are several variables that can be tuned to
improve the performance of Geo:
- Repository synchronization concurrency limit
- File synchronization concurrency limit
- Container repositories synchronization concurrency limit
- Verification concurrency limit
Increasing the concurrency values increases the number of jobs that are scheduled.
However, this may not lead to more downloads in parallel unless the number of
available Sidekiq threads is also increased. For example, if repository synchronization
concurrency is increased from 25 to 50, you may also want to increase the number
of Sidekiq threads from 25 to 50. See the
[Sidekiq concurrency documentation](../../sidekiq/extra_sidekiq_processes.md#concurrency)
for more details.
## Tuning low default settings
To avoid excessive load when setting up new Geo sites, starting with GitLab 18.0,
Geo's concurrency settings are set to low defaults for most environments.
To increase these settings:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Decide which data types are progressing too slowly.
1. Watch load metrics of the primary and secondary sites.
1. Increase concurrency limits by 10 to be conservative.
1. Watch changes in progress and load metrics for at least 3 minutes.
1. Repeat increasing the limits until either load metrics reach your desired maximum, or syncing and verification is progressing as quickly as desired.
## Repository re-verification
See
[Automatic background verification](../disaster_recovery/background_verification.md).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Tuning Geo
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can limit the number of concurrent operations the sites can run
in the background.
## Changing the sync/verification concurrency values
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Select **Edit** of the secondary site you want to tune.
1. Under **Tuning settings**, there are several variables that can be tuned to
improve the performance of Geo:
- Repository synchronization concurrency limit
- File synchronization concurrency limit
- Container repositories synchronization concurrency limit
- Verification concurrency limit
Increasing the concurrency values increases the number of jobs that are scheduled.
However, this may not lead to more downloads in parallel unless the number of
available Sidekiq threads is also increased. For example, if repository synchronization
concurrency is increased from 25 to 50, you may also want to increase the number
of Sidekiq threads from 25 to 50. See the
[Sidekiq concurrency documentation](../../sidekiq/extra_sidekiq_processes.md#concurrency)
for more details.
## Tuning low default settings
To avoid excessive load when setting up new Geo sites, starting with GitLab 18.0,
Geo's concurrency settings are set to low defaults for most environments.
To increase these settings:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Decide which data types are progressing too slowly.
1. Watch load metrics of the primary and secondary sites.
1. Increase concurrency limits by 10 to be conservative.
1. Watch changes in progress and load metrics for at least 3 minutes.
1. Repeat increasing the limits until either load metrics reach your desired maximum, or syncing and verification is progressing as quickly as desired.
## Repository re-verification
See
[Automatic background verification](../disaster_recovery/background_verification.md).
|
https://docs.gitlab.com/administration/geo/usage
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/usage.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
usage.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Using a Geo Site
| null |
<!-- Please update EE::GitLab::GeoGitAccess::GEO_SERVER_DOCS_URL if this file is moved) -->
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
After you set up the [database replication and configure the Geo nodes](../setup/_index.md), use your closest GitLab site as you would do with the primary one.
## Git operations
You can push directly to a **secondary** site (for both HTTP, SSH including
Git LFS), and the request is proxied to the primary site instead.
Example of the output you see when pushing to a **secondary** site:
```shell
$ git push
remote:
remote: This request to a Geo secondary node will be forwarded to the
remote: Geo primary node:
remote:
remote: ssh://git@primary.geo/user/repo.git
remote:
Everything up-to-date
```
{{< alert type="note" >}}
If you're using HTTPS instead of [SSH](../../../user/ssh.md) to push to the secondary,
you can't store credentials in the URL like `user:password@URL`. Instead, you can use a
[`.netrc` file](https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html)
for Unix-like operating systems or `_netrc` for Windows. In that case, the credentials
are stored as a plain text. If you're looking for a more secure way to store credentials,
you can use [Git Credential Storage](https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage).
{{< /alert >}}
## Web user interface
The web user interface on the **secondary** site is read/write. As a user, all actions permitted on the **primary** site can be performed on the **secondary** site without limitations.
Web interface access requests on the **secondary** sites are automatically and transparently proxied to the **primary** site.
## Fetch Go modules from Geo secondary sites
Go modules can be pulled from secondary sites, with a number of limitations:
- Git configuration (using `insteadOf`) is needed to fetch data from the Geo secondary site.
- For private projects, authentication details need to be specified in `~/.netrc`.
For more information, see
[Using a project as a Go package](../../../user/project/use_project_as_go_package.md#fetch-go-modules-from-geo-secondary-sites).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Using a Geo Site
breadcrumbs:
- doc
- administration
- geo
- replication
---
<!-- Please update EE::GitLab::GeoGitAccess::GEO_SERVER_DOCS_URL if this file is moved) -->
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
After you set up the [database replication and configure the Geo nodes](../setup/_index.md), use your closest GitLab site as you would do with the primary one.
## Git operations
You can push directly to a **secondary** site (for both HTTP, SSH including
Git LFS), and the request is proxied to the primary site instead.
Example of the output you see when pushing to a **secondary** site:
```shell
$ git push
remote:
remote: This request to a Geo secondary node will be forwarded to the
remote: Geo primary node:
remote:
remote: ssh://git@primary.geo/user/repo.git
remote:
Everything up-to-date
```
{{< alert type="note" >}}
If you're using HTTPS instead of [SSH](../../../user/ssh.md) to push to the secondary,
you can't store credentials in the URL like `user:password@URL`. Instead, you can use a
[`.netrc` file](https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html)
for Unix-like operating systems or `_netrc` for Windows. In that case, the credentials
are stored as a plain text. If you're looking for a more secure way to store credentials,
you can use [Git Credential Storage](https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage).
{{< /alert >}}
## Web user interface
The web user interface on the **secondary** site is read/write. As a user, all actions permitted on the **primary** site can be performed on the **secondary** site without limitations.
Web interface access requests on the **secondary** sites are automatically and transparently proxied to the **primary** site.
## Fetch Go modules from Geo secondary sites
Go modules can be pulled from secondary sites, with a number of limitations:
- Git configuration (using `insteadOf`) is needed to fetch data from the Geo secondary site.
- For private projects, authentication details need to be specified in `~/.netrc`.
For more information, see
[Using a project as a Go package](../../../user/project/use_project_as_go_package.md#fetch-go-modules-from-geo-secondary-sites).
|
https://docs.gitlab.com/administration/geo/multiple_servers
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/multiple_servers.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
multiple_servers.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo for multiple nodes
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This document describes a minimal reference architecture for running Geo
in a multi-node configuration. If your multi-node setup differs from the one
described, it is possible to adapt these instructions to your needs.
This guide applies to installations with multiple application nodes (Sidekiq or GitLab Rails).
For single-node installations with external PostgreSQL, follow [Set up Geo for two single-node sites (with external PostgreSQL services)](../setup/two_single_node_external_services.md),
and adapt your configuration if you use other external services.
## Architecture overview

**[diagram source - GitLab team members only](https://docs.google.com/drawings/d/1z0VlizKiLNXVVVaERFwgsIOuEgjcUqDTWPdQYsE7Z4c/edit)**
The topology diagram assumes the **primary** and **secondary** Geo sites
are located in two separate locations, on their own virtual network
with private IP addresses. The network is configured such that all machines in
one geographic location can communicate with each other using their private IP addresses.
The IP addresses given are examples and may be different depending on the
network topology of your deployment.
The only external way to access the two Geo sites is by HTTPS at
`gitlab.us.example.com` and `gitlab.eu.example.com` in the previous example.
{{< alert type="note" >}}
The **primary** and **secondary** Geo sites must be able to communicate to each other over HTTPS.
{{< /alert >}}
## Redis and PostgreSQL for multiple nodes
Because of the additional complexity involved in setting up this configuration
for PostgreSQL and Redis, it is not covered by this Geo multi-node documentation.
For more information on setting up a multi-node PostgreSQL cluster and Redis cluster using the Linux package, see:
- [Geo multi-node database replication](../setup/database.md#multi-node-database-replication)
- [Redis multi-node documentation](../../redis/replication_and_failover.md)
{{< alert type="note" >}}
It is possible to use cloud hosted services for PostgreSQL and Redis, but this is beyond the scope of this document.
{{< /alert >}}
## Prerequisites: Two independently working GitLab multi-node sites
One GitLab site serves as the Geo **primary** site. Use the
[GitLab reference architectures documentation](../../reference_architectures/_index.md)
to set this up. You can use different reference architecture sizes for each Geo site. If
you already have a working GitLab instance that is in-use, it can be used as a
**primary** site.
The second GitLab site serves as the Geo **secondary** site. Again, use the
[GitLab reference architectures documentation](../../reference_architectures/_index.md) to set this up.
It's a good idea to sign in and test it. However, be aware that its data is
wiped out as part of the process of replicating from the **primary** site.
## Configure a GitLab site to be the Geo **primary** site
The following steps enable a GitLab site to serve as the Geo **primary** site.
### Step 1: Configure the **primary** frontend nodes
{{< alert type="note" >}}
Do not use [`geo_primary_role`](https://docs.gitlab.com/omnibus/roles/#gitlab-geo-roles) because it is intended for a single-node site.
{{< /alert >}}
1. Edit `/etc/gitlab/gitlab.rb` and add the following:
```ruby
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
```
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
### Step 2: Define the site as the **primary** site
1. Execute the following command on one of the frontend nodes:
```shell
sudo gitlab-ctl set-geo-primary-node
```
{{< alert type="note" >}}
PostgreSQL and Redis should have already been disabled on the
application nodes during typical GitLab multi-node setup. Connections
from the application nodes to services on the backend nodes should
have also been configured. See multi-node configuration documentation for
[PostgreSQL](../../postgresql/replication_and_failover.md#configuring-the-application-nodes)
and [Redis](../../redis/replication_and_failover.md#example-configuration-for-the-gitlab-application).
{{< /alert >}}
## Configure the other GitLab site to be a Geo **secondary** site
A **secondary** site is similar to any other GitLab multi-node site, with three
major differences:
- The main PostgreSQL database is a read-only replica of the Geo **primary** site's
PostgreSQL database.
- There is an additional PostgreSQL database for each Geo **secondary** site,
called the "Geo tracking database", which tracks the replication and verification
state of various resources.
- There is an additional GitLab service [`geo-logcursor`](../_index.md#geo-log-cursor)
Therefore, we set up the multi-node components one by one and include deviations
from the typical multi-node setup. However, we highly recommend configuring a
brand-new GitLab site first, as if it were not part of a Geo setup. This allows
verifying that it is a working GitLab site. And only then should it be modified
for use as a Geo **secondary** site. This helps to separate Geo setup problems from
unrelated multi-node configuration problems.
### Step 1: Configure the Redis and Gitaly services on the Geo **secondary** site
Configure the following services, again using the non-Geo multi-node
documentation:
- [Configuring Redis for GitLab](../../redis/replication_and_failover.md#example-configuration-for-the-gitlab-application) for multiple nodes.
- [Gitaly](../../gitaly/_index.md), which stores data that is
synchronized from the Geo **primary** site.
{{< alert type="note" >}}
[NFS](../../nfs.md) can be used in place of Gitaly but is not
recommended.
{{< /alert >}}
### Step 2: Configure the Geo tracking database on the Geo **secondary** site
The Geo tracking database cannot be run in a multi-node PostgreSQL cluster,
see [Configuring Patroni cluster for the tracking PostgreSQL database](../setup/database.md#configuring-patroni-cluster-for-the-tracking-postgresql-database).
You can run the Geo tracking database on a single node as follows:
1. Generate an MD5 hash of the desired password for the database user that the
GitLab application uses to access the tracking database:
The username (`gitlab_geo` by default) is incorporated into the
hash.
```shell
gitlab-ctl pg-password-md5 gitlab_geo
# Enter password: <your_tracking_db_password_here>
# Confirm password: <your_tracking_db_password_here>
# fca0b89a972d69f00eb3ec98a5838484
```
Use this hash to fill in `<tracking_database_password_md5_hash>` in the next
step.
1. On the machine where the Geo tracking database is intended to run, add the
following to `/etc/gitlab/gitlab.rb`:
```ruby
##
## Enable the Geo secondary tracking database
##
geo_postgresql['enable'] = true
geo_postgresql['listen_address'] = '<ip_address_of_this_host>'
geo_postgresql['sql_user_password'] = '<tracking_database_password_md5_hash>'
##
## Configure PostgreSQL connection to the replica database
##
geo_postgresql['md5_auth_cidr_addresses'] = ['<replica_database_ip>/32']
gitlab_rails['db_host'] = '<replica_database_ip>'
# Prevent reconfigure from attempting to run migrations on the replica database
gitlab_rails['auto_migrate'] = false
```
1. [Opt out of automatic PostgreSQL upgrades](https://docs.gitlab.com/omnibus/settings/database/#opt-out-of-automatic-postgresql-upgrades) to avoid unintended downtime when upgrading GitLab. Be aware of the known [caveats when upgrading PostgreSQL with Geo](https://docs.gitlab.com/omnibus/settings/database/#caveats-when-upgrading-postgresql-with-geo). Especially for larger environments, PostgreSQL upgrades must be planned and executed consciously. As a result and going forward, ensure PostgreSQL upgrades are part of the regular maintenance activities.
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
If using an external PostgreSQL instance, refer also to
[Geo with external PostgreSQL instances](../setup/external_database.md).
### Step 3: Configure PostgreSQL streaming replication
Follow the [Geo database replication instructions](../setup/database.md).
If using an external PostgreSQL instance, refer also to
[Geo with external PostgreSQL instances](../setup/external_database.md).
After enabling streaming replication, `gitlab-rake db:migrate:status:geo` fails until [configuration of the secondary site is complete](#step-7-copy-secrets-and-add-the-secondary-site-in-the-application), specifically [Geo configuration - Step 3. Add the secondary site](configuration.md#step-3-add-the-secondary-site).
### Step 4: Configure the frontend application nodes on the Geo **secondary** site
{{< alert type="note" >}}
Do not use [`geo_secondary_role`](https://docs.gitlab.com/omnibus/roles/#gitlab-geo-roles) because it is intended for a single-node site.
{{< /alert >}}
In the minimal [architecture diagram](#architecture-overview), there are two
machines running the GitLab application services. These services are enabled
selectively in the configuration.
Configure the GitLab Rails application nodes following the relevant steps
outlined in the [reference architectures](../../reference_architectures/_index.md),
then make the following modifications:
1. Edit `/etc/gitlab/gitlab.rb` on each application node in the Geo **secondary**
site, and add the following:
```ruby
##
## Enable GitLab application services. The application_role enables many services.
## Alternatively, you can choose to enable or disable specific services on
## different nodes to aid in horizontal scaling and separation of concerns.
##
roles ['application_role']
## `application_role` already enables this. You only need this line if
## you selectively enable individual services that depend on Rails, like
## `puma`, `sidekiq`, `geo-logcursor`, and so on.
gitlab_rails['enable'] = true
##
## Enable Geo Log Cursor service
##
geo_logcursor['enable'] = true
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
##
## Configure the connection to the tracking database
##
geo_secondary['enable'] = true
geo_secondary['db_host'] = '<geo_tracking_db_host>'
geo_secondary['db_password'] = '<geo_tracking_db_password>'
##
## Configure connection to the streaming replica database, if you haven't
## already
##
gitlab_rails['db_host'] = '<replica_database_host>'
gitlab_rails['db_password'] = '<replica_database_password>'
##
## Configure connection to Redis, if you haven't already
##
gitlab_rails['redis_host'] = '<redis_host>'
gitlab_rails['redis_password'] = '<redis_password>'
##
## If you are using custom users not managed by Omnibus, you need to specify
## UIDs and GIDs like below, and ensure they match between nodes in a
## cluster to avoid permissions issues
##
user['uid'] = 9000
user['gid'] = 9000
web_server['uid'] = 9001
web_server['gid'] = 9001
registry['uid'] = 9002
registry['gid'] = 9002
```
{{< alert type="note" >}}
`postgresql['sql_user_password'] = 'md5 digest of secret'`
If you had set up PostgreSQL cluster using the Linux package and had set
`postgresql['sql_user_password'] = 'md5 digest of secret'`, keep in
mind that `gitlab_rails['db_password']` and `geo_secondary['db_password']`
contains the plaintext passwords. These configurations are used to let the Rails
nodes connect to the databases.
{{< /alert >}}
{{< alert type="note" >}}
Ensure that the current node's IP is listed in
`postgresql['md5_auth_cidr_addresses']` setting of the read-replica database to
allow Rails on this node to connect to PostgreSQL.
{{< /alert >}}
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
In the [architecture overview](#architecture-overview) topology, the following GitLab
services are enabled on the "frontend" nodes:
- `geo-logcursor`
- `gitlab-pages`
- `gitlab-workhorse`
- `logrotate`
- `nginx`
- `registry`
- `remote-syslog`
- `sidekiq`
- `puma`
Verify these services exist by running `sudo gitlab-ctl status` on the frontend
application nodes.
### Step 5: Set up the LoadBalancer for the Geo **secondary** site
The minimal [architecture diagram](#architecture-overview) shows a load
balancer at each geographic location to route traffic to the application nodes.
See [Load Balancer for GitLab with multiple nodes](../../load_balancer.md) for
more information.
### Step 6: Configure the backend application nodes on the Geo **secondary** site
The minimal [architecture diagram](#architecture-overview) shows all application services
running together on the same machines. However, for multiple nodes we
[strongly recommend running all services separately](../../reference_architectures/_index.md).
For example, a Sidekiq node could be configured similarly to the frontend
application nodes documented previously, with some changes to run only the `sidekiq` service:
1. Edit `/etc/gitlab/gitlab.rb` on each Sidekiq node in the Geo **secondary**
site, and add the following:
```ruby
##
## Enable the Sidekiq service
##
sidekiq['enable'] = true
gitlab_rails['enable'] = true
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
##
## Configure the connection to the tracking database
##
geo_secondary['enable'] = true
geo_secondary['db_host'] = '<geo_tracking_db_host>'
geo_secondary['db_password'] = '<geo_tracking_db_password>'
##
## Configure connection to the streaming replica database, if you haven't
## already
##
gitlab_rails['db_host'] = '<replica_database_host>'
gitlab_rails['db_password'] = '<replica_database_password>'
##
## Configure connection to Redis, if you haven't already
##
gitlab_rails['redis_host'] = '<redis_host>'
gitlab_rails['redis_password'] = '<redis_password>'
##
## If you are using custom users not managed by Omnibus, you need to specify
## UIDs and GIDs like below, and ensure they match between nodes in a
## cluster to avoid permissions issues
##
user['uid'] = 9000
user['gid'] = 9000
web_server['uid'] = 9001
web_server['gid'] = 9001
registry['uid'] = 9002
registry['gid'] = 9002
```
You can similarly configure a node to run only the `geo-logcursor` service
with `geo_logcursor['enable'] = true` and disabling Sidekiq with
`sidekiq['enable'] = false`.
These nodes do not need to be attached to the load balancer.
### Step 7: Copy secrets and add the secondary site in the application
1. [Configure GitLab](configuration.md) to set the **primary** and **secondary** sites.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Geo for multiple nodes
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This document describes a minimal reference architecture for running Geo
in a multi-node configuration. If your multi-node setup differs from the one
described, it is possible to adapt these instructions to your needs.
This guide applies to installations with multiple application nodes (Sidekiq or GitLab Rails).
For single-node installations with external PostgreSQL, follow [Set up Geo for two single-node sites (with external PostgreSQL services)](../setup/two_single_node_external_services.md),
and adapt your configuration if you use other external services.
## Architecture overview

**[diagram source - GitLab team members only](https://docs.google.com/drawings/d/1z0VlizKiLNXVVVaERFwgsIOuEgjcUqDTWPdQYsE7Z4c/edit)**
The topology diagram assumes the **primary** and **secondary** Geo sites
are located in two separate locations, on their own virtual network
with private IP addresses. The network is configured such that all machines in
one geographic location can communicate with each other using their private IP addresses.
The IP addresses given are examples and may be different depending on the
network topology of your deployment.
The only external way to access the two Geo sites is by HTTPS at
`gitlab.us.example.com` and `gitlab.eu.example.com` in the previous example.
{{< alert type="note" >}}
The **primary** and **secondary** Geo sites must be able to communicate to each other over HTTPS.
{{< /alert >}}
## Redis and PostgreSQL for multiple nodes
Because of the additional complexity involved in setting up this configuration
for PostgreSQL and Redis, it is not covered by this Geo multi-node documentation.
For more information on setting up a multi-node PostgreSQL cluster and Redis cluster using the Linux package, see:
- [Geo multi-node database replication](../setup/database.md#multi-node-database-replication)
- [Redis multi-node documentation](../../redis/replication_and_failover.md)
{{< alert type="note" >}}
It is possible to use cloud hosted services for PostgreSQL and Redis, but this is beyond the scope of this document.
{{< /alert >}}
## Prerequisites: Two independently working GitLab multi-node sites
One GitLab site serves as the Geo **primary** site. Use the
[GitLab reference architectures documentation](../../reference_architectures/_index.md)
to set this up. You can use different reference architecture sizes for each Geo site. If
you already have a working GitLab instance that is in-use, it can be used as a
**primary** site.
The second GitLab site serves as the Geo **secondary** site. Again, use the
[GitLab reference architectures documentation](../../reference_architectures/_index.md) to set this up.
It's a good idea to sign in and test it. However, be aware that its data is
wiped out as part of the process of replicating from the **primary** site.
## Configure a GitLab site to be the Geo **primary** site
The following steps enable a GitLab site to serve as the Geo **primary** site.
### Step 1: Configure the **primary** frontend nodes
{{< alert type="note" >}}
Do not use [`geo_primary_role`](https://docs.gitlab.com/omnibus/roles/#gitlab-geo-roles) because it is intended for a single-node site.
{{< /alert >}}
1. Edit `/etc/gitlab/gitlab.rb` and add the following:
```ruby
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
```
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
### Step 2: Define the site as the **primary** site
1. Execute the following command on one of the frontend nodes:
```shell
sudo gitlab-ctl set-geo-primary-node
```
{{< alert type="note" >}}
PostgreSQL and Redis should have already been disabled on the
application nodes during typical GitLab multi-node setup. Connections
from the application nodes to services on the backend nodes should
have also been configured. See multi-node configuration documentation for
[PostgreSQL](../../postgresql/replication_and_failover.md#configuring-the-application-nodes)
and [Redis](../../redis/replication_and_failover.md#example-configuration-for-the-gitlab-application).
{{< /alert >}}
## Configure the other GitLab site to be a Geo **secondary** site
A **secondary** site is similar to any other GitLab multi-node site, with three
major differences:
- The main PostgreSQL database is a read-only replica of the Geo **primary** site's
PostgreSQL database.
- There is an additional PostgreSQL database for each Geo **secondary** site,
called the "Geo tracking database", which tracks the replication and verification
state of various resources.
- There is an additional GitLab service [`geo-logcursor`](../_index.md#geo-log-cursor)
Therefore, we set up the multi-node components one by one and include deviations
from the typical multi-node setup. However, we highly recommend configuring a
brand-new GitLab site first, as if it were not part of a Geo setup. This allows
verifying that it is a working GitLab site. And only then should it be modified
for use as a Geo **secondary** site. This helps to separate Geo setup problems from
unrelated multi-node configuration problems.
### Step 1: Configure the Redis and Gitaly services on the Geo **secondary** site
Configure the following services, again using the non-Geo multi-node
documentation:
- [Configuring Redis for GitLab](../../redis/replication_and_failover.md#example-configuration-for-the-gitlab-application) for multiple nodes.
- [Gitaly](../../gitaly/_index.md), which stores data that is
synchronized from the Geo **primary** site.
{{< alert type="note" >}}
[NFS](../../nfs.md) can be used in place of Gitaly but is not
recommended.
{{< /alert >}}
### Step 2: Configure the Geo tracking database on the Geo **secondary** site
The Geo tracking database cannot be run in a multi-node PostgreSQL cluster,
see [Configuring Patroni cluster for the tracking PostgreSQL database](../setup/database.md#configuring-patroni-cluster-for-the-tracking-postgresql-database).
You can run the Geo tracking database on a single node as follows:
1. Generate an MD5 hash of the desired password for the database user that the
GitLab application uses to access the tracking database:
The username (`gitlab_geo` by default) is incorporated into the
hash.
```shell
gitlab-ctl pg-password-md5 gitlab_geo
# Enter password: <your_tracking_db_password_here>
# Confirm password: <your_tracking_db_password_here>
# fca0b89a972d69f00eb3ec98a5838484
```
Use this hash to fill in `<tracking_database_password_md5_hash>` in the next
step.
1. On the machine where the Geo tracking database is intended to run, add the
following to `/etc/gitlab/gitlab.rb`:
```ruby
##
## Enable the Geo secondary tracking database
##
geo_postgresql['enable'] = true
geo_postgresql['listen_address'] = '<ip_address_of_this_host>'
geo_postgresql['sql_user_password'] = '<tracking_database_password_md5_hash>'
##
## Configure PostgreSQL connection to the replica database
##
geo_postgresql['md5_auth_cidr_addresses'] = ['<replica_database_ip>/32']
gitlab_rails['db_host'] = '<replica_database_ip>'
# Prevent reconfigure from attempting to run migrations on the replica database
gitlab_rails['auto_migrate'] = false
```
1. [Opt out of automatic PostgreSQL upgrades](https://docs.gitlab.com/omnibus/settings/database/#opt-out-of-automatic-postgresql-upgrades) to avoid unintended downtime when upgrading GitLab. Be aware of the known [caveats when upgrading PostgreSQL with Geo](https://docs.gitlab.com/omnibus/settings/database/#caveats-when-upgrading-postgresql-with-geo). Especially for larger environments, PostgreSQL upgrades must be planned and executed consciously. As a result and going forward, ensure PostgreSQL upgrades are part of the regular maintenance activities.
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
If using an external PostgreSQL instance, refer also to
[Geo with external PostgreSQL instances](../setup/external_database.md).
### Step 3: Configure PostgreSQL streaming replication
Follow the [Geo database replication instructions](../setup/database.md).
If using an external PostgreSQL instance, refer also to
[Geo with external PostgreSQL instances](../setup/external_database.md).
After enabling streaming replication, `gitlab-rake db:migrate:status:geo` fails until [configuration of the secondary site is complete](#step-7-copy-secrets-and-add-the-secondary-site-in-the-application), specifically [Geo configuration - Step 3. Add the secondary site](configuration.md#step-3-add-the-secondary-site).
### Step 4: Configure the frontend application nodes on the Geo **secondary** site
{{< alert type="note" >}}
Do not use [`geo_secondary_role`](https://docs.gitlab.com/omnibus/roles/#gitlab-geo-roles) because it is intended for a single-node site.
{{< /alert >}}
In the minimal [architecture diagram](#architecture-overview), there are two
machines running the GitLab application services. These services are enabled
selectively in the configuration.
Configure the GitLab Rails application nodes following the relevant steps
outlined in the [reference architectures](../../reference_architectures/_index.md),
then make the following modifications:
1. Edit `/etc/gitlab/gitlab.rb` on each application node in the Geo **secondary**
site, and add the following:
```ruby
##
## Enable GitLab application services. The application_role enables many services.
## Alternatively, you can choose to enable or disable specific services on
## different nodes to aid in horizontal scaling and separation of concerns.
##
roles ['application_role']
## `application_role` already enables this. You only need this line if
## you selectively enable individual services that depend on Rails, like
## `puma`, `sidekiq`, `geo-logcursor`, and so on.
gitlab_rails['enable'] = true
##
## Enable Geo Log Cursor service
##
geo_logcursor['enable'] = true
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
##
## Configure the connection to the tracking database
##
geo_secondary['enable'] = true
geo_secondary['db_host'] = '<geo_tracking_db_host>'
geo_secondary['db_password'] = '<geo_tracking_db_password>'
##
## Configure connection to the streaming replica database, if you haven't
## already
##
gitlab_rails['db_host'] = '<replica_database_host>'
gitlab_rails['db_password'] = '<replica_database_password>'
##
## Configure connection to Redis, if you haven't already
##
gitlab_rails['redis_host'] = '<redis_host>'
gitlab_rails['redis_password'] = '<redis_password>'
##
## If you are using custom users not managed by Omnibus, you need to specify
## UIDs and GIDs like below, and ensure they match between nodes in a
## cluster to avoid permissions issues
##
user['uid'] = 9000
user['gid'] = 9000
web_server['uid'] = 9001
web_server['gid'] = 9001
registry['uid'] = 9002
registry['gid'] = 9002
```
{{< alert type="note" >}}
`postgresql['sql_user_password'] = 'md5 digest of secret'`
If you had set up PostgreSQL cluster using the Linux package and had set
`postgresql['sql_user_password'] = 'md5 digest of secret'`, keep in
mind that `gitlab_rails['db_password']` and `geo_secondary['db_password']`
contains the plaintext passwords. These configurations are used to let the Rails
nodes connect to the databases.
{{< /alert >}}
{{< alert type="note" >}}
Ensure that the current node's IP is listed in
`postgresql['md5_auth_cidr_addresses']` setting of the read-replica database to
allow Rails on this node to connect to PostgreSQL.
{{< /alert >}}
After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so the changes take effect.
In the [architecture overview](#architecture-overview) topology, the following GitLab
services are enabled on the "frontend" nodes:
- `geo-logcursor`
- `gitlab-pages`
- `gitlab-workhorse`
- `logrotate`
- `nginx`
- `registry`
- `remote-syslog`
- `sidekiq`
- `puma`
Verify these services exist by running `sudo gitlab-ctl status` on the frontend
application nodes.
### Step 5: Set up the LoadBalancer for the Geo **secondary** site
The minimal [architecture diagram](#architecture-overview) shows a load
balancer at each geographic location to route traffic to the application nodes.
See [Load Balancer for GitLab with multiple nodes](../../load_balancer.md) for
more information.
### Step 6: Configure the backend application nodes on the Geo **secondary** site
The minimal [architecture diagram](#architecture-overview) shows all application services
running together on the same machines. However, for multiple nodes we
[strongly recommend running all services separately](../../reference_architectures/_index.md).
For example, a Sidekiq node could be configured similarly to the frontend
application nodes documented previously, with some changes to run only the `sidekiq` service:
1. Edit `/etc/gitlab/gitlab.rb` on each Sidekiq node in the Geo **secondary**
site, and add the following:
```ruby
##
## Enable the Sidekiq service
##
sidekiq['enable'] = true
gitlab_rails['enable'] = true
##
## The unique identifier for the Geo site. See
## https://docs.gitlab.com/ee/administration/geo_sites.html#common-settings
##
gitlab_rails['geo_node_name'] = '<site_name_here>'
##
## Disable automatic migrations
##
gitlab_rails['auto_migrate'] = false
##
## Configure the connection to the tracking database
##
geo_secondary['enable'] = true
geo_secondary['db_host'] = '<geo_tracking_db_host>'
geo_secondary['db_password'] = '<geo_tracking_db_password>'
##
## Configure connection to the streaming replica database, if you haven't
## already
##
gitlab_rails['db_host'] = '<replica_database_host>'
gitlab_rails['db_password'] = '<replica_database_password>'
##
## Configure connection to Redis, if you haven't already
##
gitlab_rails['redis_host'] = '<redis_host>'
gitlab_rails['redis_password'] = '<redis_password>'
##
## If you are using custom users not managed by Omnibus, you need to specify
## UIDs and GIDs like below, and ensure they match between nodes in a
## cluster to avoid permissions issues
##
user['uid'] = 9000
user['gid'] = 9000
web_server['uid'] = 9001
web_server['gid'] = 9001
registry['uid'] = 9002
registry['gid'] = 9002
```
You can similarly configure a node to run only the `geo-logcursor` service
with `geo_logcursor['enable'] = true` and disabling Sidekiq with
`sidekiq['enable'] = false`.
These nodes do not need to be attached to the load balancer.
### Step 7: Copy secrets and add the secondary site in the application
1. [Configure GitLab](configuration.md) to set the **primary** and **secondary** sites.
|
https://docs.gitlab.com/administration/geo/disable_geo
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/disable_geo.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
disable_geo.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Disabling Geo
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you want to revert to a regular Linux package installation setup after a test, or you have encountered a Disaster Recovery
situation and you want to disable Geo momentarily, you can use these instructions to disable your
Geo setup.
There should be no functional difference between disabling Geo and having an active Geo setup with
no secondary Geo sites if you remove them correctly.
To disable Geo, follow these steps:
1. [Remove all secondary Geo sites](#remove-all-secondary-geo-sites).
1. [Remove the primary site from the UI](#remove-the-primary-site-from-the-ui).
1. [Remove secondary replication slots](#remove-secondary-replication-slots).
1. [Remove Geo-related configuration](#remove-geo-related-configuration).
1. [Optional. Revert PostgreSQL settings to use a password and listen on an IP](#optional-revert-postgresql-settings-to-use-a-password-and-listen-on-an-ip).
## Remove all secondary Geo sites
To disable Geo, you need to first remove all your secondary Geo sites, which means replication does not happen
anymore on these sites. You can follow our documentation to [remove your secondary Geo sites](remove_geo_site.md).
If the current site that you want to keep using is a secondary site, you need to first promote it to primary.
You can use our steps on [how to promote a secondary site](../disaster_recovery/_index.md#step-3-promoting-a-secondary-site)
to do that.
## Remove the primary site from the UI
To remove the **primary** site:
1. [Remove all secondary Geo sites](remove_geo_site.md)
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
1. Select **Remove** for the **primary** node.
1. Confirm by selecting **Remove** when the prompt appears.
## Remove secondary replication slots
To remove secondary replication slots, run one of the following queries on your primary
Geo node in a PostgreSQL console (`sudo gitlab-psql`):
- If you already have a PostgreSQL cluster, drop individual replication slots by name to prevent
removing your secondary databases from the same cluster. You can use the following to get
all names and then drop each individual slot:
```sql
SELECT slot_name, slot_type, active FROM pg_replication_slots; -- view present replication slots
SELECT pg_drop_replication_slot('slot_name'); -- where slot_name is the one expected from the previous command
```
- To remove all secondary replication slots:
```sql
SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots;
```
## Remove Geo-related configuration
1. For each node on your primary Geo site, SSH into the node and sign in as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb` and remove the Geo related configuration by
removing any lines that enabled `geo_primary_role`:
```ruby
## In pre-11.5 documentation, the role was enabled as follows. Remove this line.
geo_primary_role['enable'] = true
## In 11.5+ documentation, the role was enabled as follows. Remove this line.
roles ['geo_primary_role']
```
1. After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
## (Optional) Revert PostgreSQL settings to use a password and listen on an IP
If you want to remove the PostgreSQL-specific settings and revert
to the defaults (using a socket instead), you can safely remove the following
lines from the `/etc/gitlab/gitlab.rb` file:
```ruby
postgresql['sql_user_password'] = '...'
gitlab_rails['db_password'] = '...'
postgresql['listen_address'] = '...'
postgresql['md5_auth_cidr_addresses'] = ['...', '...']
```
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Disabling Geo
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you want to revert to a regular Linux package installation setup after a test, or you have encountered a Disaster Recovery
situation and you want to disable Geo momentarily, you can use these instructions to disable your
Geo setup.
There should be no functional difference between disabling Geo and having an active Geo setup with
no secondary Geo sites if you remove them correctly.
To disable Geo, follow these steps:
1. [Remove all secondary Geo sites](#remove-all-secondary-geo-sites).
1. [Remove the primary site from the UI](#remove-the-primary-site-from-the-ui).
1. [Remove secondary replication slots](#remove-secondary-replication-slots).
1. [Remove Geo-related configuration](#remove-geo-related-configuration).
1. [Optional. Revert PostgreSQL settings to use a password and listen on an IP](#optional-revert-postgresql-settings-to-use-a-password-and-listen-on-an-ip).
## Remove all secondary Geo sites
To disable Geo, you need to first remove all your secondary Geo sites, which means replication does not happen
anymore on these sites. You can follow our documentation to [remove your secondary Geo sites](remove_geo_site.md).
If the current site that you want to keep using is a secondary site, you need to first promote it to primary.
You can use our steps on [how to promote a secondary site](../disaster_recovery/_index.md#step-3-promoting-a-secondary-site)
to do that.
## Remove the primary site from the UI
To remove the **primary** site:
1. [Remove all secondary Geo sites](remove_geo_site.md)
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
1. Select **Remove** for the **primary** node.
1. Confirm by selecting **Remove** when the prompt appears.
## Remove secondary replication slots
To remove secondary replication slots, run one of the following queries on your primary
Geo node in a PostgreSQL console (`sudo gitlab-psql`):
- If you already have a PostgreSQL cluster, drop individual replication slots by name to prevent
removing your secondary databases from the same cluster. You can use the following to get
all names and then drop each individual slot:
```sql
SELECT slot_name, slot_type, active FROM pg_replication_slots; -- view present replication slots
SELECT pg_drop_replication_slot('slot_name'); -- where slot_name is the one expected from the previous command
```
- To remove all secondary replication slots:
```sql
SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots;
```
## Remove Geo-related configuration
1. For each node on your primary Geo site, SSH into the node and sign in as root:
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb` and remove the Geo related configuration by
removing any lines that enabled `geo_primary_role`:
```ruby
## In pre-11.5 documentation, the role was enabled as follows. Remove this line.
geo_primary_role['enable'] = true
## In 11.5+ documentation, the role was enabled as follows. Remove this line.
roles ['geo_primary_role']
```
1. After making these changes, [reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
## (Optional) Revert PostgreSQL settings to use a password and listen on an IP
If you want to remove the PostgreSQL-specific settings and revert
to the defaults (using a socket instead), you can safely remove the following
lines from the `/etc/gitlab/gitlab.rb` file:
```ruby
postgresql['sql_user_password'] = '...'
gitlab_rails['db_password'] = '...'
postgresql['listen_address'] = '...'
postgresql['md5_auth_cidr_addresses'] = ['...', '...']
```
|
https://docs.gitlab.com/administration/geo/pause_resume_replication
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/pause_resume_replication.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
pause_resume_replication.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Pausing and resuming replication
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="warning" >}}
Pausing and resuming of replication is only supported for Geo installations using a
Linux package-managed database. External databases are not supported.
**Do not pause replication** if the primary site has failed catastrophically and cannot be recovered. This can create unreachable recovery targets that prevent successful promotion of the secondary site.
{{< /alert >}}
In some circumstances, like during [upgrades](upgrading_the_geo_sites.md) or a
[planned failover](../disaster_recovery/planned_failover.md), it is desirable to pause replication between the primary and secondary.
If you plan to allow user activity on your secondary sites during the upgrade,
do not pause replication for a [zero-downtime upgrade](../../../update/zero_downtime.md). While paused, the secondary site gets more and more out-of-date.
One known effect is that more and more Git fetches get redirected or proxied to the primary site. There may be additional unknown effects.
For example, pausing a secondary site with a separate URL may break sign-in at the secondary site's URL. You land on the primary site's root URL, without a new session on the secondary site's URL.
## Pause and resume
Pausing and resuming replication is done through a command-line tool from a specific node in the secondary site. Depending on your database architecture,
this targets either the `postgresql` or `patroni` service:
- If you are using a single node for all services on your secondary site, you must run the commands on this single node.
- If you have a standalone PostgreSQL node on your secondary site, you must run the commands on this standalone PostgreSQL node.
- If your secondary site is using a Patroni cluster, you must run these commands on the secondary Patroni standby leader node.
If you aren't using a single node for all services on your secondary site, ensure that the `/etc/gitlab/gitlab.rb` on your PostgreSQL or Patroni nodes
contains the configuration line `gitlab_rails['geo_node_name'] = 'node_name'`, where `node_name` is the same as the `geo_node_name` on the application node.
**To Pause: (from secondary site)**
Also, be aware that if PostgreSQL is restarted after pausing replication (either by restarting the VM or restarting the service with `gitlab-ctl restart postgresql`), PostgreSQL automatically resumes replication, which is something you wouldn't want during an upgrade or in a planned failover scenario.
```shell
gitlab-ctl geo-replication-pause
```
**To Resume: (from secondary site)**
```shell
gitlab-ctl geo-replication-resume
```
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Pausing and resuming replication
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="warning" >}}
Pausing and resuming of replication is only supported for Geo installations using a
Linux package-managed database. External databases are not supported.
**Do not pause replication** if the primary site has failed catastrophically and cannot be recovered. This can create unreachable recovery targets that prevent successful promotion of the secondary site.
{{< /alert >}}
In some circumstances, like during [upgrades](upgrading_the_geo_sites.md) or a
[planned failover](../disaster_recovery/planned_failover.md), it is desirable to pause replication between the primary and secondary.
If you plan to allow user activity on your secondary sites during the upgrade,
do not pause replication for a [zero-downtime upgrade](../../../update/zero_downtime.md). While paused, the secondary site gets more and more out-of-date.
One known effect is that more and more Git fetches get redirected or proxied to the primary site. There may be additional unknown effects.
For example, pausing a secondary site with a separate URL may break sign-in at the secondary site's URL. You land on the primary site's root URL, without a new session on the secondary site's URL.
## Pause and resume
Pausing and resuming replication is done through a command-line tool from a specific node in the secondary site. Depending on your database architecture,
this targets either the `postgresql` or `patroni` service:
- If you are using a single node for all services on your secondary site, you must run the commands on this single node.
- If you have a standalone PostgreSQL node on your secondary site, you must run the commands on this standalone PostgreSQL node.
- If your secondary site is using a Patroni cluster, you must run these commands on the secondary Patroni standby leader node.
If you aren't using a single node for all services on your secondary site, ensure that the `/etc/gitlab/gitlab.rb` on your PostgreSQL or Patroni nodes
contains the configuration line `gitlab_rails['geo_node_name'] = 'node_name'`, where `node_name` is the same as the `geo_node_name` on the application node.
**To Pause: (from secondary site)**
Also, be aware that if PostgreSQL is restarted after pausing replication (either by restarting the VM or restarting the service with `gitlab-ctl restart postgresql`), PostgreSQL automatically resumes replication, which is something you wouldn't want during an upgrade or in a planned failover scenario.
```shell
gitlab-ctl geo-replication-pause
```
**To Resume: (from secondary site)**
```shell
gitlab-ctl geo-replication-resume
```
|
https://docs.gitlab.com/administration/geo/container_registry
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/container_registry.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
container_registry.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Container registry for a secondary site
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can set up a container registry on your **secondary** Geo site that mirrors the one on the **primary** Geo site. This container registry replication is used only for disaster recovery purposes.
Do not push to the container registry on the **secondary** Geo site, because the data is not propagated to the **primary** site.
We do not recommend pulling container registry data from the **secondary** site because it may be stale. The feature request [issue 365864](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) would solve this problem. You are encouraged to upvote the issue to register your interest.
## Supported container registries
Geo supports the following types of container registries:
- [Docker](https://distribution.github.io/distribution/)
- [OCI](https://github.com/opencontainers/distribution-spec/blob/main/spec.md)
## Supported image formats
The following container image formats are support by Geo:
- [Docker V2, schema 1](https://distribution.github.io/distribution/spec/deprecated-schema-v1/)
- [Docker V2, schema 2](https://distribution.github.io/distribution/spec/manifest-v2-2/)
- [OCI (Open Container Initiative)](https://github.com/opencontainers/image-spec)
In addition, Geo also supports [BuildKit cache images](https://github.com/moby/buildkit).
## Supported storage
### Docker
For more information on supported registry storage drivers see
[Docker registry storage drivers](https://distribution.github.io/distribution/storage-drivers/)
Read the [Load balancing considerations](https://distribution.github.io/distribution/about/deploying/#load-balancing-considerations)
when deploying the Registry, and how to set up the storage driver for the GitLab integrated
[container registry](../../packages/container_registry.md#use-object-storage).
### Registries that support OCI artifacts
The following registries support OCI artifacts:
- CNCF Distribution - local/offline verification
- Azure Container Registry (ACR)
- Amazon Elastic Container Registry (ECR)
- Google Artifact Registry (GAR)
- GitHub Packages container registry (GHCR)
- Bundle Bar
For more information, see the [OCI Distribution Specification](https://github.com/opencontainers/distribution-spec).
## Configure container registry replication
You can enable a storage-agnostic replication so it
can be used for cloud or local storage. Whenever a new image is pushed to the
**primary** site, each **secondary** site pulls it to its own container
repository.
To configure container registry replication:
1. Configure the [**primary** site](#configure-primary-site).
1. Configure the [**secondary** site](#configure-secondary-site).
1. Verify container registry [replication](#verify-replication).
### Configure primary site
Make sure that you have container registry set up and working on
the **primary** site before following the next steps.
To be able to replicate new container images, the container registry must send notification events to the
**primary** site for every push. The token shared between the container registry and the web nodes on the
**primary** is used to make communication more secure.
1. SSH into your GitLab **primary** server and sign in as root (for GitLab HA, you only need a Registry node):
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Configure the registry to listen on the public/internal interface
# Replace with the appropriate interface (for example, '0.0.0.0' for all interfaces)
registry['registry_http_addr'] = '0.0.0.0:5000'
registry['notifications'] = [
{
'name' => 'geo_event',
'url' => 'https://<example.com>/api/v4/container_registry_event/events',
'timeout' => '500ms',
'threshold' => 5,
'backoff' => '1s',
'headers' => {
'Authorization' => ['<replace_with_a_secret_token>']
}
}
]
```
{{< alert type="note" >}}
Replace `<example.com>` with the `external_url` defined in your primary site's `/etc/gitlab/gitlab.rb` file, and
replace `<replace_with_a_secret_token>` with a case-sensitive alphanumeric string
that starts with a letter. You can generate one with `< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c 32 | sed "s/^[0-9]*//"; echo`
{{< /alert >}}
{{< alert type="note" >}}
If you use an external Registry (not the one integrated with GitLab), you only need to specify
the notification secret (`registry['notification_secret']`) in the
`/etc/gitlab/gitlab.rb` file.
{{< /alert >}}
1. For GitLab HA only. Edit `/etc/gitlab/gitlab.rb` on every web node:
```ruby
registry['notification_secret'] = '<replace_with_a_secret_token_generated_above>'
```
1. Reconfigure each node you just updated:
```shell
gitlab-ctl reconfigure
```
### Configure secondary site
Make sure you have container registry set up and working on
the **secondary** site before following the next steps.
The following steps should be done on each **secondary** site you're
expecting to see the container images replicated.
Because we need to allow the **secondary** site to communicate securely with
the **primary** site container registry, we need to have a single key
pair for all the sites. The **secondary** site uses this key to
generate a short-lived JWT that is pull-only-capable to access the
**primary** site container registry.
For each application and Sidekiq node on the **secondary** site:
1. SSH into the node and sign in as the `root` user:
```shell
sudo -i
```
1. Copy `/var/opt/gitlab/gitlab-rails/etc/gitlab-registry.key` from the **primary** to the node.
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
gitlab_rails['geo_registry_replication_enabled'] = true
# Primary registry's hostname and port, it will be used by
# the secondary node to directly communicate to primary registry
gitlab_rails['geo_registry_replication_primary_api_url'] = 'https://primary.example.com:5050/'
```
1. Reconfigure the node for the change to take effect:
```shell
gitlab-ctl reconfigure
```
### Verify replication
To verify container registry replication is working, on the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
The initial replication, or "backfill", is probably still in progress.
You can monitor the synchronization process on each Geo site from the **primary** site's **Geo Nodes** dashboard in your browser.
## Troubleshooting
### Confirm that container registry replication is enabled
This can be done with a check using the [Rails console](../../operations/rails_console.md#starting-a-rails-console-session):
```ruby
Geo::ContainerRepositoryRegistry.replication_enabled?
```
### Missing container registry notification event
1. When an image is pushed to the primary site's container registry, it should trigger a [Container Registry notification](../../packages/container_registry.md#configure-container-registry-notifications)
1. The primary site's container registry calls the primary site's API on `https://<example.com>/api/v4/container_registry_event/events`
1. The primary site inserts a record to the `geo_events` table with `replicable_name: 'container_repository', model_record_id: <ID of the container repository>`.
1. The record gets replicated by PostgreSQL to the secondary site's database.
1. The Geo Log Cursor service processes the new event and enqueues a Sidekiq job `Geo::EventWorker`
To verify this is working correctly, push an image to the registry on the primary site, and run the following command on the Rails console to verify that the notification was received, and processed into an event:
```ruby
Geo::Event.where(replicable_name: 'container_repository')
```
You can further verify this by checking `geo.log` for entries from `Geo::ContainerRepositorySyncService`.
### Registry events logs response status 401 Unauthorized unaccepted
`401 Unauthorized` errors indicate that the primary site's container registry notification is not accepted by the Rails application, preventing it from notifying GitLab that something was pushed.
To fix this, make sure that the authorization headers being sent with the registry notification match what's configured on the primary site, as should be done during step [Configure primary site](#configure-primary-site).
#### Registry error: `token from untrusted issuer: "<token>"`
When replicating container images in Geo, you might see the error `token from untrusted issuer: "<token>"`.
This issue occurs when the container registry configuration is incorrect, causing Sidekiq's JWT
authentication to fail.
To resolve this issue:
1. Ensure both sites share a single signing key pair, as described in [configure secondary site](#configure-secondary-site).
1. Verify that both container registries and both primary and secondary sites are configured
to use the same token issuer. For more information, see
[configure GitLab and registry on separate nodes](../../packages/container_registry.md#configure-gitlab-and-registry-on-separate-nodes-linux-package-installations).
1. For multi-node deployments, confirm that the issuer configured on the Sidekiq node matches
the value configured on the registries.
### Manually trigger a container registry sync event
To help with troubleshooting, you can manually trigger the container registry replication process:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. In **Replication Details** for a **Secondary Site**, select **Container Repositories**.
1. Select **Resync** for one row, or **Resync all**.
You can also manually trigger a resync by running the following commands on the secondary's Rails console:
```ruby
registry = Geo::ContainerRepositoryRegistry.first # Choose a Geo registry entry
registry.replicator.sync # Resync the container repository
pp registry.reload # Look at replication state fields
#<Geo::ContainerRepositoryRegistry:0x00007f54c2a36060
id: 1,
container_repository_id: 1,
state: "2",
retry_count: 0,
last_sync_failure: nil,
retry_at: nil,
last_synced_at: Thu, 28 Sep 2023 19:38:05.823680000 UTC +00:00,
created_at: Mon, 11 Sep 2023 15:38:06.262490000 UTC +00:00>
```
The `state` field represents sync state:
- `"0"`: pending sync (usually means it was never synced)
- `"1"`: started sync (a sync job is currently running)
- `"2"`: successfully synced
- `"3"`: failed to sync
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Container registry for a secondary site
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can set up a container registry on your **secondary** Geo site that mirrors the one on the **primary** Geo site. This container registry replication is used only for disaster recovery purposes.
Do not push to the container registry on the **secondary** Geo site, because the data is not propagated to the **primary** site.
We do not recommend pulling container registry data from the **secondary** site because it may be stale. The feature request [issue 365864](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) would solve this problem. You are encouraged to upvote the issue to register your interest.
## Supported container registries
Geo supports the following types of container registries:
- [Docker](https://distribution.github.io/distribution/)
- [OCI](https://github.com/opencontainers/distribution-spec/blob/main/spec.md)
## Supported image formats
The following container image formats are support by Geo:
- [Docker V2, schema 1](https://distribution.github.io/distribution/spec/deprecated-schema-v1/)
- [Docker V2, schema 2](https://distribution.github.io/distribution/spec/manifest-v2-2/)
- [OCI (Open Container Initiative)](https://github.com/opencontainers/image-spec)
In addition, Geo also supports [BuildKit cache images](https://github.com/moby/buildkit).
## Supported storage
### Docker
For more information on supported registry storage drivers see
[Docker registry storage drivers](https://distribution.github.io/distribution/storage-drivers/)
Read the [Load balancing considerations](https://distribution.github.io/distribution/about/deploying/#load-balancing-considerations)
when deploying the Registry, and how to set up the storage driver for the GitLab integrated
[container registry](../../packages/container_registry.md#use-object-storage).
### Registries that support OCI artifacts
The following registries support OCI artifacts:
- CNCF Distribution - local/offline verification
- Azure Container Registry (ACR)
- Amazon Elastic Container Registry (ECR)
- Google Artifact Registry (GAR)
- GitHub Packages container registry (GHCR)
- Bundle Bar
For more information, see the [OCI Distribution Specification](https://github.com/opencontainers/distribution-spec).
## Configure container registry replication
You can enable a storage-agnostic replication so it
can be used for cloud or local storage. Whenever a new image is pushed to the
**primary** site, each **secondary** site pulls it to its own container
repository.
To configure container registry replication:
1. Configure the [**primary** site](#configure-primary-site).
1. Configure the [**secondary** site](#configure-secondary-site).
1. Verify container registry [replication](#verify-replication).
### Configure primary site
Make sure that you have container registry set up and working on
the **primary** site before following the next steps.
To be able to replicate new container images, the container registry must send notification events to the
**primary** site for every push. The token shared between the container registry and the web nodes on the
**primary** is used to make communication more secure.
1. SSH into your GitLab **primary** server and sign in as root (for GitLab HA, you only need a Registry node):
```shell
sudo -i
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Configure the registry to listen on the public/internal interface
# Replace with the appropriate interface (for example, '0.0.0.0' for all interfaces)
registry['registry_http_addr'] = '0.0.0.0:5000'
registry['notifications'] = [
{
'name' => 'geo_event',
'url' => 'https://<example.com>/api/v4/container_registry_event/events',
'timeout' => '500ms',
'threshold' => 5,
'backoff' => '1s',
'headers' => {
'Authorization' => ['<replace_with_a_secret_token>']
}
}
]
```
{{< alert type="note" >}}
Replace `<example.com>` with the `external_url` defined in your primary site's `/etc/gitlab/gitlab.rb` file, and
replace `<replace_with_a_secret_token>` with a case-sensitive alphanumeric string
that starts with a letter. You can generate one with `< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c 32 | sed "s/^[0-9]*//"; echo`
{{< /alert >}}
{{< alert type="note" >}}
If you use an external Registry (not the one integrated with GitLab), you only need to specify
the notification secret (`registry['notification_secret']`) in the
`/etc/gitlab/gitlab.rb` file.
{{< /alert >}}
1. For GitLab HA only. Edit `/etc/gitlab/gitlab.rb` on every web node:
```ruby
registry['notification_secret'] = '<replace_with_a_secret_token_generated_above>'
```
1. Reconfigure each node you just updated:
```shell
gitlab-ctl reconfigure
```
### Configure secondary site
Make sure you have container registry set up and working on
the **secondary** site before following the next steps.
The following steps should be done on each **secondary** site you're
expecting to see the container images replicated.
Because we need to allow the **secondary** site to communicate securely with
the **primary** site container registry, we need to have a single key
pair for all the sites. The **secondary** site uses this key to
generate a short-lived JWT that is pull-only-capable to access the
**primary** site container registry.
For each application and Sidekiq node on the **secondary** site:
1. SSH into the node and sign in as the `root` user:
```shell
sudo -i
```
1. Copy `/var/opt/gitlab/gitlab-rails/etc/gitlab-registry.key` from the **primary** to the node.
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
gitlab_rails['geo_registry_replication_enabled'] = true
# Primary registry's hostname and port, it will be used by
# the secondary node to directly communicate to primary registry
gitlab_rails['geo_registry_replication_primary_api_url'] = 'https://primary.example.com:5050/'
```
1. Reconfigure the node for the change to take effect:
```shell
gitlab-ctl reconfigure
```
### Verify replication
To verify container registry replication is working, on the **secondary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Nodes**.
The initial replication, or "backfill", is probably still in progress.
You can monitor the synchronization process on each Geo site from the **primary** site's **Geo Nodes** dashboard in your browser.
## Troubleshooting
### Confirm that container registry replication is enabled
This can be done with a check using the [Rails console](../../operations/rails_console.md#starting-a-rails-console-session):
```ruby
Geo::ContainerRepositoryRegistry.replication_enabled?
```
### Missing container registry notification event
1. When an image is pushed to the primary site's container registry, it should trigger a [Container Registry notification](../../packages/container_registry.md#configure-container-registry-notifications)
1. The primary site's container registry calls the primary site's API on `https://<example.com>/api/v4/container_registry_event/events`
1. The primary site inserts a record to the `geo_events` table with `replicable_name: 'container_repository', model_record_id: <ID of the container repository>`.
1. The record gets replicated by PostgreSQL to the secondary site's database.
1. The Geo Log Cursor service processes the new event and enqueues a Sidekiq job `Geo::EventWorker`
To verify this is working correctly, push an image to the registry on the primary site, and run the following command on the Rails console to verify that the notification was received, and processed into an event:
```ruby
Geo::Event.where(replicable_name: 'container_repository')
```
You can further verify this by checking `geo.log` for entries from `Geo::ContainerRepositorySyncService`.
### Registry events logs response status 401 Unauthorized unaccepted
`401 Unauthorized` errors indicate that the primary site's container registry notification is not accepted by the Rails application, preventing it from notifying GitLab that something was pushed.
To fix this, make sure that the authorization headers being sent with the registry notification match what's configured on the primary site, as should be done during step [Configure primary site](#configure-primary-site).
#### Registry error: `token from untrusted issuer: "<token>"`
When replicating container images in Geo, you might see the error `token from untrusted issuer: "<token>"`.
This issue occurs when the container registry configuration is incorrect, causing Sidekiq's JWT
authentication to fail.
To resolve this issue:
1. Ensure both sites share a single signing key pair, as described in [configure secondary site](#configure-secondary-site).
1. Verify that both container registries and both primary and secondary sites are configured
to use the same token issuer. For more information, see
[configure GitLab and registry on separate nodes](../../packages/container_registry.md#configure-gitlab-and-registry-on-separate-nodes-linux-package-installations).
1. For multi-node deployments, confirm that the issuer configured on the Sidekiq node matches
the value configured on the registries.
### Manually trigger a container registry sync event
To help with troubleshooting, you can manually trigger the container registry replication process:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. In **Replication Details** for a **Secondary Site**, select **Container Repositories**.
1. Select **Resync** for one row, or **Resync all**.
You can also manually trigger a resync by running the following commands on the secondary's Rails console:
```ruby
registry = Geo::ContainerRepositoryRegistry.first # Choose a Geo registry entry
registry.replicator.sync # Resync the container repository
pp registry.reload # Look at replication state fields
#<Geo::ContainerRepositoryRegistry:0x00007f54c2a36060
id: 1,
container_repository_id: 1,
state: "2",
retry_count: 0,
last_sync_failure: nil,
retry_at: nil,
last_synced_at: Thu, 28 Sep 2023 19:38:05.823680000 UTC +00:00,
created_at: Mon, 11 Sep 2023 15:38:06.262490000 UTC +00:00>
```
The `state` field represents sync state:
- `"0"`: pending sync (usually means it was never synced)
- `"1"`: started sync (a sync job is currently running)
- `"2"`: successfully synced
- `"3"`: failed to sync
|
https://docs.gitlab.com/administration/geo/selective_synchronization
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/selective_synchronization.md
|
2025-08-13
|
doc/administration/geo/replication
|
[
"doc",
"administration",
"geo",
"replication"
] |
selective_synchronization.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Selective synchronization
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Geo supports selective synchronization, which allows administrators to choose
which projects should be synchronized by **secondary** sites.
A subset of projects can be chosen, either by group or by storage shard. The
former is ideal for reducing transfer and storage costs by replicating data
belonging to only a subset of users. The latter is more suited to progressively
rolling out Geo to a large GitLab instance.
{{< alert type="note" >}}
Geo's synchronization logic is outlined in the [documentation](../_index.md). Both the solution and the documentation is subject to change from time to time. You must independently determine your legal obligations in regard to privacy and cybersecurity laws, and applicable trade control law on an ongoing basis.
{{< /alert >}}
Selective synchronization:
1. Does not restrict permissions from **secondary** sites.
1. Does not prevent users from viewing, interacting with, cloning, and pushing to project repositories that are not included in the selective sync.
- For more details, see [Geo proxying for secondary sites](../secondary_proxy/_index.md).
1. Does not hide project metadata from **secondary** sites.
- Because Geo relies on PostgreSQL replication, all project metadata
gets replicated to **secondary** sites, but repositories that have not been
selected will not exist on the secondary site.
1. Does not reduce the number of events generated for the Geo event log.
- The **primary** site generates events as long as any **secondary** sites are present.
Selective synchronization restrictions are implemented on the **secondary** sites,
not the **primary** site.
## Git operations on unreplicated repositories
Git clone, pull, and push operations over HTTP(S) and SSH are supported for repositories that
exist on the **primary** site but not on **secondary** sites. This situation can occur
when:
- Selective synchronization does not include the project attached to the repository.
- The repository is actively being replicated but has not completed yet.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Selective synchronization
breadcrumbs:
- doc
- administration
- geo
- replication
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Geo supports selective synchronization, which allows administrators to choose
which projects should be synchronized by **secondary** sites.
A subset of projects can be chosen, either by group or by storage shard. The
former is ideal for reducing transfer and storage costs by replicating data
belonging to only a subset of users. The latter is more suited to progressively
rolling out Geo to a large GitLab instance.
{{< alert type="note" >}}
Geo's synchronization logic is outlined in the [documentation](../_index.md). Both the solution and the documentation is subject to change from time to time. You must independently determine your legal obligations in regard to privacy and cybersecurity laws, and applicable trade control law on an ongoing basis.
{{< /alert >}}
Selective synchronization:
1. Does not restrict permissions from **secondary** sites.
1. Does not prevent users from viewing, interacting with, cloning, and pushing to project repositories that are not included in the selective sync.
- For more details, see [Geo proxying for secondary sites](../secondary_proxy/_index.md).
1. Does not hide project metadata from **secondary** sites.
- Because Geo relies on PostgreSQL replication, all project metadata
gets replicated to **secondary** sites, but repositories that have not been
selected will not exist on the secondary site.
1. Does not reduce the number of events generated for the Geo event log.
- The **primary** site generates events as long as any **secondary** sites are present.
Selective synchronization restrictions are implemented on the **secondary** sites,
not the **primary** site.
## Git operations on unreplicated repositories
Git clone, pull, and push operations over HTTP(S) and SSH are supported for repositories that
exist on the **primary** site but not on **secondary** sites. This situation can occur
when:
- Selective synchronization does not include the project attached to the repository.
- The repository is actively being replicated but has not completed yet.
|
https://docs.gitlab.com/administration/geo/replication/common
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/common.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
common.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting common Geo errors
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## Basic troubleshooting
Before attempting more advanced troubleshooting:
- Check [the health of the Geo sites](#check-the-health-of-the-geo-sites).
- Check [if PostgreSQL replication is working](#check-if-postgresql-replication-is-working).
### Check the health of the Geo sites
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites**.
We perform the following health checks on each **secondary** site
to help identify if something is wrong:
- Is the site running?
- Is the secondary site's database configured for streaming replication?
- Is the secondary site's tracking database configured?
- Is the secondary site's tracking database connected?
- Is the secondary site's tracking database up-to-date?
- Is the secondary site's status less than 1 hour old?
A site shows as "Unhealthy" if the site's status is more than 1 hour old. In that case, try running the following in the [Rails console](../../../operations/rails_console.md) on the affected secondary site:
```ruby
Geo::MetricsUpdateWorker.new.perform
```
If it raises an error, then the error is probably also preventing the jobs from completing. If it takes longer than 1 hour, then the status might flap or persist as "Unhealthy", even if the status does occasionally get updated. This might be due to growth in usage, growth in data over time, or performance bugs such as a missing database index.
You can monitor system CPU load with a utility like `top` or `htop`. If PostgreSQL is using a significant amount of CPU, it might indicate that there's a problem, or that the system is underprovisioned. System memory should also be monitored.
If you increase memory, you should also check the PostgreSQL memory-related settings in your `/etc/gitlab/gitlab.rb` configuration.
If it successfully updates the status, then something may be wrong with Sidekiq. Is it running? Do the logs show errors? This job is supposed to be enqueued every minute and might not run if a [job deduplication idempotency](../../../sidekiq/sidekiq_troubleshooting.md#clearing-a-sidekiq-job-deduplication-idempotency-key) key was not cleared properly. It takes an exclusive lease in Redis to ensure that only one of these jobs can run at a time. The primary site updates its status directly in the PostgreSQL database. Secondary sites send an HTTP Post request to the primary site with their status data.
A site also shows as "Unhealthy" if certain health checks fail. You can reveal the failure by running the following in the [Rails console](../../../operations/rails_console.md) on the affected secondary site:
```ruby
Gitlab::Geo::HealthCheck.new.perform_checks
```
If it returns `""` (an empty string) or `"Healthy"`, then the checks succeeded. If it returns anything else, then the message should explain what failed, or show the exception message.
For information about how to resolve common error messages reported from the user interface,
see [Fixing Common Errors](#fixing-common-errors).
If the user interface is not working, or you are unable to sign in, you can run the Geo
health check manually to get this information and a few more details.
#### Health check Rake task
{{< history >}}
- The use of a custom NTP server was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105514) in GitLab 15.7.
{{< /history >}}
This Rake task can be run on a **Rails** node in the **primary** or **secondary**
Geo sites:
```shell
sudo gitlab-rake gitlab:geo:check
```
Example output:
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
This machine's Geo node name matches a database record ... yes, found a secondary node named "Shanghai"
GitLab Geo tracking database is correctly configured ... yes
Database replication enabled? ... yes
Database replication working? ... yes
GitLab Geo HTTP(S) connectivity ...
* Can connect to the primary node ... yes
HTTP/HTTPS repository cloning is enabled ... yes
Machine clock is synchronized ... yes
Git user has default SSH configuration? ... yes
OpenSSH configured to use AuthorizedKeysCommand ... yes
GitLab configured to disable writing to authorized_keys file ... yes
GitLab configured to store new projects in hashed storage? ... yes
All projects are in hashed storage? ... yes
Checking Geo ... Finished
```
You can also specify a custom NTP server using environment variables. For example:
```shell
sudo gitlab-rake gitlab:geo:check NTP_HOST="ntp.ubuntu.com" NTP_TIMEOUT="30"
```
The following environment variables are supported.
| Variable | Description | Default value |
| ----------- | ----------- | ------------- |
|`NTP_HOST` | The NTP host. | `pool.ntp.org` |
|`NTP_PORT` | The NTP port the host listens on. |`ntp`|
|`NTP_TIMEOUT`| The NTP timeout in seconds. | The value defined in the `net-ntp` Ruby library ([60 seconds](https://github.com/zencoder/net-ntp/blob/3d0990214f439a5127782e0f50faeaf2c8ca7023/lib/net/ntp/ntp.rb#L6)). |
If the Rake task skips the `OpenSSH configured to use AuthorizedKeysCommand` check, the
following output displays:
```plaintext
OpenSSH configured to use AuthorizedKeysCommand ... skipped
Reason:
Cannot access OpenSSH configuration file
Try fixing it:
This is expected if you are using SELinux. You may want to check configuration manually
For more information see:
doc/administration/operations/fast_ssh_key_lookup.md
```
This issue might occur if:
- You use [SELinux](../../../operations/fast_ssh_key_lookup.md#selinux-support).
- You don't use SELinux, and the `git` user cannot access the OpenSSH configuration file due to restricted file permissions.
In the latter case, the following output shows that only the `root` user can read this file:
```plaintext
sudo stat -c '%G:%U %A %a %n' /etc/ssh/sshd_config
root:root -rw------- 600 /etc/ssh/sshd_config
```
To allow the `git` user to read the OpenSSH configuration file, without changing the file owner or permissions, use `acl`:
```plaintext
sudo setfacl -m u:git:r /etc/ssh/sshd_config
```
#### Sync status Rake task
Current sync information can be found manually by running this Rake task on any
node running Rails (Puma, Sidekiq, or Geo Log Cursor) on the Geo **secondary** site.
GitLab does **not** verify objects that are stored in Object Storage. If you are using Object Storage, you will see all of the "verified" checks showing 0 successes. This is expected and not a cause for concern.
```shell
sudo gitlab-rake geo:status
```
The output includes:
- a count of "failed" items if any failures occurred
- the percentage of "succeeded" items, relative to the "total"
Example:
```plaintext
Geo Site Information
--------------------------------------------
Name: example-us-east-2
URL: https://gitlab.example.com
Geo Role: Secondary
Health Status: Healthy
This Node's GitLab Version: 17.7.0-ee
Replication Information
--------------------------------------------
Sync Settings: Full
Database replication lag: 0 seconds
Last event ID seen from primary: 12345 (about 2 minutes ago)
Last event ID processed: 12345 (about 2 minutes ago)
Last status report was: 1 minute ago
Replication Status
--------------------------------------------
Lfs Objects replicated: succeeded 111 / total 111 (100%)
Merge Request Diffs replicated: succeeded 28 / total 28 (100%)
Package Files replicated: succeeded 90 / total 90 (100%)
Terraform State Versions replicated: succeeded 65 / total 65 (100%)
Snippet Repositories replicated: succeeded 63 / total 63 (100%)
Group Wiki Repositories replicated: succeeded 14 / total 14 (100%)
Pipeline Artifacts replicated: succeeded 112 / total 112 (100%)
Pages Deployments replicated: succeeded 55 / total 55 (100%)
Uploads replicated: succeeded 2 / total 2 (100%)
Job Artifacts replicated: succeeded 32 / total 32 (100%)
Ci Secure Files replicated: succeeded 44 / total 44 (100%)
Dependency Proxy Blobs replicated: succeeded 15 / total 15 (100%)
Dependency Proxy Manifests replicated: succeeded 2 / total 2 (100%)
Project Wiki Repositories replicated: succeeded 2 / total 2 (100%)
Design Management Repositories replicated: succeeded 1 / total 1 (100%)
Project Repositories replicated: succeeded 2 / total 2 (100%)
Verification Status
--------------------------------------------
Lfs Objects verified: succeeded 111 / total 111 (100%)
Merge Request Diffs verified: succeeded 28 / total 28 (100%)
Package Files verified: succeeded 90 / total 90 (100%)
Terraform State Versions verified: succeeded 65 / total 65 (100%)
Snippet Repositories verified: succeeded 63 / total 63 (100%)
Group Wiki Repositories verified: succeeded 14 / total 14 (100%)
Pipeline Artifacts verified: succeeded 112 / total 112 (100%)
Pages Deployments verified: succeeded 55 / total 55 (100%)
Uploads verified: succeeded 2 / total 2 (100%)
Job Artifacts verified: succeeded 32 / total 32 (100%)
Ci Secure Files verified: succeeded 44 / total 44 (100%)
Dependency Proxy Blobs verified: succeeded 15 / total 15 (100%)
Dependency Proxy Manifests verified: succeeded 2 / total 2 (100%)
Project Wiki Repositories verified: succeeded 2 / total 2 (100%)
Design Management Repositories verified: succeeded 1 / total 1 (100%)
Project Repositories verified: succeeded 2 / total 2 (100%)
```
All objects are replicated and verified, which are defined in the [Geo glossary](../../glossary.md). Read more about the
methods we use for replicating and verifying each data type in [supported Geo data types](../datatypes.md#data-types).
To find more details about failed items, check
[the `gitlab-rails/geo.log` file](../../../logs/log_parsing.md#find-most-common-geo-sync-errors)
If you notice replication or verification failures, you can try to [resolve them](synchronization_verification.md).
##### Fixing errors found when running the Geo check Rake task
When running this Rake task, you may see error messages if the nodes are not properly configured:
```shell
sudo gitlab-rake gitlab:geo:check
```
- Rails did not provide a password when connecting to the database.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: fe_sendauth: no password supplied
GitLab Geo is enabled ... Exception: fe_sendauth: no password supplied
...
Checking Geo ... Finished
```
Ensure you have the `gitlab_rails['db_password']` set to the plain-text
password used when creating the hash for `postgresql['sql_user_password']`.
- Rails is unable to connect to the database.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL on
FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL off
GitLab Geo is enabled ... Exception: FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL on
FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL off
...
Checking Geo ... Finished
```
Ensure you have the IP address of the rails node included in `postgresql['md5_auth_cidr_addresses']`.
Also, ensure you have included the subnet mask on the IP address: `postgresql['md5_auth_cidr_addresses'] = ['1.1.1.1/32']`.
- Rails has supplied the incorrect password.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: FATAL: password authentication failed for user "gitlab"
FATAL: password authentication failed for user "gitlab"
GitLab Geo is enabled ... Exception: FATAL: password authentication failed for user "gitlab"
FATAL: password authentication failed for user "gitlab"
...
Checking Geo ... Finished
```
Verify the correct password is set for `gitlab_rails['db_password']` that was
used when creating the hash in `postgresql['sql_user_password']` by running
`gitlab-ctl pg-password-md5 gitlab` and entering the password.
- Check returns `not a secondary node`.
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
GitLab Geo tracking database is correctly configured ... not a secondary node
Database replication enabled? ... not a secondary node
...
Checking Geo ... Finished
```
Ensure you have added the secondary site in the **Admin** area under **Geo > Sites** on the web interface for the **primary** site.
Also ensure you entered the `gitlab_rails['geo_node_name']`
when adding the secondary site in the **Admin** area of the **primary** site.
- Check returns `Exception: PG::UndefinedTable: ERROR: relation "geo_nodes" does not exist`.
```plaintext
Checking Geo ...
GitLab Geo is available ... no
Try fixing it:
Add a new license that includes the GitLab Geo feature
For more information see:
https://about.gitlab.com/features/gitlab-geo/
GitLab Geo is enabled ... Exception: PG::UndefinedTable: ERROR: relation "geo_nodes" does not exist
LINE 8: WHERE a.attrelid = '"geo_nodes"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
c.collname, col_description(a.attrelid, a.attnum) AS comment
FROM pg_attribute a
LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
WHERE a.attrelid = '"geo_nodes"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
...
Checking Geo ... Finished
```
When performing a PostgreSQL major version (9 > 10), update this is expected. Follow
the [initiate-the-replication-process](../../setup/database.md#step-3-initiate-the-replication-process).
- Rails does not appear to have the configuration necessary to connect to the Geo tracking database.
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
GitLab Geo tracking database is correctly configured ... no
Try fixing it:
Rails does not appear to have the configuration necessary to connect to the Geo tracking database. If the tracking database is running on a node other than this one, then you may need to add configuration.
...
Checking Geo ... Finished
```
- If you are running the secondary site on a single node for all services, then follow [Geo database replication - Configure the secondary server](../../setup/database.md#step-2-configure-the-secondary-server).
- If you are running the secondary site's tracking database on its own node, then follow [Geo for multiple servers - Configure the Geo tracking database on the Geo secondary site](../multiple_servers.md#step-2-configure-the-geo-tracking-database-on-the-geo-secondary-site)
- If you are running the secondary site's tracking database in a Patroni cluster, then follow [Geo database replication - Configuring Patroni cluster for the tracking PostgreSQL database](../../setup/database.md#configuring-patroni-cluster-for-the-tracking-postgresql-database)
- If you are running the secondary site's tracking database in an external database, then follow [Geo with external PostgreSQL instances](../../setup/external_database.md#configure-the-tracking-database)
- If the Geo check task was run on a node which is not running a service which runs the GitLab Rails app (Puma, Sidekiq, or Geo Log Cursor), then this error can be ignored. The node does not need Rails to be configured.
##### Message: Machine clock is synchronized ... Exception
The Rake task attempts to verify that the server clock is synchronized with NTP. Synchronized clocks
are required for Geo to function correctly. As an example, for security, when the server time on the
primary site and secondary site differ by about a minute or more, requests between Geo sites
fail. If this check task fails to complete due to a reason other than mismatching times, it
does not necessarily mean that Geo will not work.
The Ruby gem which performs the check is hard coded with `pool.ntp.org` as its reference time source.
- Exception message `Machine clock is synchronized ... Exception: Timeout::Error`
This issue occurs when your server cannot access the host `pool.ntp.org`.
- Exception message `Machine clock is synchronized ... Exception: No route to host - recvfrom(2)`
This issue occurs when the hostname `pool.ntp.org` resolves to a server which does not provide a time service.
In this case, in GitLab 15.7 and later, [specify a custom NTP server using environment variables](#health-check-rake-task).
In GitLab 15.6 and earlier, use one of the following workarounds:
- Add entries in `/etc/hosts` for `pool.ntp.org` to direct the request to valid local time servers.
This fixes the long timeout and the timeout error.
- Direct the check to any valid IP address. This resolves the timeout issue, but the check fails
with the `No route to host` error, as noted previously.
[Cloud native GitLab deployments](https://docs.gitlab.com/charts/advanced/geo/#set-the-geo-primary-site)
generate an error because containers in Kubernetes do not have access to the host clock:
```plaintext
Machine clock is synchronized ... Exception: getaddrinfo: Servname not supported for ai_socktype
```
##### Message: `cannot execute INSERT in a read-only transaction`
When this error is encountered on a secondary site, it likely affects all usages of GitLab Rails such as `gitlab-rails` or `gitlab-rake` commands, as well the Puma, Sidekiq, and Geo Log Cursor services.
```plaintext
ActiveRecord::StatementInvalid: PG::ReadOnlySqlTransaction: ERROR: cannot execute INSERT in a read-only transaction
/opt/gitlab/embedded/service/gitlab-rails/app/models/application_record.rb:86:in `block in safe_find_or_create_by'
/opt/gitlab/embedded/service/gitlab-rails/app/models/concerns/cross_database_modification.rb:92:in `block in transaction'
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database.rb:332:in `block in transaction'
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database.rb:331:in `transaction'
/opt/gitlab/embedded/service/gitlab-rails/app/models/concerns/cross_database_modification.rb:83:in `transaction'
/opt/gitlab/embedded/service/gitlab-rails/app/models/application_record.rb:86:in `safe_find_or_create_by'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:21:in `by_name'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `block in populate!'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `map'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `populate!'
/opt/gitlab/embedded/service/gitlab-rails/config/initializers/fill_shards.rb:9:in `<top (required)>'
/opt/gitlab/embedded/service/gitlab-rails/config/environment.rb:7:in `<top (required)>'
/opt/gitlab/embedded/bin/bundle:23:in `load'
/opt/gitlab/embedded/bin/bundle:23:in `<main>'
```
The PostgreSQL read-replica database would be producing these errors:
```plaintext
2023-01-17_17:44:54.64268 ERROR: cannot execute INSERT in a read-only transaction
2023-01-17_17:44:54.64271 STATEMENT: /*application:web,db_config_name:main*/ INSERT INTO "shards" ("name") VALUES ('storage1') RETURNING "id"
```
This situation can occur:
- During initial configuration when a secondary site is not yet aware that it is a secondary site. To resolve the error, follow [Step 3. Add the secondary site](../configuration.md#step-3-add-the-secondary-site).
- During the upgrade of a Geo secondary site. It's possible that `gitlab_rails['auto_migrate']` is set to `true`, causing GitLab to attempt database migrations on the replica database, which is not required. To resolve the error:
1. SSH as root to the GitLab Rails node of the secondary site.
1. Edit `/etc/gitlab/gitlab.rb`, and comment out this setting or set it to false:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Check if PostgreSQL replication is working
To check if PostgreSQL replication is working, check if:
- [Sites are pointing to the correct database node](#are-sites-pointing-to-the-correct-database-node).
- [Geo can detect the current site correctly](#can-geo-detect-the-current-site-correctly).
If you're still having problems, see the [advanced replication troubleshooting](synchronization_verification.md).
#### Are sites pointing to the correct database node?
You should make sure your **primary** Geo [site](../../glossary.md) points to
the database node that has write permissions.
Any **secondary** sites should point only to read-only database nodes.
#### Can Geo detect the current site correctly?
Geo finds the current Puma or Sidekiq node's Geo [site](../../glossary.md) name in
`/etc/gitlab/gitlab.rb` with the following logic:
1. Get the "Geo node name" (there is
[an issue to rename the settings to "Geo site name"](https://gitlab.com/gitlab-org/gitlab/-/issues/335944)):
- Linux package: get the `gitlab_rails['geo_node_name']` setting.
- GitLab Helm charts: get the `global.geo.nodeName` setting (see [Charts with GitLab Geo](https://docs.gitlab.com/charts/advanced/geo/)).
1. If that is not defined, then get the `external_url` setting.
This name is used to look up the Geo site with the same **Name** in the **Geo Sites**
dashboard.
To check if the current machine has a site name that matches a site in the
database, run the check task:
```shell
sudo gitlab-rake gitlab:geo:check
```
It displays the current machine's site name and whether the matching database
record is a **primary** or **secondary** site.
```plaintext
This machine's Geo node name matches a database record ... yes, found a secondary node named "Shanghai"
```
```plaintext
This machine's Geo node name matches a database record ... no
Try fixing it:
You could add or update a Geo node database record, setting the name to "https://example.com/".
Or you could set this machine's Geo node name to match the name of an existing database record: "London", "Shanghai"
For more information see:
doc/administration/geo/replication/troubleshooting/_index.md#can-geo-detect-the-current-node-correctly
```
For more information about recommended site names in the description of the Name field, see
[Geo **Admin** area Common Settings](../../../geo_sites.md#common-settings).
### Check OS locale data compatibility
If at all possible, all Geo nodes across all sites should be deployed with the same method and operating system, as defined in the [requirements for running Geo](../../_index.md#requirements-for-running-geo).
If different operating systems or different operating system versions are deployed across Geo sites, you **must** perform a locale data compatibility check before setting up Geo. You must also check `glibc` when using a mixture of GitLab deployment methods. The locale might be different between a Linux package install, a GitLab Docker container, a Helm chart deployment, or external database services. See the [documentation on upgrading operating systems for PostgreSQL](../../../postgresql/upgrading_os.md), including how to check `glibc` version compatibility.
Geo uses PostgreSQL and Streaming Replication to replicate data across Geo sites. PostgreSQL uses locale data provided by the operating system's C library for sorting text. If the locale data in the C library is incompatible across Geo sites, it causes erroneous query results that lead to [incorrect behavior on secondary sites](https://gitlab.com/gitlab-org/gitlab/-/issues/360723).
For example, Ubuntu 18.04 (and earlier) and RHEL/CentOS 7 (and earlier) are incompatible with their later releases.
See the [PostgreSQL wiki for more details](https://wiki.postgresql.org/wiki/Locale_data_changes).
## Fixing common errors
This section documents common error messages reported in the **Admin** area on the web interface, and how to fix them.
### An existing tracking database cannot be reused
Geo cannot reuse an existing tracking database.
It is safest to use a fresh secondary, or reset the whole secondary by following
[Resetting Geo secondary site replication](synchronization_verification.md#resetting-geo-secondary-site-replication).
It is risky to reuse a secondary site without resetting it because the secondary site may have missed some Geo events. For example, missed deletion events lead to the secondary site permanently having data that should be deleted. Similarly, losing an event which physically moves the location of data leads to data permanently orphaned in one location, and missing in the other location until it is re-verified. This is why GitLab switched to hashed storage, which makes moving data unnecessary. There may be other unknown problems due to lost events.
If these kinds of risks do not apply, for example in a test environment, or if you know that the main Postgres database still contains all Geo events since the Geo site was added, then you can bypass this health check:
1. Get the last processed event time. In Rails console in the **secondary** site, run:
```ruby
Geo::EventLogState.last.created_at.utc
```
1. Copy the output, for example `2024-02-21 23:50:50.676918 UTC`.
1. Update the created time of the secondary site to make it appear older. In Rails console in the **primary** site, run:
```ruby
GeoNode.secondary_nodes.last.update_column(:created_at, DateTime.parse('2024-02-21 23:50:50.676918 UTC') - 1.second)
```
This command assumes that the affected secondary site is the one that was created last.
1. Update the secondary site's status in **Admin > Geo > Sites**. In Rails console in the **secondary** site, run:
```ruby
Geo::MetricsUpdateWorker.new.perform
```
1. The secondary site should appear healthy. If it does not, run `gitlab-rake gitlab:geo:check` on the secondary site, or try restarting Rails if you haven't done so since re-adding the secondary site.
1. To resync missing or out-of-date data, go to **Admin > Geo > Sites**.
1. Under the secondary site select **Replication Details**.
1. Select **Reverify all** for every data type.
### Geo site has a database that is writable
This error message refers to a problem with the database replica on a **secondary** site,
which Geo expects to have access to. A secondary site database that is writable
is an indication the database is not configured for replication with the primary site. It usually means, either:
- An unsupported replication method was used (for example, logical replication).
- The instructions to set up a [Geo database replication](../../setup/database.md) were not followed correctly.
- Your database connection details are incorrect, that is you have specified the wrong
user in your `/etc/gitlab/gitlab.rb` file.
Geo **secondary** sites require two separate PostgreSQL instances:
- A read-only replica of the **primary** site.
- A regular, writable instance that holds replication metadata. That is, the Geo tracking database.
This error message indicates that the replica database in the **secondary** site is misconfigured and replication has stopped.
To restore the database and resume replication, you can do one of the following:
- [Reset the Geo secondary site replication](synchronization_verification.md#resetting-geo-secondary-site-replication).
- [Set up a new Geo secondary using the Linux package](../../setup/_index.md#using-linux-package-installations).
If you set up a new secondary from scratch, you must also [remove the old site from the Geo cluster](../remove_geo_site.md).
### Geo site does not appear to be replicating the database from the primary site
The most common problems that prevent the database from replicating correctly are:
- **Secondary** sites cannot reach the **primary** site. Check credentials and
[firewall rules](../../_index.md#firewall-rules).
- SSL certificate problems. Make sure you copied `/etc/gitlab/gitlab-secrets.json` from the **primary** site.
- Database storage disk is full.
- Database replication slot is misconfigured.
- Database is not using a replication slot or another alternative and cannot catch-up because WAL files were purged.
Make sure you follow the [Geo database replication](../../setup/database.md) instructions for supported configuration.
### Geo database version (...) does not match latest migration (...)
If you are using the Linux package installation, something might have failed during upgrade. You can:
- Run `sudo gitlab-ctl reconfigure`.
- Manually trigger the database migration by running: `sudo gitlab-rake db:migrate:geo` as root on the **secondary** site.
### GitLab indicates that more than 100% of repositories were synced
This can be caused by orphaned records in the project registry. They are being cleaned
periodically using a registry worker, so give it some time to fix it itself.
### Failed checksums on primary site
Failed checksums identified by the Geo Primary Verification information screen can be caused by missing files or mismatched checksums. You can find error messages like `"Repository cannot be checksummed because it does not exist"` or `"File is not checksummable"` in the `gitlab-rails/geo.log` file.
For additional information about failed items, run the [integrity check Rake tasks](../../../raketasks/check.md#uploaded-files-integrity):
```ruby
sudo gitlab-rake gitlab:artifacts:check
sudo gitlab-rake gitlab:ci_secure_files:check
sudo gitlab-rake gitlab:lfs:check
sudo gitlab-rake gitlab:uploads:check
```
For detailed information about individual errors, use the `VERBOSE=1` variable.
### Secondary site shows "Unhealthy" in UI
If you have updated the value of `external_url` in `/etc/gitlab/gitlab.rb` for the primary site or changed the protocol from `http` to `https`, you may see that secondary sites are shown as `Unhealthy`. You may also find the following error in `geo.log`:
```plaintext
"class": "Geo::NodeStatusRequestService",
...
"message": "Failed to Net::HTTP::Post to primary url: http://primary-site.gitlab.tld/api/v4/geo/status",
"error": "Failed to open TCP connection to <PRIMARY_IP_ADDRESS>:80 (Connection refused - connect(2) for \"<PRIMARY_ID_ADDRESS>\" port 80)"
```
In this case, make sure to update the changed URL on all your sites:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites**.
1. Change the URL and save the change.
### Message: `ERROR: canceling statement due to conflict with recovery` during backup
Running a backup on a Geo **secondary** [is not supported](https://gitlab.com/gitlab-org/gitlab/-/issues/211668).
When running a backup on a **secondary** you might encounter the following error message:
```plaintext
Dumping PostgreSQL database gitlabhq_production ...
pg_dump: error: Dumping the contents of table "notes" failed: PQgetResult() failed.
pg_dump: error: Error message from server: ERROR: canceling statement due to conflict with recovery
DETAIL: User query might have needed to see row versions that must be removed.
pg_dump: error: The command was: COPY public.notes (id, note, [...], last_edited_at) TO stdout;
```
To prevent a database backup being made automatically during GitLab upgrades on your Geo **secondaries**,
create the following empty file:
```shell
sudo touch /etc/gitlab/skip-auto-backup
```
### High CPU usage on primary during object verification
From GitLab 16.11 to GitLab 17.2, a missing PostgreSQL index causes high CPU
usage and slow artifact verification progress. Additionally, the Geo secondary
sites might report as unhealthy. [Issue 471727](https://gitlab.com/gitlab-org/gitlab/-/issues/471727) describes the behavior in detail.
To determine if you might be experiencing this issue, follow the steps to
[confirm if you are affected](https://gitlab.com/gitlab-org/gitlab/-/issues/471727#to-confirm-if-you-are-affected).
If you are affected, follow the steps in the [workaround](https://gitlab.com/gitlab-org/gitlab/-/issues/471727#workaround)
to manually create the index. Creating the index causes PostgreSQL to
consume slightly more resources until it finishes. Afterward, CPU usage might
remain high while verification continues, but queries should complete
significantly faster, and secondary site status should update correctly.
### Verification failed with: `Verification timed out after (...)`
From GitLab 16.11, Geo may create duplicate `JobArtifactRegistry` entries for the same `artifact_id`, which can lead to synchronization
failures between primary and secondary sites. This issue may also impact `UploadRegistry` and `PackageFileRegistry` entries.
To determine if you might be experiencing this issue and remove the duplicate entries:
1. Open a [Rails console](../../../operations/rails_console.md) in the secondary site.
1. Get the number of model record IDs that have duplicates:
```ruby
artifact_ids = Geo::JobArtifactRegistry.group(:artifact_id).having('COUNT(*) > 1').pluck(:artifact_id); artifact_ids.size
upload_ids = Geo::UploadRegistry.group(:file_id).having('COUNT(*) > 1').pluck(:file_id); upload_ids.size
package_file_ids = Geo::PackageFileRegistry.group(:package_file_id).having('COUNT(*) > 1').pluck(:package_file_id); package_file_ids.size
```
1. Output the IDs:
```ruby
puts 'BEGIN Artifact IDs', artifact_ids, 'END Artifact IDs'
puts 'BEGIN Upload IDs', upload_ids, 'END Upload IDs'
puts 'BEGIN Package File IDs', package_file_ids, 'END Package File IDs'
```
If the output is empty, you are not affected. Otherwise, save
the terminal output in a text file in case you lose connection later.
1. Delete all duplicates:
```ruby
Geo::JobArtifactRegistry.where(artifact_id: artifact_ids).delete_all
Geo::UploadRegistry.where(file_id: upload_ids).delete_all
Geo::PackageFileRegistry.where(package_file_id: package_file_ids).delete_all
```
1. Wait for the background jobs to create the registry rows again and resync.
Follow [issue 479852](https://gitlab.com/gitlab-org/gitlab/-/issues/479852) to get feedback on the fix.
### Error `end of file reached` when running Geo Rake check task on secondary
You may face the following error when running the [health check Rake task](common.md#health-check-rake-task) on the secondary site:
```plaintext
Can connect to the primary node ... no
Reason:
end of file reached
```
It might happen if the incorrect URL to the primary site was specified in the setting. To troubleshoot it,
run the following commands in [the Rails Console](../../../operations/rails_console.md):
```ruby
primary = Gitlab::Geo.primary_node
primary.internal_uri
Gitlab::HTTP.get(primary.internal_uri, allow_local_requests: true, limit: 10)
```
Make sure that the value of `internal_uri` is correct in the previous output.
If the URL of the primary site is incorrect, double-check it in `/etc/gitlab/gitlab.rb`, and in **Admin > Geo > Sites**.
### Excessive database IO from Geo metrics collection
If you're experiencing high database load due to frequent Geo metrics collection, you can reduce the frequency of the `geo_metrics_update_worker` job. This adjustment can help alleviate database strain in large GitLab instances where metrics collection significantly impacts database performance.
Increasing the interval means that your Geo metrics are updated less frequently. This results in metrics being out-of-date for longer periods of time, which may impact your ability to monitor Geo replication in real-time. If metrics are out-of-date for more than 10 minutes, the site is arbitrarily marked as "Unhealthy" in the Admin Area.
The following example sets the job to run every 30 minutes. Adjust the cron schedule based on your needs.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Add or modify the following setting in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['geo_metrics_update_worker_cron'] = "*/30 * * * *"
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
geo_metrics_update_worker:
cron: "*/30 * * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting common Geo errors
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## Basic troubleshooting
Before attempting more advanced troubleshooting:
- Check [the health of the Geo sites](#check-the-health-of-the-geo-sites).
- Check [if PostgreSQL replication is working](#check-if-postgresql-replication-is-working).
### Check the health of the Geo sites
On the **primary** site:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites**.
We perform the following health checks on each **secondary** site
to help identify if something is wrong:
- Is the site running?
- Is the secondary site's database configured for streaming replication?
- Is the secondary site's tracking database configured?
- Is the secondary site's tracking database connected?
- Is the secondary site's tracking database up-to-date?
- Is the secondary site's status less than 1 hour old?
A site shows as "Unhealthy" if the site's status is more than 1 hour old. In that case, try running the following in the [Rails console](../../../operations/rails_console.md) on the affected secondary site:
```ruby
Geo::MetricsUpdateWorker.new.perform
```
If it raises an error, then the error is probably also preventing the jobs from completing. If it takes longer than 1 hour, then the status might flap or persist as "Unhealthy", even if the status does occasionally get updated. This might be due to growth in usage, growth in data over time, or performance bugs such as a missing database index.
You can monitor system CPU load with a utility like `top` or `htop`. If PostgreSQL is using a significant amount of CPU, it might indicate that there's a problem, or that the system is underprovisioned. System memory should also be monitored.
If you increase memory, you should also check the PostgreSQL memory-related settings in your `/etc/gitlab/gitlab.rb` configuration.
If it successfully updates the status, then something may be wrong with Sidekiq. Is it running? Do the logs show errors? This job is supposed to be enqueued every minute and might not run if a [job deduplication idempotency](../../../sidekiq/sidekiq_troubleshooting.md#clearing-a-sidekiq-job-deduplication-idempotency-key) key was not cleared properly. It takes an exclusive lease in Redis to ensure that only one of these jobs can run at a time. The primary site updates its status directly in the PostgreSQL database. Secondary sites send an HTTP Post request to the primary site with their status data.
A site also shows as "Unhealthy" if certain health checks fail. You can reveal the failure by running the following in the [Rails console](../../../operations/rails_console.md) on the affected secondary site:
```ruby
Gitlab::Geo::HealthCheck.new.perform_checks
```
If it returns `""` (an empty string) or `"Healthy"`, then the checks succeeded. If it returns anything else, then the message should explain what failed, or show the exception message.
For information about how to resolve common error messages reported from the user interface,
see [Fixing Common Errors](#fixing-common-errors).
If the user interface is not working, or you are unable to sign in, you can run the Geo
health check manually to get this information and a few more details.
#### Health check Rake task
{{< history >}}
- The use of a custom NTP server was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105514) in GitLab 15.7.
{{< /history >}}
This Rake task can be run on a **Rails** node in the **primary** or **secondary**
Geo sites:
```shell
sudo gitlab-rake gitlab:geo:check
```
Example output:
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
This machine's Geo node name matches a database record ... yes, found a secondary node named "Shanghai"
GitLab Geo tracking database is correctly configured ... yes
Database replication enabled? ... yes
Database replication working? ... yes
GitLab Geo HTTP(S) connectivity ...
* Can connect to the primary node ... yes
HTTP/HTTPS repository cloning is enabled ... yes
Machine clock is synchronized ... yes
Git user has default SSH configuration? ... yes
OpenSSH configured to use AuthorizedKeysCommand ... yes
GitLab configured to disable writing to authorized_keys file ... yes
GitLab configured to store new projects in hashed storage? ... yes
All projects are in hashed storage? ... yes
Checking Geo ... Finished
```
You can also specify a custom NTP server using environment variables. For example:
```shell
sudo gitlab-rake gitlab:geo:check NTP_HOST="ntp.ubuntu.com" NTP_TIMEOUT="30"
```
The following environment variables are supported.
| Variable | Description | Default value |
| ----------- | ----------- | ------------- |
|`NTP_HOST` | The NTP host. | `pool.ntp.org` |
|`NTP_PORT` | The NTP port the host listens on. |`ntp`|
|`NTP_TIMEOUT`| The NTP timeout in seconds. | The value defined in the `net-ntp` Ruby library ([60 seconds](https://github.com/zencoder/net-ntp/blob/3d0990214f439a5127782e0f50faeaf2c8ca7023/lib/net/ntp/ntp.rb#L6)). |
If the Rake task skips the `OpenSSH configured to use AuthorizedKeysCommand` check, the
following output displays:
```plaintext
OpenSSH configured to use AuthorizedKeysCommand ... skipped
Reason:
Cannot access OpenSSH configuration file
Try fixing it:
This is expected if you are using SELinux. You may want to check configuration manually
For more information see:
doc/administration/operations/fast_ssh_key_lookup.md
```
This issue might occur if:
- You use [SELinux](../../../operations/fast_ssh_key_lookup.md#selinux-support).
- You don't use SELinux, and the `git` user cannot access the OpenSSH configuration file due to restricted file permissions.
In the latter case, the following output shows that only the `root` user can read this file:
```plaintext
sudo stat -c '%G:%U %A %a %n' /etc/ssh/sshd_config
root:root -rw------- 600 /etc/ssh/sshd_config
```
To allow the `git` user to read the OpenSSH configuration file, without changing the file owner or permissions, use `acl`:
```plaintext
sudo setfacl -m u:git:r /etc/ssh/sshd_config
```
#### Sync status Rake task
Current sync information can be found manually by running this Rake task on any
node running Rails (Puma, Sidekiq, or Geo Log Cursor) on the Geo **secondary** site.
GitLab does **not** verify objects that are stored in Object Storage. If you are using Object Storage, you will see all of the "verified" checks showing 0 successes. This is expected and not a cause for concern.
```shell
sudo gitlab-rake geo:status
```
The output includes:
- a count of "failed" items if any failures occurred
- the percentage of "succeeded" items, relative to the "total"
Example:
```plaintext
Geo Site Information
--------------------------------------------
Name: example-us-east-2
URL: https://gitlab.example.com
Geo Role: Secondary
Health Status: Healthy
This Node's GitLab Version: 17.7.0-ee
Replication Information
--------------------------------------------
Sync Settings: Full
Database replication lag: 0 seconds
Last event ID seen from primary: 12345 (about 2 minutes ago)
Last event ID processed: 12345 (about 2 minutes ago)
Last status report was: 1 minute ago
Replication Status
--------------------------------------------
Lfs Objects replicated: succeeded 111 / total 111 (100%)
Merge Request Diffs replicated: succeeded 28 / total 28 (100%)
Package Files replicated: succeeded 90 / total 90 (100%)
Terraform State Versions replicated: succeeded 65 / total 65 (100%)
Snippet Repositories replicated: succeeded 63 / total 63 (100%)
Group Wiki Repositories replicated: succeeded 14 / total 14 (100%)
Pipeline Artifacts replicated: succeeded 112 / total 112 (100%)
Pages Deployments replicated: succeeded 55 / total 55 (100%)
Uploads replicated: succeeded 2 / total 2 (100%)
Job Artifacts replicated: succeeded 32 / total 32 (100%)
Ci Secure Files replicated: succeeded 44 / total 44 (100%)
Dependency Proxy Blobs replicated: succeeded 15 / total 15 (100%)
Dependency Proxy Manifests replicated: succeeded 2 / total 2 (100%)
Project Wiki Repositories replicated: succeeded 2 / total 2 (100%)
Design Management Repositories replicated: succeeded 1 / total 1 (100%)
Project Repositories replicated: succeeded 2 / total 2 (100%)
Verification Status
--------------------------------------------
Lfs Objects verified: succeeded 111 / total 111 (100%)
Merge Request Diffs verified: succeeded 28 / total 28 (100%)
Package Files verified: succeeded 90 / total 90 (100%)
Terraform State Versions verified: succeeded 65 / total 65 (100%)
Snippet Repositories verified: succeeded 63 / total 63 (100%)
Group Wiki Repositories verified: succeeded 14 / total 14 (100%)
Pipeline Artifacts verified: succeeded 112 / total 112 (100%)
Pages Deployments verified: succeeded 55 / total 55 (100%)
Uploads verified: succeeded 2 / total 2 (100%)
Job Artifacts verified: succeeded 32 / total 32 (100%)
Ci Secure Files verified: succeeded 44 / total 44 (100%)
Dependency Proxy Blobs verified: succeeded 15 / total 15 (100%)
Dependency Proxy Manifests verified: succeeded 2 / total 2 (100%)
Project Wiki Repositories verified: succeeded 2 / total 2 (100%)
Design Management Repositories verified: succeeded 1 / total 1 (100%)
Project Repositories verified: succeeded 2 / total 2 (100%)
```
All objects are replicated and verified, which are defined in the [Geo glossary](../../glossary.md). Read more about the
methods we use for replicating and verifying each data type in [supported Geo data types](../datatypes.md#data-types).
To find more details about failed items, check
[the `gitlab-rails/geo.log` file](../../../logs/log_parsing.md#find-most-common-geo-sync-errors)
If you notice replication or verification failures, you can try to [resolve them](synchronization_verification.md).
##### Fixing errors found when running the Geo check Rake task
When running this Rake task, you may see error messages if the nodes are not properly configured:
```shell
sudo gitlab-rake gitlab:geo:check
```
- Rails did not provide a password when connecting to the database.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: fe_sendauth: no password supplied
GitLab Geo is enabled ... Exception: fe_sendauth: no password supplied
...
Checking Geo ... Finished
```
Ensure you have the `gitlab_rails['db_password']` set to the plain-text
password used when creating the hash for `postgresql['sql_user_password']`.
- Rails is unable to connect to the database.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL on
FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL off
GitLab Geo is enabled ... Exception: FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL on
FATAL: no pg_hba.conf entry for host "1.1.1.1", user "gitlab", database "gitlabhq_production", SSL off
...
Checking Geo ... Finished
```
Ensure you have the IP address of the rails node included in `postgresql['md5_auth_cidr_addresses']`.
Also, ensure you have included the subnet mask on the IP address: `postgresql['md5_auth_cidr_addresses'] = ['1.1.1.1/32']`.
- Rails has supplied the incorrect password.
```plaintext
Checking Geo ...
GitLab Geo is available ... Exception: FATAL: password authentication failed for user "gitlab"
FATAL: password authentication failed for user "gitlab"
GitLab Geo is enabled ... Exception: FATAL: password authentication failed for user "gitlab"
FATAL: password authentication failed for user "gitlab"
...
Checking Geo ... Finished
```
Verify the correct password is set for `gitlab_rails['db_password']` that was
used when creating the hash in `postgresql['sql_user_password']` by running
`gitlab-ctl pg-password-md5 gitlab` and entering the password.
- Check returns `not a secondary node`.
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
GitLab Geo tracking database is correctly configured ... not a secondary node
Database replication enabled? ... not a secondary node
...
Checking Geo ... Finished
```
Ensure you have added the secondary site in the **Admin** area under **Geo > Sites** on the web interface for the **primary** site.
Also ensure you entered the `gitlab_rails['geo_node_name']`
when adding the secondary site in the **Admin** area of the **primary** site.
- Check returns `Exception: PG::UndefinedTable: ERROR: relation "geo_nodes" does not exist`.
```plaintext
Checking Geo ...
GitLab Geo is available ... no
Try fixing it:
Add a new license that includes the GitLab Geo feature
For more information see:
https://about.gitlab.com/features/gitlab-geo/
GitLab Geo is enabled ... Exception: PG::UndefinedTable: ERROR: relation "geo_nodes" does not exist
LINE 8: WHERE a.attrelid = '"geo_nodes"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
c.collname, col_description(a.attrelid, a.attnum) AS comment
FROM pg_attribute a
LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
WHERE a.attrelid = '"geo_nodes"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
...
Checking Geo ... Finished
```
When performing a PostgreSQL major version (9 > 10), update this is expected. Follow
the [initiate-the-replication-process](../../setup/database.md#step-3-initiate-the-replication-process).
- Rails does not appear to have the configuration necessary to connect to the Geo tracking database.
```plaintext
Checking Geo ...
GitLab Geo is available ... yes
GitLab Geo is enabled ... yes
GitLab Geo tracking database is correctly configured ... no
Try fixing it:
Rails does not appear to have the configuration necessary to connect to the Geo tracking database. If the tracking database is running on a node other than this one, then you may need to add configuration.
...
Checking Geo ... Finished
```
- If you are running the secondary site on a single node for all services, then follow [Geo database replication - Configure the secondary server](../../setup/database.md#step-2-configure-the-secondary-server).
- If you are running the secondary site's tracking database on its own node, then follow [Geo for multiple servers - Configure the Geo tracking database on the Geo secondary site](../multiple_servers.md#step-2-configure-the-geo-tracking-database-on-the-geo-secondary-site)
- If you are running the secondary site's tracking database in a Patroni cluster, then follow [Geo database replication - Configuring Patroni cluster for the tracking PostgreSQL database](../../setup/database.md#configuring-patroni-cluster-for-the-tracking-postgresql-database)
- If you are running the secondary site's tracking database in an external database, then follow [Geo with external PostgreSQL instances](../../setup/external_database.md#configure-the-tracking-database)
- If the Geo check task was run on a node which is not running a service which runs the GitLab Rails app (Puma, Sidekiq, or Geo Log Cursor), then this error can be ignored. The node does not need Rails to be configured.
##### Message: Machine clock is synchronized ... Exception
The Rake task attempts to verify that the server clock is synchronized with NTP. Synchronized clocks
are required for Geo to function correctly. As an example, for security, when the server time on the
primary site and secondary site differ by about a minute or more, requests between Geo sites
fail. If this check task fails to complete due to a reason other than mismatching times, it
does not necessarily mean that Geo will not work.
The Ruby gem which performs the check is hard coded with `pool.ntp.org` as its reference time source.
- Exception message `Machine clock is synchronized ... Exception: Timeout::Error`
This issue occurs when your server cannot access the host `pool.ntp.org`.
- Exception message `Machine clock is synchronized ... Exception: No route to host - recvfrom(2)`
This issue occurs when the hostname `pool.ntp.org` resolves to a server which does not provide a time service.
In this case, in GitLab 15.7 and later, [specify a custom NTP server using environment variables](#health-check-rake-task).
In GitLab 15.6 and earlier, use one of the following workarounds:
- Add entries in `/etc/hosts` for `pool.ntp.org` to direct the request to valid local time servers.
This fixes the long timeout and the timeout error.
- Direct the check to any valid IP address. This resolves the timeout issue, but the check fails
with the `No route to host` error, as noted previously.
[Cloud native GitLab deployments](https://docs.gitlab.com/charts/advanced/geo/#set-the-geo-primary-site)
generate an error because containers in Kubernetes do not have access to the host clock:
```plaintext
Machine clock is synchronized ... Exception: getaddrinfo: Servname not supported for ai_socktype
```
##### Message: `cannot execute INSERT in a read-only transaction`
When this error is encountered on a secondary site, it likely affects all usages of GitLab Rails such as `gitlab-rails` or `gitlab-rake` commands, as well the Puma, Sidekiq, and Geo Log Cursor services.
```plaintext
ActiveRecord::StatementInvalid: PG::ReadOnlySqlTransaction: ERROR: cannot execute INSERT in a read-only transaction
/opt/gitlab/embedded/service/gitlab-rails/app/models/application_record.rb:86:in `block in safe_find_or_create_by'
/opt/gitlab/embedded/service/gitlab-rails/app/models/concerns/cross_database_modification.rb:92:in `block in transaction'
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database.rb:332:in `block in transaction'
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database.rb:331:in `transaction'
/opt/gitlab/embedded/service/gitlab-rails/app/models/concerns/cross_database_modification.rb:83:in `transaction'
/opt/gitlab/embedded/service/gitlab-rails/app/models/application_record.rb:86:in `safe_find_or_create_by'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:21:in `by_name'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `block in populate!'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `map'
/opt/gitlab/embedded/service/gitlab-rails/app/models/shard.rb:17:in `populate!'
/opt/gitlab/embedded/service/gitlab-rails/config/initializers/fill_shards.rb:9:in `<top (required)>'
/opt/gitlab/embedded/service/gitlab-rails/config/environment.rb:7:in `<top (required)>'
/opt/gitlab/embedded/bin/bundle:23:in `load'
/opt/gitlab/embedded/bin/bundle:23:in `<main>'
```
The PostgreSQL read-replica database would be producing these errors:
```plaintext
2023-01-17_17:44:54.64268 ERROR: cannot execute INSERT in a read-only transaction
2023-01-17_17:44:54.64271 STATEMENT: /*application:web,db_config_name:main*/ INSERT INTO "shards" ("name") VALUES ('storage1') RETURNING "id"
```
This situation can occur:
- During initial configuration when a secondary site is not yet aware that it is a secondary site. To resolve the error, follow [Step 3. Add the secondary site](../configuration.md#step-3-add-the-secondary-site).
- During the upgrade of a Geo secondary site. It's possible that `gitlab_rails['auto_migrate']` is set to `true`, causing GitLab to attempt database migrations on the replica database, which is not required. To resolve the error:
1. SSH as root to the GitLab Rails node of the secondary site.
1. Edit `/etc/gitlab/gitlab.rb`, and comment out this setting or set it to false:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Check if PostgreSQL replication is working
To check if PostgreSQL replication is working, check if:
- [Sites are pointing to the correct database node](#are-sites-pointing-to-the-correct-database-node).
- [Geo can detect the current site correctly](#can-geo-detect-the-current-site-correctly).
If you're still having problems, see the [advanced replication troubleshooting](synchronization_verification.md).
#### Are sites pointing to the correct database node?
You should make sure your **primary** Geo [site](../../glossary.md) points to
the database node that has write permissions.
Any **secondary** sites should point only to read-only database nodes.
#### Can Geo detect the current site correctly?
Geo finds the current Puma or Sidekiq node's Geo [site](../../glossary.md) name in
`/etc/gitlab/gitlab.rb` with the following logic:
1. Get the "Geo node name" (there is
[an issue to rename the settings to "Geo site name"](https://gitlab.com/gitlab-org/gitlab/-/issues/335944)):
- Linux package: get the `gitlab_rails['geo_node_name']` setting.
- GitLab Helm charts: get the `global.geo.nodeName` setting (see [Charts with GitLab Geo](https://docs.gitlab.com/charts/advanced/geo/)).
1. If that is not defined, then get the `external_url` setting.
This name is used to look up the Geo site with the same **Name** in the **Geo Sites**
dashboard.
To check if the current machine has a site name that matches a site in the
database, run the check task:
```shell
sudo gitlab-rake gitlab:geo:check
```
It displays the current machine's site name and whether the matching database
record is a **primary** or **secondary** site.
```plaintext
This machine's Geo node name matches a database record ... yes, found a secondary node named "Shanghai"
```
```plaintext
This machine's Geo node name matches a database record ... no
Try fixing it:
You could add or update a Geo node database record, setting the name to "https://example.com/".
Or you could set this machine's Geo node name to match the name of an existing database record: "London", "Shanghai"
For more information see:
doc/administration/geo/replication/troubleshooting/_index.md#can-geo-detect-the-current-node-correctly
```
For more information about recommended site names in the description of the Name field, see
[Geo **Admin** area Common Settings](../../../geo_sites.md#common-settings).
### Check OS locale data compatibility
If at all possible, all Geo nodes across all sites should be deployed with the same method and operating system, as defined in the [requirements for running Geo](../../_index.md#requirements-for-running-geo).
If different operating systems or different operating system versions are deployed across Geo sites, you **must** perform a locale data compatibility check before setting up Geo. You must also check `glibc` when using a mixture of GitLab deployment methods. The locale might be different between a Linux package install, a GitLab Docker container, a Helm chart deployment, or external database services. See the [documentation on upgrading operating systems for PostgreSQL](../../../postgresql/upgrading_os.md), including how to check `glibc` version compatibility.
Geo uses PostgreSQL and Streaming Replication to replicate data across Geo sites. PostgreSQL uses locale data provided by the operating system's C library for sorting text. If the locale data in the C library is incompatible across Geo sites, it causes erroneous query results that lead to [incorrect behavior on secondary sites](https://gitlab.com/gitlab-org/gitlab/-/issues/360723).
For example, Ubuntu 18.04 (and earlier) and RHEL/CentOS 7 (and earlier) are incompatible with their later releases.
See the [PostgreSQL wiki for more details](https://wiki.postgresql.org/wiki/Locale_data_changes).
## Fixing common errors
This section documents common error messages reported in the **Admin** area on the web interface, and how to fix them.
### An existing tracking database cannot be reused
Geo cannot reuse an existing tracking database.
It is safest to use a fresh secondary, or reset the whole secondary by following
[Resetting Geo secondary site replication](synchronization_verification.md#resetting-geo-secondary-site-replication).
It is risky to reuse a secondary site without resetting it because the secondary site may have missed some Geo events. For example, missed deletion events lead to the secondary site permanently having data that should be deleted. Similarly, losing an event which physically moves the location of data leads to data permanently orphaned in one location, and missing in the other location until it is re-verified. This is why GitLab switched to hashed storage, which makes moving data unnecessary. There may be other unknown problems due to lost events.
If these kinds of risks do not apply, for example in a test environment, or if you know that the main Postgres database still contains all Geo events since the Geo site was added, then you can bypass this health check:
1. Get the last processed event time. In Rails console in the **secondary** site, run:
```ruby
Geo::EventLogState.last.created_at.utc
```
1. Copy the output, for example `2024-02-21 23:50:50.676918 UTC`.
1. Update the created time of the secondary site to make it appear older. In Rails console in the **primary** site, run:
```ruby
GeoNode.secondary_nodes.last.update_column(:created_at, DateTime.parse('2024-02-21 23:50:50.676918 UTC') - 1.second)
```
This command assumes that the affected secondary site is the one that was created last.
1. Update the secondary site's status in **Admin > Geo > Sites**. In Rails console in the **secondary** site, run:
```ruby
Geo::MetricsUpdateWorker.new.perform
```
1. The secondary site should appear healthy. If it does not, run `gitlab-rake gitlab:geo:check` on the secondary site, or try restarting Rails if you haven't done so since re-adding the secondary site.
1. To resync missing or out-of-date data, go to **Admin > Geo > Sites**.
1. Under the secondary site select **Replication Details**.
1. Select **Reverify all** for every data type.
### Geo site has a database that is writable
This error message refers to a problem with the database replica on a **secondary** site,
which Geo expects to have access to. A secondary site database that is writable
is an indication the database is not configured for replication with the primary site. It usually means, either:
- An unsupported replication method was used (for example, logical replication).
- The instructions to set up a [Geo database replication](../../setup/database.md) were not followed correctly.
- Your database connection details are incorrect, that is you have specified the wrong
user in your `/etc/gitlab/gitlab.rb` file.
Geo **secondary** sites require two separate PostgreSQL instances:
- A read-only replica of the **primary** site.
- A regular, writable instance that holds replication metadata. That is, the Geo tracking database.
This error message indicates that the replica database in the **secondary** site is misconfigured and replication has stopped.
To restore the database and resume replication, you can do one of the following:
- [Reset the Geo secondary site replication](synchronization_verification.md#resetting-geo-secondary-site-replication).
- [Set up a new Geo secondary using the Linux package](../../setup/_index.md#using-linux-package-installations).
If you set up a new secondary from scratch, you must also [remove the old site from the Geo cluster](../remove_geo_site.md).
### Geo site does not appear to be replicating the database from the primary site
The most common problems that prevent the database from replicating correctly are:
- **Secondary** sites cannot reach the **primary** site. Check credentials and
[firewall rules](../../_index.md#firewall-rules).
- SSL certificate problems. Make sure you copied `/etc/gitlab/gitlab-secrets.json` from the **primary** site.
- Database storage disk is full.
- Database replication slot is misconfigured.
- Database is not using a replication slot or another alternative and cannot catch-up because WAL files were purged.
Make sure you follow the [Geo database replication](../../setup/database.md) instructions for supported configuration.
### Geo database version (...) does not match latest migration (...)
If you are using the Linux package installation, something might have failed during upgrade. You can:
- Run `sudo gitlab-ctl reconfigure`.
- Manually trigger the database migration by running: `sudo gitlab-rake db:migrate:geo` as root on the **secondary** site.
### GitLab indicates that more than 100% of repositories were synced
This can be caused by orphaned records in the project registry. They are being cleaned
periodically using a registry worker, so give it some time to fix it itself.
### Failed checksums on primary site
Failed checksums identified by the Geo Primary Verification information screen can be caused by missing files or mismatched checksums. You can find error messages like `"Repository cannot be checksummed because it does not exist"` or `"File is not checksummable"` in the `gitlab-rails/geo.log` file.
For additional information about failed items, run the [integrity check Rake tasks](../../../raketasks/check.md#uploaded-files-integrity):
```ruby
sudo gitlab-rake gitlab:artifacts:check
sudo gitlab-rake gitlab:ci_secure_files:check
sudo gitlab-rake gitlab:lfs:check
sudo gitlab-rake gitlab:uploads:check
```
For detailed information about individual errors, use the `VERBOSE=1` variable.
### Secondary site shows "Unhealthy" in UI
If you have updated the value of `external_url` in `/etc/gitlab/gitlab.rb` for the primary site or changed the protocol from `http` to `https`, you may see that secondary sites are shown as `Unhealthy`. You may also find the following error in `geo.log`:
```plaintext
"class": "Geo::NodeStatusRequestService",
...
"message": "Failed to Net::HTTP::Post to primary url: http://primary-site.gitlab.tld/api/v4/geo/status",
"error": "Failed to open TCP connection to <PRIMARY_IP_ADDRESS>:80 (Connection refused - connect(2) for \"<PRIMARY_ID_ADDRESS>\" port 80)"
```
In this case, make sure to update the changed URL on all your sites:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo > Sites**.
1. Change the URL and save the change.
### Message: `ERROR: canceling statement due to conflict with recovery` during backup
Running a backup on a Geo **secondary** [is not supported](https://gitlab.com/gitlab-org/gitlab/-/issues/211668).
When running a backup on a **secondary** you might encounter the following error message:
```plaintext
Dumping PostgreSQL database gitlabhq_production ...
pg_dump: error: Dumping the contents of table "notes" failed: PQgetResult() failed.
pg_dump: error: Error message from server: ERROR: canceling statement due to conflict with recovery
DETAIL: User query might have needed to see row versions that must be removed.
pg_dump: error: The command was: COPY public.notes (id, note, [...], last_edited_at) TO stdout;
```
To prevent a database backup being made automatically during GitLab upgrades on your Geo **secondaries**,
create the following empty file:
```shell
sudo touch /etc/gitlab/skip-auto-backup
```
### High CPU usage on primary during object verification
From GitLab 16.11 to GitLab 17.2, a missing PostgreSQL index causes high CPU
usage and slow artifact verification progress. Additionally, the Geo secondary
sites might report as unhealthy. [Issue 471727](https://gitlab.com/gitlab-org/gitlab/-/issues/471727) describes the behavior in detail.
To determine if you might be experiencing this issue, follow the steps to
[confirm if you are affected](https://gitlab.com/gitlab-org/gitlab/-/issues/471727#to-confirm-if-you-are-affected).
If you are affected, follow the steps in the [workaround](https://gitlab.com/gitlab-org/gitlab/-/issues/471727#workaround)
to manually create the index. Creating the index causes PostgreSQL to
consume slightly more resources until it finishes. Afterward, CPU usage might
remain high while verification continues, but queries should complete
significantly faster, and secondary site status should update correctly.
### Verification failed with: `Verification timed out after (...)`
From GitLab 16.11, Geo may create duplicate `JobArtifactRegistry` entries for the same `artifact_id`, which can lead to synchronization
failures between primary and secondary sites. This issue may also impact `UploadRegistry` and `PackageFileRegistry` entries.
To determine if you might be experiencing this issue and remove the duplicate entries:
1. Open a [Rails console](../../../operations/rails_console.md) in the secondary site.
1. Get the number of model record IDs that have duplicates:
```ruby
artifact_ids = Geo::JobArtifactRegistry.group(:artifact_id).having('COUNT(*) > 1').pluck(:artifact_id); artifact_ids.size
upload_ids = Geo::UploadRegistry.group(:file_id).having('COUNT(*) > 1').pluck(:file_id); upload_ids.size
package_file_ids = Geo::PackageFileRegistry.group(:package_file_id).having('COUNT(*) > 1').pluck(:package_file_id); package_file_ids.size
```
1. Output the IDs:
```ruby
puts 'BEGIN Artifact IDs', artifact_ids, 'END Artifact IDs'
puts 'BEGIN Upload IDs', upload_ids, 'END Upload IDs'
puts 'BEGIN Package File IDs', package_file_ids, 'END Package File IDs'
```
If the output is empty, you are not affected. Otherwise, save
the terminal output in a text file in case you lose connection later.
1. Delete all duplicates:
```ruby
Geo::JobArtifactRegistry.where(artifact_id: artifact_ids).delete_all
Geo::UploadRegistry.where(file_id: upload_ids).delete_all
Geo::PackageFileRegistry.where(package_file_id: package_file_ids).delete_all
```
1. Wait for the background jobs to create the registry rows again and resync.
Follow [issue 479852](https://gitlab.com/gitlab-org/gitlab/-/issues/479852) to get feedback on the fix.
### Error `end of file reached` when running Geo Rake check task on secondary
You may face the following error when running the [health check Rake task](common.md#health-check-rake-task) on the secondary site:
```plaintext
Can connect to the primary node ... no
Reason:
end of file reached
```
It might happen if the incorrect URL to the primary site was specified in the setting. To troubleshoot it,
run the following commands in [the Rails Console](../../../operations/rails_console.md):
```ruby
primary = Gitlab::Geo.primary_node
primary.internal_uri
Gitlab::HTTP.get(primary.internal_uri, allow_local_requests: true, limit: 10)
```
Make sure that the value of `internal_uri` is correct in the previous output.
If the URL of the primary site is incorrect, double-check it in `/etc/gitlab/gitlab.rb`, and in **Admin > Geo > Sites**.
### Excessive database IO from Geo metrics collection
If you're experiencing high database load due to frequent Geo metrics collection, you can reduce the frequency of the `geo_metrics_update_worker` job. This adjustment can help alleviate database strain in large GitLab instances where metrics collection significantly impacts database performance.
Increasing the interval means that your Geo metrics are updated less frequently. This results in metrics being out-of-date for longer periods of time, which may impact your ability to monitor Geo replication in real-time. If metrics are out-of-date for more than 10 minutes, the site is arbitrarily marked as "Unhealthy" in the Admin Area.
The following example sets the job to run every 30 minutes. Adjust the cron schedule based on your needs.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Add or modify the following setting in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['geo_metrics_update_worker_cron'] = "*/30 * * * *"
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
geo_metrics_update_worker:
cron: "*/30 * * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
|
https://docs.gitlab.com/administration/geo/replication/failover
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/failover.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
failover.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
<!-- vale off -->
This document was moved to [another location](../../disaster_recovery/failover_troubleshooting.md).
<!-- This redirect file can be deleted after <2025-08-02>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
---
redirect_to: ../../disaster_recovery/failover_troubleshooting.md
remove_date: '2025-08-02'
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
<!-- markdownlint-disable -->
<!-- vale off -->
This document was moved to [another location](../../disaster_recovery/failover_troubleshooting.md).
<!-- This redirect file can be deleted after <2025-08-02>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
https://docs.gitlab.com/administration/geo/replication/client_http
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/client_http.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
client_http.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting Geo client and HTTP response code errors
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## Fixing client errors
### Authorization errors from LFS HTTP(S) client requests
You may have problems if you're running a version of [Git LFS](https://git-lfs.com/) before 2.4.2.
As noted in [this authentication issue](https://github.com/git-lfs/git-lfs/issues/3025),
requests redirected from the secondary to the primary site do not properly send the
Authorization header. This may result in either an infinite `Authorization <-> Redirect`
loop, or Authorization error messages.
### Error: `Net::ReadTimeout` when pushing through SSH on a Geo secondary
When you push large repositories through SSH on a Geo secondary site, you may encounter a timeout.
This is because Rails proxies the push to the primary and has a 60 second default timeout,
[as described in this Geo issue](https://gitlab.com/gitlab-org/gitlab/-/issues/7405).
Current workarounds are:
- Push through HTTP instead, where Workhorse proxies the request to the primary (or redirects to the primary if Geo proxying is not enabled).
- Push directly to the primary.
Example log (`gitlab-shell.log`):
```plaintext
Failed to contact primary https://primary.domain.com/namespace/push_test.git\\nError: Net::ReadTimeout\",\"result\":null}" code=500 method=POST pid=5483 url="http://127.0.0.1:3000/api/v4/geo/proxy_git_push_ssh/push"
```
### Repair OAuth authorization between Geo sites
When upgrading a Geo site, you might not be able to sign into a secondary site that only uses OAuth for authentication. In that case, start a [Rails console](../../../operations/rails_console.md) session on your primary site and perform the following steps:
1. To find the affected node, first list all the Geo Nodes you have:
```ruby
GeoNode.all
```
1. Repair the affected Geo node by specifying the ID:
```ruby
GeoNode.find(<id>).repair
```
## HTTP response code errors
### Secondary site returns 502 errors with Geo proxying
When [Geo proxying for secondary sites](../../secondary_proxy/_index.md) is enabled, and the secondary site user interface returns
502 errors, it is possible that the response header proxied from the primary site is too large.
Check the NGINX logs for errors similar to this example:
```plaintext
2022/01/26 00:02:13 [error] 26641#0: *829148 upstream sent too big header while reading response header from upstream, client: 10.0.2.2, server: geo.staging.gitlab.com, request: "POST /users/sign_in HTTP/2.0", upstream: "http://unix:/var/opt/gitlab/gitlab-workhorse/sockets/socket:/users/sign_in", host: "geo.staging.gitlab.com", referrer: "https://geo.staging.gitlab.com/users/sign_in"
```
To resolve this issue:
1. Set `nginx['proxy_custom_buffer_size'] = '8k'` in `/etc/gitlab.rb` on all web nodes on the secondary site.
1. Reconfigure the **secondary** using `sudo gitlab-ctl reconfigure`.
If you still get this error, you can further increase the buffer size by repeating the previous steps
and changing the `8k` size, for example by doubling it to `16k`.
### Geo Admin area shows `Unknown` for health status and 'Request failed with status code 401'
If using a load balancer, ensure that the load balancer's URL is set as the `external_url` in the
`/etc/gitlab/gitlab.rb` of the nodes behind the load balancer.
On the primary site, go to **Admin > Geo > Settings** and find the **Allowed Geo IP** field. Ensure the IP address of the secondary site is listed.
### Primary site returns 500 error when accessing `/admin/geo/replication/projects`
Navigating to **Admin > Geo > Replication** (or `/admin/geo/replication/projects`) on a primary Geo site, shows a 500 error, while that same link on the secondary works fine. The primary's `production.log` has a similar entry to the following:
```plaintext
Geo::TrackingBase::SecondaryNotConfigured: Geo secondary database is not configured
from ee/app/models/geo/tracking_base.rb:26:in `connection'
[..]
from ee/app/views/admin/geo/projects/_all.html.haml:1
```
On a Geo primary site this error can be ignored.
This happens because GitLab is attempting to display registries from the [Geo tracking database](../../_index.md#geo-tracking-database) which doesn't exist on the primary site (only the original projects exist on the primary; no replicated projects are present, therefore no tracking database exists).
### Secondary site returns 400 error "Request header or cookie too large"
This error can happen when the internal URL of the primary site is incorrect.
For example, when you use a unified URL and the primary site's internal URL is also equal to the external URL. This causes a loop when a secondary site proxies requests to the primary site's internal URL.
To fix this issue, set the primary site's internal URL to a URL that is:
- Unique to the primary site.
- Accessible from all secondary sites.
1. Visit the primary site.
1. [Set up the internal URLs](../../../geo_sites.md#set-up-the-internal-urls).
### Secondary site returns `Received HTTP code 403 from proxy after CONNECT`
If you have installed GitLab using the Linux package (Omnibus) and have configured the `no_proxy` [custom environment variable](https://docs.gitlab.com/omnibus/settings/environment-variables.html) for Gitaly, you may experience this issue. Affected versions:
- `15.4.6`
- `15.5.0`-`15.5.6`
- `15.6.0`-`15.6.3`
- `15.7.0`-`15.7.1`
This is due to [a bug introduced in the included version of cURL](https://github.com/curl/curl/issues/10122) shipped with
the Linux package 15.4.6 and later. You should upgrade to a later version where this has been
[fixed](https://about.gitlab.com/releases/2023/01/09/security-release-gitlab-15-7-2-released/).
The bug causes all wildcard domains (`.example.com`) to be ignored except for the last on in the `no_proxy` environment variable list. Therefore, if for any reason you cannot upgrade to a newer version, you can work around the issue by moving your wildcard domain to the end of the list:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitaly['env'] = {
"no_proxy" => "sever.yourdomain.org, .yourdomain.com",
}
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
You can have only one wildcard domain in the `no_proxy` list.
### Geo Admin area returns 404 error for a secondary site
Sometimes `sudo gitlab-rake gitlab:geo:check` indicates that **Rails nodes of the secondary** sites are
healthy, but a 404 Not Found error message for the **secondary** site is returned in the Geo **Admin** area on the web interface for
the **primary** site.
To resolve this issue:
- Try restarting **each Rails, Sidekiq and Gitaly nodes on your secondary site** using `sudo gitlab-ctl restart`.
- Check `/var/log/gitlab/gitlab-rails/geo.log` on Sidekiq nodes to see if the **secondary** site is
using IPv6 to send its status to the **primary** site. If it is, add an entry to
the **primary** site using IPv4 in the `/etc/hosts` file. Alternatively, you should
[enable IPv6 on the **primary** site](https://docs.gitlab.com/omnibus/settings/nginx.html#setting-the-nginx-listen-address-or-addresses).
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting Geo client and HTTP response code errors
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## Fixing client errors
### Authorization errors from LFS HTTP(S) client requests
You may have problems if you're running a version of [Git LFS](https://git-lfs.com/) before 2.4.2.
As noted in [this authentication issue](https://github.com/git-lfs/git-lfs/issues/3025),
requests redirected from the secondary to the primary site do not properly send the
Authorization header. This may result in either an infinite `Authorization <-> Redirect`
loop, or Authorization error messages.
### Error: `Net::ReadTimeout` when pushing through SSH on a Geo secondary
When you push large repositories through SSH on a Geo secondary site, you may encounter a timeout.
This is because Rails proxies the push to the primary and has a 60 second default timeout,
[as described in this Geo issue](https://gitlab.com/gitlab-org/gitlab/-/issues/7405).
Current workarounds are:
- Push through HTTP instead, where Workhorse proxies the request to the primary (or redirects to the primary if Geo proxying is not enabled).
- Push directly to the primary.
Example log (`gitlab-shell.log`):
```plaintext
Failed to contact primary https://primary.domain.com/namespace/push_test.git\\nError: Net::ReadTimeout\",\"result\":null}" code=500 method=POST pid=5483 url="http://127.0.0.1:3000/api/v4/geo/proxy_git_push_ssh/push"
```
### Repair OAuth authorization between Geo sites
When upgrading a Geo site, you might not be able to sign into a secondary site that only uses OAuth for authentication. In that case, start a [Rails console](../../../operations/rails_console.md) session on your primary site and perform the following steps:
1. To find the affected node, first list all the Geo Nodes you have:
```ruby
GeoNode.all
```
1. Repair the affected Geo node by specifying the ID:
```ruby
GeoNode.find(<id>).repair
```
## HTTP response code errors
### Secondary site returns 502 errors with Geo proxying
When [Geo proxying for secondary sites](../../secondary_proxy/_index.md) is enabled, and the secondary site user interface returns
502 errors, it is possible that the response header proxied from the primary site is too large.
Check the NGINX logs for errors similar to this example:
```plaintext
2022/01/26 00:02:13 [error] 26641#0: *829148 upstream sent too big header while reading response header from upstream, client: 10.0.2.2, server: geo.staging.gitlab.com, request: "POST /users/sign_in HTTP/2.0", upstream: "http://unix:/var/opt/gitlab/gitlab-workhorse/sockets/socket:/users/sign_in", host: "geo.staging.gitlab.com", referrer: "https://geo.staging.gitlab.com/users/sign_in"
```
To resolve this issue:
1. Set `nginx['proxy_custom_buffer_size'] = '8k'` in `/etc/gitlab.rb` on all web nodes on the secondary site.
1. Reconfigure the **secondary** using `sudo gitlab-ctl reconfigure`.
If you still get this error, you can further increase the buffer size by repeating the previous steps
and changing the `8k` size, for example by doubling it to `16k`.
### Geo Admin area shows `Unknown` for health status and 'Request failed with status code 401'
If using a load balancer, ensure that the load balancer's URL is set as the `external_url` in the
`/etc/gitlab/gitlab.rb` of the nodes behind the load balancer.
On the primary site, go to **Admin > Geo > Settings** and find the **Allowed Geo IP** field. Ensure the IP address of the secondary site is listed.
### Primary site returns 500 error when accessing `/admin/geo/replication/projects`
Navigating to **Admin > Geo > Replication** (or `/admin/geo/replication/projects`) on a primary Geo site, shows a 500 error, while that same link on the secondary works fine. The primary's `production.log` has a similar entry to the following:
```plaintext
Geo::TrackingBase::SecondaryNotConfigured: Geo secondary database is not configured
from ee/app/models/geo/tracking_base.rb:26:in `connection'
[..]
from ee/app/views/admin/geo/projects/_all.html.haml:1
```
On a Geo primary site this error can be ignored.
This happens because GitLab is attempting to display registries from the [Geo tracking database](../../_index.md#geo-tracking-database) which doesn't exist on the primary site (only the original projects exist on the primary; no replicated projects are present, therefore no tracking database exists).
### Secondary site returns 400 error "Request header or cookie too large"
This error can happen when the internal URL of the primary site is incorrect.
For example, when you use a unified URL and the primary site's internal URL is also equal to the external URL. This causes a loop when a secondary site proxies requests to the primary site's internal URL.
To fix this issue, set the primary site's internal URL to a URL that is:
- Unique to the primary site.
- Accessible from all secondary sites.
1. Visit the primary site.
1. [Set up the internal URLs](../../../geo_sites.md#set-up-the-internal-urls).
### Secondary site returns `Received HTTP code 403 from proxy after CONNECT`
If you have installed GitLab using the Linux package (Omnibus) and have configured the `no_proxy` [custom environment variable](https://docs.gitlab.com/omnibus/settings/environment-variables.html) for Gitaly, you may experience this issue. Affected versions:
- `15.4.6`
- `15.5.0`-`15.5.6`
- `15.6.0`-`15.6.3`
- `15.7.0`-`15.7.1`
This is due to [a bug introduced in the included version of cURL](https://github.com/curl/curl/issues/10122) shipped with
the Linux package 15.4.6 and later. You should upgrade to a later version where this has been
[fixed](https://about.gitlab.com/releases/2023/01/09/security-release-gitlab-15-7-2-released/).
The bug causes all wildcard domains (`.example.com`) to be ignored except for the last on in the `no_proxy` environment variable list. Therefore, if for any reason you cannot upgrade to a newer version, you can work around the issue by moving your wildcard domain to the end of the list:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitaly['env'] = {
"no_proxy" => "sever.yourdomain.org, .yourdomain.com",
}
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
You can have only one wildcard domain in the `no_proxy` list.
### Geo Admin area returns 404 error for a secondary site
Sometimes `sudo gitlab-rake gitlab:geo:check` indicates that **Rails nodes of the secondary** sites are
healthy, but a 404 Not Found error message for the **secondary** site is returned in the Geo **Admin** area on the web interface for
the **primary** site.
To resolve this issue:
- Try restarting **each Rails, Sidekiq and Gitaly nodes on your secondary site** using `sudo gitlab-ctl restart`.
- Check `/var/log/gitlab/gitlab-rails/geo.log` on Sidekiq nodes to see if the **secondary** site is
using IPv6 to send its status to the **primary** site. If it is, add an entry to
the **primary** site using IPv4 in the `/etc/hosts` file. Alternatively, you should
[enable IPv6 on the **primary** site](https://docs.gitlab.com/omnibus/settings/nginx.html#setting-the-nginx-listen-address-or-addresses).
|
https://docs.gitlab.com/administration/geo/replication/synchronization_verification
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/synchronization_verification.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
synchronization_verification.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting Geo synchronization and verification errors
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you notice replication or verification failures in `Admin > Geo > Sites` or the [Sync status Rake task](common.md#sync-status-rake-task), you can try to resolve the failures with the following general steps:
1. Geo automatically retries failures. If the failures are new and few in number, or if you suspect the root cause is already resolved, then you can wait to see if the failures go away.
1. If failures were present for a long time, then many retries have already occurred, and the interval between automatic retries has increased to up to 4 hours depending on the type of failure. If you suspect the root cause is already resolved, you can [manually retry replication or verification](#manually-retry-replication-or-verification) to avoid the wait.
1. If the failures persist, use the following sections to try to resolve them.
## Manually retry replication or verification
In [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) in a
secondary Geo site, you can:
- [Manually resync and reverify individual components](#resync-and-reverify-individual-components)
- [Manually resync and reverify multiple components](#resync-and-reverify-multiple-components)
### Resync and reverify individual components
On the secondary site, visit **Admin** > **Geo** > **Replication** to force a resync or reverify of individual items.
However, if this doesn't work, you can perform the same action using the Rails console. The
following sections describe how to use internal application commands in the
[Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to cause
replication or verification for individual records synchronously or asynchronously.
#### Obtaining a Replicator instance
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
Before you can perform any sync or verify operations, you need to obtain a Replicator instance.
First, [start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
in a **primary** or **secondary** site, depending on what you want to do.
**Primary** site:
- You can checksum a resource
**Secondary** site:
- You can sync a resource
- You can checksum a resource and verify that checksum against the primary site's checksum
Next, run one of the following snippets to get a Replicator instance.
##### Given a model record's ID
- Replace `123` with the actual ID.
- Replace `Packages::PackageFile` with any of the
[Geo data type Model classes](#geo-data-type-model-classes).
```ruby
model_record = Packages::PackageFile.find_by(id: 123)
replicator = model_record.replicator
```
##### Given a registry record's ID
- Replace `432` with the actual ID. A Registry record may or may not have the same ID
value as the Model record that it tracks.
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
In a secondary Geo site:
```ruby
registry_record = Geo::PackageFileRegistry.find_by(id: 432)
replicator = registry_record.replicator
```
##### Given an error message in a Registry record's `last_sync_failure`
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
- Replace `error message here` with the actual error message.
```ruby
registry = Geo::PackageFileRegistry.find_by("last_sync_failure LIKE '%error message here%'")
replicator = registry.replicator
```
##### Given an error message in a Registry record's `verification_failure`
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
- Replace `error message here` with the actual error message.
```ruby
registry = Geo::PackageFileRegistry.find_by("verification_failure LIKE '%error message here%'")
replicator = registry.replicator
```
#### Performing operations with a Replicator instance
After you have a Replicator instance stored in a `replicator` variable, you can perform many
operations:
##### Sync in the console
This snippet only works in a **secondary** site.
This executes the sync code synchronously in the console, so you can observe how long it takes to
sync a resource, or view a full error backtrace.
```ruby
replicator.sync
```
Optionally, make the log level of the console more verbose than the configured log level, and then
perform a sync:
```ruby
Rails.logger.level = :debug
```
##### Checksum or verify in the console
This snippet works in any **primary** or **secondary** site.
In a **primary** site, it checksums the resource and stores the result in the main GitLab
database. In a **secondary** site, it checksums the resource, compares it against the checksum in
the main GitLab database (generated by the **primary** site), and stores the result in the Geo
Tracking database.
This executes the checksum and verification code synchronously in the console, so you can observe
how long it takes, or view a full error backtrace.
```ruby
replicator.verify
```
##### Sync in a Sidekiq job
This snippet only works in a **secondary** site.
It enqueues a job for Sidekiq to perform a [sync](#sync-in-the-console) of the resource.
```ruby
replicator.enqueue_sync
```
##### Verify in a Sidekiq job
This snippet works in any **primary** or **secondary** site.
It enqueues a job for Sidekiq to perform a
[checksum or verify](#checksum-or-verify-in-the-console) of the resource.
```ruby
replicator.verify_async
```
##### Get a model record
This snippet works in any **primary** or **secondary** site.
```ruby
replicator.model_record
```
##### Get a registry record
This snippet only works in a **secondary** site because registry tables are stored in the Geo
Tracking DB.
```ruby
replicator.registry
```
#### Geo data type Model classes
A Geo data type is a specific class of data that is required by one or more GitLab features to store
relevant data and is replicated by Geo to secondary sites.
- **Blob types**:
- `Ci::JobArtifact`
- `Ci::PipelineArtifact`
- `Ci::SecureFile`
- `LfsObject`
- `MergeRequestDiff`
- `Packages::PackageFile`
- `PagesDeployment`
- `Terraform::StateVersion`
- `Upload`
- `DependencyProxy::Manifest`
- `DependencyProxy::Blob`
- **Git Repository types**:
- `DesignManagement::Repository`
- `ProjectRepository`
- `ProjectWikiRepository`
- `SnippetRepository`
- `GroupWikiRepository`
- **Other types**:
- `ContainerRepository`
The main kinds of classes are Registry, Model, and Replicator. If you have an instance of one of
these classes, you can get the others. The Registry and Model mostly manage PostgreSQL DB state. The
Replicator knows how to replicate or verify the non-PostgreSQL data (file/Git repository/Container
repository).
#### Geo Registry classes
In the context of GitLab Geo, a **registry record** refers to registry tables in
the Geo tracking database. Each record tracks a single replicable in the main
GitLab database, such as an LFS file, or a project Git repository. The Rails
models that correspond to Geo registry tables that can be queried are:
- **Blob types**:
- `Geo::CiSecureFileRegistry`
- `Geo::DependencyProxyBlobRegistry`
- `Geo::DependencyProxyManifestRegistry`
- `Geo::JobArtifactRegistry`
- `Geo::LfsObjectRegistry`
- `Geo::MergeRequestDiffRegistry`
- `Geo::PackageFileRegistry`
- `Geo::PagesDeploymentRegistry`
- `Geo::PipelineArtifactRegistry`
- `Geo::ProjectWikiRepositoryRegistry`
- `Geo::SnippetRepositoryRegistry`
- `Geo::TerraformStateVersionRegistry`
- `Geo::UploadRegistry`
- **Git Repository types**:
- `Geo::DesignManagementRepositoryRegistry`
- `Geo::ProjectRepositoryRegistry`
- `Geo::ProjectWikiRepositoryRegistry`
- `Geo::SnippetRepositoryRegistry`
- `Geo::GroupWikiRepositoryRegistry`
- **Other types**:
- `Geo::ContainerRepositoryRegistry`
### Resync and reverify multiple components
{{< history >}}
- Bulk resync and reverify [added](https://gitlab.com/gitlab-org/gitlab/-/issues/364729) in GitLab 16.5.
{{< /history >}}
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
The following sections describe how to use internal application commands in the
[Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to cause bulk
replication or verification.
#### Resync all resources of one component
You can schedule a full resync of all resources of one component from the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Under **Replication details**, select the desired component.
1. Select **Resync all**.
Alternatively,
[start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
**on the secondary Geo site** to gather more information, or execute these operations manually using
the snippets below.
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
##### Sync all resources of one component that failed to sync
The following script:
- Loops over all failed repositories.
- Displays the Geo sync and verification metadata, including the reasons for the last failure.
- Attempts to resync the repository.
- Reports back if a failure occurs, and why.
- Might take some time to complete. Each repository check must complete
before reporting back the result. If your session times out, take measures
to allow the process to continue running such as starting a `screen` session,
or running it using [Rails runner](../../../operations/rails_console.md#using-the-rails-runner)
and `nohup`.
```ruby
Geo::ProjectRepositoryRegistry.failed.find_each do |registry|
begin
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Last Sync Failure: '#{registry.last_sync_failure}'"
registry.replicator.sync
puts "Sync initiated for registry ID: #{registry.id}"
rescue => e
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Failed: '#{e}'", e.backtrace.join("\n")
end
end; nil
```
#### Reverify one component on all sites
If the **primary** site's checksums are in question, then you need to make the **primary** site recalculate checksums. A "full re-verification" is then achieved, because after each checksum is recalculated on a **primary** site, events are generated which propagate to all **secondary** sites, causing them to recalculate their checksums and compare values. Any mismatch marks the registry as `sync failed`, which causes sync retries to be scheduled.
The UI does not provide a button to do a full re-verification. You can simulate this by setting your **primary** site's `Re-verification interval` to 1 (day) in **Admin** > **Geo** > **Nodes** > **Edit**. The **primary** site will then recalculate the checksum of any resource that has been checksummed more than 1 day ago.
Optionally, you can do this manually:
1. SSH into a GitLab Rails node in the **primary** site.
1. Open the [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session).
1. Replacing `Upload` with any of the [Geo data type Model classes](#geo-data-type-model-classes),
mark all resources as `pending verification`:
```ruby
Upload.verification_state_table_class.each_batch do |relation|
relation.update_all(verification_state: 0)
end
```
##### Reverify all resources that failed to checksum on the primary site
The system automatically reverifies all resources that failed to checksum on the primary site, but
it uses a progressive backoff scheme to avoid an excessive volume of failures.
Optionally, for example if you've completed an attempted intervention, you can manually trigger
reverification sooner:
1. SSH into a GitLab Rails node in the **primary** site.
1. Open the [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session).
1. Replacing `Upload` with any of the [Geo data type Model classes](#geo-data-type-model-classes),
mark all resources as `pending verification`:
```ruby
Upload.verification_state_table_class.where(verification_state: 3).each_batch do |relation|
relation.update_all(verification_state: 0)
end
```
#### Reverify one component on one secondary site
If you believe the **primary** site checksums are correct, you can schedule a reverification of one
component on one **secondary** site from the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Under **Replication details**, select the desired component.
1. Select **Reverify all**.
## Errors
### Message: `The file is missing on the Geo primary site`
The sync failure `The file is missing on the Geo primary site` is common when
setting up a secondary Geo site for the first time, which is caused by data
inconsistencies on the primary site.
Data inconsistencies and missing files can occur due to system or human errors
when operating GitLab. For example, an instance administrator manually deletes
several artifacts on the local file system. Such changes are not properly
propagated to the database and result in inconsistencies. These inconsistencies
remain and can cause frictions. Geo secondaries might continue to try
replicating those files as they are still referenced in the database but no
longer exist.
{{< alert type="note" >}}
In case of a recent migration from local to object storage, see the dedicated
[object storage troubleshooting section](../../../object_storage.md#inconsistencies-after-migrating-to-object-storage).
{{< /alert >}}
#### Identify inconsistencies
When missing files or inconsistencies are present, you can encounter entries in `geo.log` such as the following. Take note of the field `"primary_missing_file" : true`:
```json
{
"bytes_downloaded" : 0,
"class" : "Geo::BlobDownloadService",
"correlation_id" : "01JT69C1ECRBEMZHA60E5SAX8E",
"download_success" : false,
"download_time_s" : 0.196,
"gitlab_host" : "gitlab.example.com",
"mark_as_synced" : false,
"message" : "Blob download",
"model_record_id" : 55,
"primary_missing_file" : true,
"reason" : "Not Found",
"replicable_name" : "upload",
"severity" : "WARN",
"status_code" : 404,
"time" : "2025-05-01T16:02:44.836Z",
"url" : "http://gitlab.example.com/api/v4/geo/retrieve/upload/55"
}
```
The same errors are also reflected in the UI under **Admin** > **Geo** > **Sites** when reviewing the synchronization status of specific replicables. In this scenario, a specific upload is missing:


#### Clean up inconsistencies
{{< alert type="warning" >}}
Ensure you have a recent and working backup at hand before issuing any deletion commands.
{{< /alert >}}
To remove those errors, first identify which particular resources are affected. Then, run the appropriate `destroy` commands to ensure the deletion is propagated across all Geo sites and their databases. Based on the previous scenario, an **upload** is causing those errors which is used as an example below.
1. Map the identified inconsistencies to their respective [Geo Model class](#geo-data-type-model-classes) name. The class name is needed in the following steps. In this scenario, for uploads it corresponds to `Upload`.
1. Start a [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) on the **Geo primary site**.
1. Query all resources where verification failed due to missing files based on the *Geo Model class* of the previous step. Adjust or remove the `limit(20)` to display more results. Observe how the listed resources should match the failed ones shown in the UI:
```ruby
Upload.verification_failed.where("verification_failure like '%File is not checksummable%'").limit(20)
=> #<Upload:0x00007b362bb6c4e8
id: 55,
size: 13346,
path: "503d99159e2aa8a3ac23602058cfdf58/openbao.png",
checksum: "db29d233de49b25d2085dcd8610bac787070e721baa8dcedba528a292b6e816b",
model_id: 1,
model_type: "Project",
uploader: "FileUploader",
created_at: Thu, 01 May 2025 15:54:10.549178000 UTC +00:00,
store: 1,
mount_point: nil,
secret: "[FILTERED]",
version: 2,
uploaded_by_user_id: 1,
organization_id: nil,
namespace_id: nil,
project_id: 1,
verification_checksum: nil>
```
1. Optionally, use the `id` of the affected resources to determine if they are still needed:
```ruby
Upload.find(55)
=> #<Upload:0x00007b362bb6c4e8
id: 55,
size: 13346,
path: "503d99159e2aa8a3ac23602058cfdf58/openbao.png",
checksum: "db29d233de49b25d2085dcd8610bac787070e721baa8dcedba528a292b6e816b",
model_id: 1,
model_type: "Project",
uploader: "FileUploader",
created_at: Thu, 01 May 2025 15:54:10.549178000 UTC +00:00,
store: 1,
mount_point: nil,
secret: "[FILTERED]",
version: 2,
uploaded_by_user_id: 1,
organization_id: nil,
namespace_id: nil,
project_id: 1,
verification_checksum: nil>
```
- If you determine that the affected resources need to be recovered, then you can explore the following options (non-exhaustive) to recover them:
- Check if the secondary site has the object and manually copy them to the primary.
- Look through old backups and manually copy the object back into the primary site.
- Spot check some to try to determine that it's probably fine to destroy the records, for example, if they are all very old artifacts, then maybe they are not critical data.
1. Use the `id` of the identified resources to properly delete them individually or in bulk by using `destroy`. Ensure to use the appropriate *Geo Model class* name.
- Delete individual resources:
```ruby
Upload.find(55).destroy
```
- Delete all affected resources:
```ruby
def destroy_uploads_not_checksummable
uploads = Upload.verification_failed.where("verification_failure like '%File is not checksummable%'");1
puts "Found #{uploads.count} resources that failed verification with 'File is not checksummable'."
puts "Enter 'y' to continue: "
prompt = STDIN.gets.chomp
if prompt != 'y'
puts "Exiting without action..."
return
end
puts "Destroying all..."
uploads.destroy_all
end
destroy_uploads_not_checksummable
```
Repeat the steps for all affected resources and Geo data types.
### Message: `"Error during verification","error":"File is not checksummable"`
The error `"Error during verification","error":"File is not checksummable"` is caused by inconsistencies on the primary site. Follow the instructions provided in [The file is missing on the Geo primary site](#message-the-file-is-missing-on-the-geo-primary-site).
### Failed verification of Uploads on the primary Geo site
If verification of some uploads is failing on the primary Geo site with `verification_checksum = nil` and with `verification_failure` containing ``Error during verification: undefined method `underscore' for NilClass:Class`` or ``The model which owns this Upload is missing.``, this is due to orphaned Uploads. The parent record owning the Upload (the upload's "model") has somehow been deleted, but the Upload record still exists. This is usually due to a bug in the application, introduced by implementing bulk delete of the "model" while forgetting to bulk delete its associated Upload records. These verification failures are therefore not failures to verify, rather, the errors are a result of bad data in Postgres.
You can find these errors in the `geo.log` file on the primary Geo site.
To confirm that model records are missing, you can run a Rake task on the primary Geo site:
```shell
sudo gitlab-rake gitlab:uploads:check
```
You can delete these Upload records on the primary Geo site to get rid of these failures by running the following script from the [Rails console](../../../operations/rails_console.md):
```ruby
def delete_orphaned_uploads(dry_run: true)
if dry_run
p "This is a dry run. Upload rows will only be printed."
else
p "This is NOT A DRY RUN! Upload rows will be deleted from the DB!"
end
subquery = Geo::UploadState.where("(verification_failure LIKE 'Error during verification: The model which owns this Upload is missing.%' OR verification_failure = 'Error during verification: undefined method `underscore'' for NilClass:Class') AND verification_checksum IS NULL")
uploads = Upload.where(upload_state: subquery)
p "Found #{uploads.count} uploads with a model that does not exist"
uploads_deleted = 0
begin
uploads.each do |upload|
if dry_run
p upload
else
uploads_deleted=uploads_deleted + 1
p upload.destroy!
end
rescue => e
puts "checking upload #{upload.id} failed with #{e.message}"
end
end
p "#{uploads_deleted} remote objects were destroyed." unless dry_run
end
```
The previous script defines a method named `delete_orphaned_uploads` which you can call like this to do a dry run:
```ruby
delete_orphaned_uploads(dry_run: true)
```
And to actually delete the orphaned upload rows:
```ruby
delete_orphaned_uploads(dry_run: false)
```
### Error: `Error syncing repository: 13:fatal: could not read Username`
The `last_sync_failure` error
`Error syncing repository: 13:fatal: could not read Username for 'https://gitlab.example.com': terminal prompts disabled`
indicates that JWT authentication is failing during a Geo clone or fetch request.
First, check that system clocks are synced. Run the [Health check Rake task](common.md#health-check-rake-task), or
manually check that `date`, on all Sidekiq nodes on the secondary site and all Puma nodes on the primary site, are the
same.
If system clocks are synced, then the JWT token may be expiring while Git fetch is performing calculations between its
two separate HTTP requests. See [issue 464101](https://gitlab.com/gitlab-org/gitlab/-/issues/464101), which existed in
all GitLab versions until it was fixed in GitLab 17.1.0, 17.0.5, and 16.11.7.
To validate if you are experiencing this issue:
1. Monkey patch the code in a [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to increase the validity period of the token from 1 minute to 10 minutes. Run
this in Rails console on the secondary site:
```ruby
module Gitlab; module Geo; class BaseRequest
private
def geo_auth_token(message)
signed_data = Gitlab::Geo::SignedData.new(geo_node: requesting_node, validity_period: 10.minutes).sign_and_encode_data(message)
"#{GITLAB_GEO_AUTH_TOKEN_TYPE} #{signed_data}"
end
end;end;end
```
1. In the same Rails console, resync an affected project:
```ruby
Project.find_by_full_path('<mygroup/mysubgroup/myproject>').replicator.resync
```
1. Look at the sync state:
```ruby
Project.find_by_full_path('<mygroup/mysubgroup/myproject>').replicator.registry
```
1. If `last_sync_failure` no longer includes the error `fatal: could not read Username`, then you are
affected by this issue. The state should now be `2`, which means that it's synced. If so, then you should upgrade to
a GitLab version with the fix. You may also wish to upvote or comment on
[issue 466681](https://gitlab.com/gitlab-org/gitlab/-/issues/466681) which would have reduced the severity of this
issue.
To workaround the issue, you must hot-patch all Sidekiq nodes in the secondary site to extend the JWT expiration time:
1. Edit `/opt/gitlab/embedded/service/gitlab-rails/ee/lib/gitlab/geo/signed_data.rb`.
1. Find `Gitlab::Geo::SignedData.new(geo_node: requesting_node)` and add `, validity_period: 10.minutes` to it:
```diff
- Gitlab::Geo::SignedData.new(geo_node: requesting_node)
+ Gitlab::Geo::SignedData.new(geo_node: requesting_node, validity_period: 10.minutes)
```
1. Restart Sidekiq:
```shell
sudo gitlab-ctl restart sidekiq
```
1. Unless you upgrade to a version containing the fix, you would have to repeat this workaround after every GitLab upgrade.
### Error: `Error syncing repository: 13:creating repository: cloning repository: exit status 128`
You might see this error for projects that do not sync successfully.
Exit code 128 during repository creation means Git encountered a fatal error while cloning. This could be due to repository corruption, network issues, authentication problems, resource limits or because the project does not have an associated Git repository. More details about the specific cause for such failures can be found in the Gitaly logs.
When unsure where to start, run an integrity check on the source repository on the Primary site by [executing the `git fsck` command manually on the command line](../../../../administration/repository_checks.md#run-a-check-using-the-command-line).
### Error: `fetch remote: signal: terminated: context deadline exceeded` at exactly 3 hours
If Git fetch fails at exactly three hours while syncing a Git repository:
1. Edit `/etc/gitlab/gitlab.rb` to increase the Git timeout from the default of 10800 seconds:
```ruby
# Git timeout in seconds
gitlab_rails['gitlab_shell_git_timeout'] = 21600
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Error `Failed to open TCP connection to localhost:5000` on secondary when configuring registry replication
You may face the following error when configuring container registry replication on the secondary site:
```plaintext
Failed to open TCP connection to localhost:5000 (Connection refused - connect(2) for \"localhost\" port 5000)"
```
It happens if the container registry is not enabled on the secondary site. To fix it, check that the container registry
is [enabled on the secondary site](../../../packages/container_registry.md#enable-the-container-registry). If the [Let's Encrypt integration is disabled](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually), container registry is disabled as well, and you must [configure it manually](../../../packages/container_registry.md#configure-container-registry-under-its-own-domain).
### Message: `Synchronization failed - Error syncing repository`
{{< alert type="warning" >}}
If large repositories are affected by this problem,
their resync may take a long time and cause significant load on your Geo sites,
storage and network systems.
{{< /alert >}}
The following error message indicates a consistency check error when syncing the repository:
```plaintext
Synchronization failed - Error syncing repository [..] fatal: fsck error in packed object
```
Several issues can trigger this error. For example, problems with email addresses:
```plaintext
Error syncing repository: 13:fetch remote: "error: object <SHA>: badEmail: invalid author/committer line - bad email
fatal: fsck error in packed object
fatal: fetch-pack: invalid index-pack output
```
Another issue that can trigger this error is `object <SHA>: hasDotgit: contains '.git'`. Check the specific errors because you might have more than one problem across all
your repositories.
A second synchronization error can also be caused by repository check issues:
```plaintext
Error syncing repository: 13:Received RST_STREAM with error code 2.
```
These errors can be observed by [immediately syncing all failed repositories](#sync-all-resources-of-one-component-that-failed-to-sync).
Removing the malformed objects causing consistency errors involves rewriting the repository history, which is usually not an option.
To ignore these consistency checks, reconfigure Gitaly **on the secondary Geo sites** to ignore these `git fsck` issues.
The following configuration example:
- [Uses the new configuration structure](../../../../update/versions/gitlab_16_changes.md#gitaly-configuration-structure-change) required from GitLab 16.0.
- Ignores five common check failures.
[The Gitaly documentation has more details](../../../gitaly/consistency_checks.md)
about other Git check failures and earlier versions of GitLab.
```ruby
gitaly['configuration'] = {
git: {
config: [
{ key: "fsck.duplicateEntries", value: "ignore" },
{ key: "fsck.badFilemode", value: "ignore" },
{ key: "fsck.missingEmail", value: "ignore" },
{ key: "fsck.badEmail", value: "ignore" },
{ key: "fsck.hasDotgit", value: "ignore" },
{ key: "fetch.fsck.duplicateEntries", value: "ignore" },
{ key: "fetch.fsck.badFilemode", value: "ignore" },
{ key: "fetch.fsck.missingEmail", value: "ignore" },
{ key: "fetch.fsck.badEmail", value: "ignore" },
{ key: "fetch.fsck.hasDotgit", value: "ignore" },
{ key: "receive.fsck.duplicateEntries", value: "ignore" },
{ key: "receive.fsck.badFilemode", value: "ignore" },
{ key: "receive.fsck.missingEmail", value: "ignore" },
{ key: "receive.fsck.badEmail", value: "ignore" },
{ key: "receive.fsck.hasDotgit", value: "ignore" },
],
},
}
```
A comprehensive list of `fsck` errors can be found in the [Git documentation](https://git-scm.com/docs/git-fsck#_fsck_messages).
GitLab 16.1 and later [include an enhancement](https://gitlab.com/gitlab-org/gitaly/-/merge_requests/5879) that might resolve some of these issues.
[Gitaly issue 5625](https://gitlab.com/gitlab-org/gitaly/-/issues/5625) proposes to ensure that Geo replicates repositories even if the source repository contains
problematic commits.
### Related error `does not appear to be a git repository`
You can also get the error message `Synchronization failed - Error syncing repository` along with the following log messages.
This error indicates that the expected Geo remote is not present in the `.git/config` file
of a repository on the secondary Geo site's file system:
```json
{
"created": "@1603481145.084348757",
"description": "Error received from peer unix:/var/opt/gitlab/gitaly/gitaly.socket",
…
"grpc_message": "exit status 128",
"grpc_status": 13
}
{ …
"grpc.request.fullMethod": "/gitaly.RemoteService/FindRemoteRootRef",
"grpc.request.glProjectPath": "<namespace>/<project>",
…
"level": "error",
"msg": "fatal: 'geo' does not appear to be a git repository
fatal: Could not read from remote repository. …",
}
```
To solve this:
1. Sign in on the web interface for the secondary Geo site.
1. Back up [the `.git` folder](../../../repository_storage_paths.md#translate-hashed-storage-paths).
1. Optional. [Spot-check](../../../logs/log_parsing.md#find-all-projects-affected-by-a-fatal-git-problem)
a few of those IDs whether they indeed correspond
to a project with known Geo replication failures.
Use `fatal: 'geo'` as the `grep` term and the following API call:
```shell
curl --request GET --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/<first_failed_geo_sync_ID>"
```
1. Enter the [Rails console](../../../operations/rails_console.md) and run:
```ruby
failed_project_registries = Geo::ProjectRepositoryRegistry.failed
if failed_project_registries.any?
puts "Found #{failed_project_registries.count} failed project repository registry entries:"
failed_project_registries.each do |registry|
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Last Sync Failure: '#{registry.last_sync_failure}'"
end
else
puts "No failed project repository registry entries found."
end
```
1. Run the following commands to execute a new sync for each project:
```ruby
failed_project_registries.each do |registry|
registry.replicator.sync
puts "Sync initiated for registry ID: #{registry.id}, Project ID: #{registry.project_id}"
end
```
## Failures during backfill
During a [backfill](../../_index.md#backfill), failures are scheduled to be retried at the end
of the backfill queue, therefore these failures only clear up **after** the backfill completes.
## Message: `unexpected disconnect while reading sideband packet`
Unstable networking conditions can cause Gitaly to fail when trying to fetch large repository
data from the primary site. Those conditions can result in this error:
```plaintext
curl 18 transfer closed with outstanding read data remaining & fetch-pack:
unexpected disconnect while reading sideband packet
```
This error is more likely to happen if a repository has to be
replicated from scratch between sites.
Geo retries several times, but if the transmission is consistently interrupted
by network hiccups, an alternative method such as `rsync` can be used to circumvent `git` and
create the initial copy of any repository that fails to be replicated by Geo.
We recommend transferring each failing repository individually and checking for consistency
after each transfer. Follow the [single target `rsync` instructions](../../../operations/moving_repositories.md#single-rsync-to-another-server)
to transfer each affected repository from the primary to the secondary site.
## Find repository check failures in a Geo secondary site
{{< alert type="note" >}}
All repositories data types have been migrated to the Geo Self-Service Framework in GitLab 16.3. There is an [issue to implement this functionality back in the Geo Self-Service Framework](https://gitlab.com/gitlab-org/gitlab/-/issues/426659).
{{< /alert >}}
For GitLab 16.2 and earlier:
When [enabled for all projects](../../../repository_checks.md#enable-repository-checks-for-all-projects), [Repository checks](../../../repository_checks.md) are also performed on Geo secondary sites. The metadata is stored in the Geo tracking database.
Repository check failures on a Geo secondary site do not necessarily imply a replication problem. Here is a general approach to resolve these failures.
1. Find affected repositories as mentioned below, as well as their [logged errors](../../../repository_checks.md#what-to-do-if-a-check-failed).
1. Try to diagnose specific `git fsck` errors. The range of possible errors is wide, try putting them into search engines.
1. Test typical functions of the affected repositories. Pull from the secondary, view the files.
1. Check if the primary site's copy of the repository has an identical `git fsck` error. If you are planning a failover, then consider prioritizing that the secondary site has the same information that the primary site has. Ensure you have a backup of the primary, and follow [planned failover guidelines](../../disaster_recovery/planned_failover.md).
1. Push to the primary and check if the change gets replicated to the secondary site.
1. If replication is not automatically working, try to manually sync the repository.
[Start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
to enact the following, basic troubleshooting steps.
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions. Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
### Get the number of repositories that failed the repository check
```ruby
Geo::ProjectRegistry.where(last_repository_check_failed: true).count
```
### Find the repositories that failed the repository check
```ruby
Geo::ProjectRegistry.where(last_repository_check_failed: true)
```
## Resetting Geo **secondary** site replication
If you get a **secondary** site in a broken state and want to reset the replication state,
to start again from scratch, there are a few steps that can help you:
1. Stop Sidekiq and the Geo Log Cursor.
It's possible to make Sidekiq stop gracefully, but making it stop getting new jobs and
wait until the current jobs to finish processing.
You need to send a **SIGTSTP** kill signal for the first phase and them a **SIGTERM**
when all jobs have finished. Otherwise just use the `gitlab-ctl stop` commands.
```shell
gitlab-ctl status sidekiq
# run: sidekiq: (pid 10180) <- this is the PID you will use
kill -TSTP 10180 # change to the correct PID
gitlab-ctl stop sidekiq
gitlab-ctl stop geo-logcursor
```
You can watch the [Sidekiq logs](../../../logs/_index.md#sidekiq-logs) to know when Sidekiq jobs processing has finished:
```shell
gitlab-ctl tail sidekiq
```
1. Clear Gitaly and Gitaly Cluster (Praefect) data.
{{< tabs >}}
{{< tab title="Gitaly" >}}
```shell
mv /var/opt/gitlab/git-data/repositories /var/opt/gitlab/git-data/repositories.old
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Gitaly Cluster (Praefect)" >}}
1. Optional. Disable the Praefect internal load balancer.
1. Stop Praefect on each Praefect server:
```shell
sudo gitlab-ctl stop praefect
```
1. Reset the Praefect database:
```shell
sudo /opt/gitlab/embedded/bin/psql -U praefect -d template1 -h localhost -c "DROP DATABASE praefect_production WITH (FORCE);"
sudo /opt/gitlab/embedded/bin/psql -U praefect -d template1 -h localhost -c "CREATE DATABASE praefect_production WITH OWNER=praefect ENCODING=UTF8;"
```
1. Rename/delete repository data from each Gitaly node:
```shell
sudo mv /var/opt/gitlab/git-data/repositories /var/opt/gitlab/git-data/repositories.old
sudo gitlab-ctl reconfigure
```
1. On your Praefect deploy node run reconfigure to set up the database:
```shell
sudo gitlab-ctl reconfigure
```
1. Start Praefect on each Praefect server:
```shell
sudo gitlab-ctl start praefect
```
1. Optional. If you disabled it, reactivate the Praefect internal load balancer.
{{< /tab >}}
{{< /tabs >}}
{{< alert type="note" >}}
You may want to remove the `/var/opt/gitlab/git-data/repositories.old` in the future
as soon as you confirmed that you don't need it anymore, to save disk space.
{{< /alert >}}
1. Optional. Rename other data folders and create new ones.
{{< alert type="warning" >}}
You may still have files on the **secondary** site that have been removed from the **primary** site, but this
removal has not been reflected. If you skip this step, these files are not removed from the Geo **secondary** site.
{{< /alert >}}
Any uploaded content (like file attachments, avatars, or LFS objects) is stored in a
subfolder in one of these paths:
- `/var/opt/gitlab/gitlab-rails/shared`
- `/var/opt/gitlab/gitlab-rails/uploads`
To rename all of them:
```shell
gitlab-ctl stop
mv /var/opt/gitlab/gitlab-rails/shared /var/opt/gitlab/gitlab-rails/shared.old
mkdir -p /var/opt/gitlab/gitlab-rails/shared
mv /var/opt/gitlab/gitlab-rails/uploads /var/opt/gitlab/gitlab-rails/uploads.old
mkdir -p /var/opt/gitlab/gitlab-rails/uploads
gitlab-ctl start postgresql
gitlab-ctl start geo-postgresql
```
Reconfigure to recreate the folders and make sure permissions and ownership
are correct:
```shell
gitlab-ctl reconfigure
```
1. Reset the Tracking Database.
{{< alert type="warning" >}}
If you skipped the optional step 3, be sure both `geo-postgresql` and `postgresql` services are running.
{{< /alert >}}
```shell
gitlab-rake db:drop:geo DISABLE_DATABASE_ENVIRONMENT_CHECK=1 # on a secondary app node
gitlab-ctl reconfigure # on the tracking database node
gitlab-rake db:migrate:geo # on a secondary app node
```
1. Restart previously stopped services.
```shell
gitlab-ctl start
```
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting Geo synchronization and verification errors
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you notice replication or verification failures in `Admin > Geo > Sites` or the [Sync status Rake task](common.md#sync-status-rake-task), you can try to resolve the failures with the following general steps:
1. Geo automatically retries failures. If the failures are new and few in number, or if you suspect the root cause is already resolved, then you can wait to see if the failures go away.
1. If failures were present for a long time, then many retries have already occurred, and the interval between automatic retries has increased to up to 4 hours depending on the type of failure. If you suspect the root cause is already resolved, you can [manually retry replication or verification](#manually-retry-replication-or-verification) to avoid the wait.
1. If the failures persist, use the following sections to try to resolve them.
## Manually retry replication or verification
In [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) in a
secondary Geo site, you can:
- [Manually resync and reverify individual components](#resync-and-reverify-individual-components)
- [Manually resync and reverify multiple components](#resync-and-reverify-multiple-components)
### Resync and reverify individual components
On the secondary site, visit **Admin** > **Geo** > **Replication** to force a resync or reverify of individual items.
However, if this doesn't work, you can perform the same action using the Rails console. The
following sections describe how to use internal application commands in the
[Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to cause
replication or verification for individual records synchronously or asynchronously.
#### Obtaining a Replicator instance
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
Before you can perform any sync or verify operations, you need to obtain a Replicator instance.
First, [start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
in a **primary** or **secondary** site, depending on what you want to do.
**Primary** site:
- You can checksum a resource
**Secondary** site:
- You can sync a resource
- You can checksum a resource and verify that checksum against the primary site's checksum
Next, run one of the following snippets to get a Replicator instance.
##### Given a model record's ID
- Replace `123` with the actual ID.
- Replace `Packages::PackageFile` with any of the
[Geo data type Model classes](#geo-data-type-model-classes).
```ruby
model_record = Packages::PackageFile.find_by(id: 123)
replicator = model_record.replicator
```
##### Given a registry record's ID
- Replace `432` with the actual ID. A Registry record may or may not have the same ID
value as the Model record that it tracks.
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
In a secondary Geo site:
```ruby
registry_record = Geo::PackageFileRegistry.find_by(id: 432)
replicator = registry_record.replicator
```
##### Given an error message in a Registry record's `last_sync_failure`
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
- Replace `error message here` with the actual error message.
```ruby
registry = Geo::PackageFileRegistry.find_by("last_sync_failure LIKE '%error message here%'")
replicator = registry.replicator
```
##### Given an error message in a Registry record's `verification_failure`
- Replace `Geo::PackageFileRegistry` with any of the [Geo Registry classes](#geo-registry-classes).
- Replace `error message here` with the actual error message.
```ruby
registry = Geo::PackageFileRegistry.find_by("verification_failure LIKE '%error message here%'")
replicator = registry.replicator
```
#### Performing operations with a Replicator instance
After you have a Replicator instance stored in a `replicator` variable, you can perform many
operations:
##### Sync in the console
This snippet only works in a **secondary** site.
This executes the sync code synchronously in the console, so you can observe how long it takes to
sync a resource, or view a full error backtrace.
```ruby
replicator.sync
```
Optionally, make the log level of the console more verbose than the configured log level, and then
perform a sync:
```ruby
Rails.logger.level = :debug
```
##### Checksum or verify in the console
This snippet works in any **primary** or **secondary** site.
In a **primary** site, it checksums the resource and stores the result in the main GitLab
database. In a **secondary** site, it checksums the resource, compares it against the checksum in
the main GitLab database (generated by the **primary** site), and stores the result in the Geo
Tracking database.
This executes the checksum and verification code synchronously in the console, so you can observe
how long it takes, or view a full error backtrace.
```ruby
replicator.verify
```
##### Sync in a Sidekiq job
This snippet only works in a **secondary** site.
It enqueues a job for Sidekiq to perform a [sync](#sync-in-the-console) of the resource.
```ruby
replicator.enqueue_sync
```
##### Verify in a Sidekiq job
This snippet works in any **primary** or **secondary** site.
It enqueues a job for Sidekiq to perform a
[checksum or verify](#checksum-or-verify-in-the-console) of the resource.
```ruby
replicator.verify_async
```
##### Get a model record
This snippet works in any **primary** or **secondary** site.
```ruby
replicator.model_record
```
##### Get a registry record
This snippet only works in a **secondary** site because registry tables are stored in the Geo
Tracking DB.
```ruby
replicator.registry
```
#### Geo data type Model classes
A Geo data type is a specific class of data that is required by one or more GitLab features to store
relevant data and is replicated by Geo to secondary sites.
- **Blob types**:
- `Ci::JobArtifact`
- `Ci::PipelineArtifact`
- `Ci::SecureFile`
- `LfsObject`
- `MergeRequestDiff`
- `Packages::PackageFile`
- `PagesDeployment`
- `Terraform::StateVersion`
- `Upload`
- `DependencyProxy::Manifest`
- `DependencyProxy::Blob`
- **Git Repository types**:
- `DesignManagement::Repository`
- `ProjectRepository`
- `ProjectWikiRepository`
- `SnippetRepository`
- `GroupWikiRepository`
- **Other types**:
- `ContainerRepository`
The main kinds of classes are Registry, Model, and Replicator. If you have an instance of one of
these classes, you can get the others. The Registry and Model mostly manage PostgreSQL DB state. The
Replicator knows how to replicate or verify the non-PostgreSQL data (file/Git repository/Container
repository).
#### Geo Registry classes
In the context of GitLab Geo, a **registry record** refers to registry tables in
the Geo tracking database. Each record tracks a single replicable in the main
GitLab database, such as an LFS file, or a project Git repository. The Rails
models that correspond to Geo registry tables that can be queried are:
- **Blob types**:
- `Geo::CiSecureFileRegistry`
- `Geo::DependencyProxyBlobRegistry`
- `Geo::DependencyProxyManifestRegistry`
- `Geo::JobArtifactRegistry`
- `Geo::LfsObjectRegistry`
- `Geo::MergeRequestDiffRegistry`
- `Geo::PackageFileRegistry`
- `Geo::PagesDeploymentRegistry`
- `Geo::PipelineArtifactRegistry`
- `Geo::ProjectWikiRepositoryRegistry`
- `Geo::SnippetRepositoryRegistry`
- `Geo::TerraformStateVersionRegistry`
- `Geo::UploadRegistry`
- **Git Repository types**:
- `Geo::DesignManagementRepositoryRegistry`
- `Geo::ProjectRepositoryRegistry`
- `Geo::ProjectWikiRepositoryRegistry`
- `Geo::SnippetRepositoryRegistry`
- `Geo::GroupWikiRepositoryRegistry`
- **Other types**:
- `Geo::ContainerRepositoryRegistry`
### Resync and reverify multiple components
{{< history >}}
- Bulk resync and reverify [added](https://gitlab.com/gitlab-org/gitlab/-/issues/364729) in GitLab 16.5.
{{< /history >}}
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
The following sections describe how to use internal application commands in the
[Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to cause bulk
replication or verification.
#### Resync all resources of one component
You can schedule a full resync of all resources of one component from the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Under **Replication details**, select the desired component.
1. Select **Resync all**.
Alternatively,
[start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
**on the secondary Geo site** to gather more information, or execute these operations manually using
the snippets below.
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions.
Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
##### Sync all resources of one component that failed to sync
The following script:
- Loops over all failed repositories.
- Displays the Geo sync and verification metadata, including the reasons for the last failure.
- Attempts to resync the repository.
- Reports back if a failure occurs, and why.
- Might take some time to complete. Each repository check must complete
before reporting back the result. If your session times out, take measures
to allow the process to continue running such as starting a `screen` session,
or running it using [Rails runner](../../../operations/rails_console.md#using-the-rails-runner)
and `nohup`.
```ruby
Geo::ProjectRepositoryRegistry.failed.find_each do |registry|
begin
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Last Sync Failure: '#{registry.last_sync_failure}'"
registry.replicator.sync
puts "Sync initiated for registry ID: #{registry.id}"
rescue => e
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Failed: '#{e}'", e.backtrace.join("\n")
end
end; nil
```
#### Reverify one component on all sites
If the **primary** site's checksums are in question, then you need to make the **primary** site recalculate checksums. A "full re-verification" is then achieved, because after each checksum is recalculated on a **primary** site, events are generated which propagate to all **secondary** sites, causing them to recalculate their checksums and compare values. Any mismatch marks the registry as `sync failed`, which causes sync retries to be scheduled.
The UI does not provide a button to do a full re-verification. You can simulate this by setting your **primary** site's `Re-verification interval` to 1 (day) in **Admin** > **Geo** > **Nodes** > **Edit**. The **primary** site will then recalculate the checksum of any resource that has been checksummed more than 1 day ago.
Optionally, you can do this manually:
1. SSH into a GitLab Rails node in the **primary** site.
1. Open the [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session).
1. Replacing `Upload` with any of the [Geo data type Model classes](#geo-data-type-model-classes),
mark all resources as `pending verification`:
```ruby
Upload.verification_state_table_class.each_batch do |relation|
relation.update_all(verification_state: 0)
end
```
##### Reverify all resources that failed to checksum on the primary site
The system automatically reverifies all resources that failed to checksum on the primary site, but
it uses a progressive backoff scheme to avoid an excessive volume of failures.
Optionally, for example if you've completed an attempted intervention, you can manually trigger
reverification sooner:
1. SSH into a GitLab Rails node in the **primary** site.
1. Open the [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session).
1. Replacing `Upload` with any of the [Geo data type Model classes](#geo-data-type-model-classes),
mark all resources as `pending verification`:
```ruby
Upload.verification_state_table_class.where(verification_state: 3).each_batch do |relation|
relation.update_all(verification_state: 0)
end
```
#### Reverify one component on one secondary site
If you believe the **primary** site checksums are correct, you can schedule a reverification of one
component on one **secondary** site from the UI:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Geo** > **Sites**.
1. Under **Replication details**, select the desired component.
1. Select **Reverify all**.
## Errors
### Message: `The file is missing on the Geo primary site`
The sync failure `The file is missing on the Geo primary site` is common when
setting up a secondary Geo site for the first time, which is caused by data
inconsistencies on the primary site.
Data inconsistencies and missing files can occur due to system or human errors
when operating GitLab. For example, an instance administrator manually deletes
several artifacts on the local file system. Such changes are not properly
propagated to the database and result in inconsistencies. These inconsistencies
remain and can cause frictions. Geo secondaries might continue to try
replicating those files as they are still referenced in the database but no
longer exist.
{{< alert type="note" >}}
In case of a recent migration from local to object storage, see the dedicated
[object storage troubleshooting section](../../../object_storage.md#inconsistencies-after-migrating-to-object-storage).
{{< /alert >}}
#### Identify inconsistencies
When missing files or inconsistencies are present, you can encounter entries in `geo.log` such as the following. Take note of the field `"primary_missing_file" : true`:
```json
{
"bytes_downloaded" : 0,
"class" : "Geo::BlobDownloadService",
"correlation_id" : "01JT69C1ECRBEMZHA60E5SAX8E",
"download_success" : false,
"download_time_s" : 0.196,
"gitlab_host" : "gitlab.example.com",
"mark_as_synced" : false,
"message" : "Blob download",
"model_record_id" : 55,
"primary_missing_file" : true,
"reason" : "Not Found",
"replicable_name" : "upload",
"severity" : "WARN",
"status_code" : 404,
"time" : "2025-05-01T16:02:44.836Z",
"url" : "http://gitlab.example.com/api/v4/geo/retrieve/upload/55"
}
```
The same errors are also reflected in the UI under **Admin** > **Geo** > **Sites** when reviewing the synchronization status of specific replicables. In this scenario, a specific upload is missing:


#### Clean up inconsistencies
{{< alert type="warning" >}}
Ensure you have a recent and working backup at hand before issuing any deletion commands.
{{< /alert >}}
To remove those errors, first identify which particular resources are affected. Then, run the appropriate `destroy` commands to ensure the deletion is propagated across all Geo sites and their databases. Based on the previous scenario, an **upload** is causing those errors which is used as an example below.
1. Map the identified inconsistencies to their respective [Geo Model class](#geo-data-type-model-classes) name. The class name is needed in the following steps. In this scenario, for uploads it corresponds to `Upload`.
1. Start a [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) on the **Geo primary site**.
1. Query all resources where verification failed due to missing files based on the *Geo Model class* of the previous step. Adjust or remove the `limit(20)` to display more results. Observe how the listed resources should match the failed ones shown in the UI:
```ruby
Upload.verification_failed.where("verification_failure like '%File is not checksummable%'").limit(20)
=> #<Upload:0x00007b362bb6c4e8
id: 55,
size: 13346,
path: "503d99159e2aa8a3ac23602058cfdf58/openbao.png",
checksum: "db29d233de49b25d2085dcd8610bac787070e721baa8dcedba528a292b6e816b",
model_id: 1,
model_type: "Project",
uploader: "FileUploader",
created_at: Thu, 01 May 2025 15:54:10.549178000 UTC +00:00,
store: 1,
mount_point: nil,
secret: "[FILTERED]",
version: 2,
uploaded_by_user_id: 1,
organization_id: nil,
namespace_id: nil,
project_id: 1,
verification_checksum: nil>
```
1. Optionally, use the `id` of the affected resources to determine if they are still needed:
```ruby
Upload.find(55)
=> #<Upload:0x00007b362bb6c4e8
id: 55,
size: 13346,
path: "503d99159e2aa8a3ac23602058cfdf58/openbao.png",
checksum: "db29d233de49b25d2085dcd8610bac787070e721baa8dcedba528a292b6e816b",
model_id: 1,
model_type: "Project",
uploader: "FileUploader",
created_at: Thu, 01 May 2025 15:54:10.549178000 UTC +00:00,
store: 1,
mount_point: nil,
secret: "[FILTERED]",
version: 2,
uploaded_by_user_id: 1,
organization_id: nil,
namespace_id: nil,
project_id: 1,
verification_checksum: nil>
```
- If you determine that the affected resources need to be recovered, then you can explore the following options (non-exhaustive) to recover them:
- Check if the secondary site has the object and manually copy them to the primary.
- Look through old backups and manually copy the object back into the primary site.
- Spot check some to try to determine that it's probably fine to destroy the records, for example, if they are all very old artifacts, then maybe they are not critical data.
1. Use the `id` of the identified resources to properly delete them individually or in bulk by using `destroy`. Ensure to use the appropriate *Geo Model class* name.
- Delete individual resources:
```ruby
Upload.find(55).destroy
```
- Delete all affected resources:
```ruby
def destroy_uploads_not_checksummable
uploads = Upload.verification_failed.where("verification_failure like '%File is not checksummable%'");1
puts "Found #{uploads.count} resources that failed verification with 'File is not checksummable'."
puts "Enter 'y' to continue: "
prompt = STDIN.gets.chomp
if prompt != 'y'
puts "Exiting without action..."
return
end
puts "Destroying all..."
uploads.destroy_all
end
destroy_uploads_not_checksummable
```
Repeat the steps for all affected resources and Geo data types.
### Message: `"Error during verification","error":"File is not checksummable"`
The error `"Error during verification","error":"File is not checksummable"` is caused by inconsistencies on the primary site. Follow the instructions provided in [The file is missing on the Geo primary site](#message-the-file-is-missing-on-the-geo-primary-site).
### Failed verification of Uploads on the primary Geo site
If verification of some uploads is failing on the primary Geo site with `verification_checksum = nil` and with `verification_failure` containing ``Error during verification: undefined method `underscore' for NilClass:Class`` or ``The model which owns this Upload is missing.``, this is due to orphaned Uploads. The parent record owning the Upload (the upload's "model") has somehow been deleted, but the Upload record still exists. This is usually due to a bug in the application, introduced by implementing bulk delete of the "model" while forgetting to bulk delete its associated Upload records. These verification failures are therefore not failures to verify, rather, the errors are a result of bad data in Postgres.
You can find these errors in the `geo.log` file on the primary Geo site.
To confirm that model records are missing, you can run a Rake task on the primary Geo site:
```shell
sudo gitlab-rake gitlab:uploads:check
```
You can delete these Upload records on the primary Geo site to get rid of these failures by running the following script from the [Rails console](../../../operations/rails_console.md):
```ruby
def delete_orphaned_uploads(dry_run: true)
if dry_run
p "This is a dry run. Upload rows will only be printed."
else
p "This is NOT A DRY RUN! Upload rows will be deleted from the DB!"
end
subquery = Geo::UploadState.where("(verification_failure LIKE 'Error during verification: The model which owns this Upload is missing.%' OR verification_failure = 'Error during verification: undefined method `underscore'' for NilClass:Class') AND verification_checksum IS NULL")
uploads = Upload.where(upload_state: subquery)
p "Found #{uploads.count} uploads with a model that does not exist"
uploads_deleted = 0
begin
uploads.each do |upload|
if dry_run
p upload
else
uploads_deleted=uploads_deleted + 1
p upload.destroy!
end
rescue => e
puts "checking upload #{upload.id} failed with #{e.message}"
end
end
p "#{uploads_deleted} remote objects were destroyed." unless dry_run
end
```
The previous script defines a method named `delete_orphaned_uploads` which you can call like this to do a dry run:
```ruby
delete_orphaned_uploads(dry_run: true)
```
And to actually delete the orphaned upload rows:
```ruby
delete_orphaned_uploads(dry_run: false)
```
### Error: `Error syncing repository: 13:fatal: could not read Username`
The `last_sync_failure` error
`Error syncing repository: 13:fatal: could not read Username for 'https://gitlab.example.com': terminal prompts disabled`
indicates that JWT authentication is failing during a Geo clone or fetch request.
First, check that system clocks are synced. Run the [Health check Rake task](common.md#health-check-rake-task), or
manually check that `date`, on all Sidekiq nodes on the secondary site and all Puma nodes on the primary site, are the
same.
If system clocks are synced, then the JWT token may be expiring while Git fetch is performing calculations between its
two separate HTTP requests. See [issue 464101](https://gitlab.com/gitlab-org/gitlab/-/issues/464101), which existed in
all GitLab versions until it was fixed in GitLab 17.1.0, 17.0.5, and 16.11.7.
To validate if you are experiencing this issue:
1. Monkey patch the code in a [Rails console](../../../operations/rails_console.md#starting-a-rails-console-session) to increase the validity period of the token from 1 minute to 10 minutes. Run
this in Rails console on the secondary site:
```ruby
module Gitlab; module Geo; class BaseRequest
private
def geo_auth_token(message)
signed_data = Gitlab::Geo::SignedData.new(geo_node: requesting_node, validity_period: 10.minutes).sign_and_encode_data(message)
"#{GITLAB_GEO_AUTH_TOKEN_TYPE} #{signed_data}"
end
end;end;end
```
1. In the same Rails console, resync an affected project:
```ruby
Project.find_by_full_path('<mygroup/mysubgroup/myproject>').replicator.resync
```
1. Look at the sync state:
```ruby
Project.find_by_full_path('<mygroup/mysubgroup/myproject>').replicator.registry
```
1. If `last_sync_failure` no longer includes the error `fatal: could not read Username`, then you are
affected by this issue. The state should now be `2`, which means that it's synced. If so, then you should upgrade to
a GitLab version with the fix. You may also wish to upvote or comment on
[issue 466681](https://gitlab.com/gitlab-org/gitlab/-/issues/466681) which would have reduced the severity of this
issue.
To workaround the issue, you must hot-patch all Sidekiq nodes in the secondary site to extend the JWT expiration time:
1. Edit `/opt/gitlab/embedded/service/gitlab-rails/ee/lib/gitlab/geo/signed_data.rb`.
1. Find `Gitlab::Geo::SignedData.new(geo_node: requesting_node)` and add `, validity_period: 10.minutes` to it:
```diff
- Gitlab::Geo::SignedData.new(geo_node: requesting_node)
+ Gitlab::Geo::SignedData.new(geo_node: requesting_node, validity_period: 10.minutes)
```
1. Restart Sidekiq:
```shell
sudo gitlab-ctl restart sidekiq
```
1. Unless you upgrade to a version containing the fix, you would have to repeat this workaround after every GitLab upgrade.
### Error: `Error syncing repository: 13:creating repository: cloning repository: exit status 128`
You might see this error for projects that do not sync successfully.
Exit code 128 during repository creation means Git encountered a fatal error while cloning. This could be due to repository corruption, network issues, authentication problems, resource limits or because the project does not have an associated Git repository. More details about the specific cause for such failures can be found in the Gitaly logs.
When unsure where to start, run an integrity check on the source repository on the Primary site by [executing the `git fsck` command manually on the command line](../../../../administration/repository_checks.md#run-a-check-using-the-command-line).
### Error: `fetch remote: signal: terminated: context deadline exceeded` at exactly 3 hours
If Git fetch fails at exactly three hours while syncing a Git repository:
1. Edit `/etc/gitlab/gitlab.rb` to increase the Git timeout from the default of 10800 seconds:
```ruby
# Git timeout in seconds
gitlab_rails['gitlab_shell_git_timeout'] = 21600
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Error `Failed to open TCP connection to localhost:5000` on secondary when configuring registry replication
You may face the following error when configuring container registry replication on the secondary site:
```plaintext
Failed to open TCP connection to localhost:5000 (Connection refused - connect(2) for \"localhost\" port 5000)"
```
It happens if the container registry is not enabled on the secondary site. To fix it, check that the container registry
is [enabled on the secondary site](../../../packages/container_registry.md#enable-the-container-registry). If the [Let's Encrypt integration is disabled](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually), container registry is disabled as well, and you must [configure it manually](../../../packages/container_registry.md#configure-container-registry-under-its-own-domain).
### Message: `Synchronization failed - Error syncing repository`
{{< alert type="warning" >}}
If large repositories are affected by this problem,
their resync may take a long time and cause significant load on your Geo sites,
storage and network systems.
{{< /alert >}}
The following error message indicates a consistency check error when syncing the repository:
```plaintext
Synchronization failed - Error syncing repository [..] fatal: fsck error in packed object
```
Several issues can trigger this error. For example, problems with email addresses:
```plaintext
Error syncing repository: 13:fetch remote: "error: object <SHA>: badEmail: invalid author/committer line - bad email
fatal: fsck error in packed object
fatal: fetch-pack: invalid index-pack output
```
Another issue that can trigger this error is `object <SHA>: hasDotgit: contains '.git'`. Check the specific errors because you might have more than one problem across all
your repositories.
A second synchronization error can also be caused by repository check issues:
```plaintext
Error syncing repository: 13:Received RST_STREAM with error code 2.
```
These errors can be observed by [immediately syncing all failed repositories](#sync-all-resources-of-one-component-that-failed-to-sync).
Removing the malformed objects causing consistency errors involves rewriting the repository history, which is usually not an option.
To ignore these consistency checks, reconfigure Gitaly **on the secondary Geo sites** to ignore these `git fsck` issues.
The following configuration example:
- [Uses the new configuration structure](../../../../update/versions/gitlab_16_changes.md#gitaly-configuration-structure-change) required from GitLab 16.0.
- Ignores five common check failures.
[The Gitaly documentation has more details](../../../gitaly/consistency_checks.md)
about other Git check failures and earlier versions of GitLab.
```ruby
gitaly['configuration'] = {
git: {
config: [
{ key: "fsck.duplicateEntries", value: "ignore" },
{ key: "fsck.badFilemode", value: "ignore" },
{ key: "fsck.missingEmail", value: "ignore" },
{ key: "fsck.badEmail", value: "ignore" },
{ key: "fsck.hasDotgit", value: "ignore" },
{ key: "fetch.fsck.duplicateEntries", value: "ignore" },
{ key: "fetch.fsck.badFilemode", value: "ignore" },
{ key: "fetch.fsck.missingEmail", value: "ignore" },
{ key: "fetch.fsck.badEmail", value: "ignore" },
{ key: "fetch.fsck.hasDotgit", value: "ignore" },
{ key: "receive.fsck.duplicateEntries", value: "ignore" },
{ key: "receive.fsck.badFilemode", value: "ignore" },
{ key: "receive.fsck.missingEmail", value: "ignore" },
{ key: "receive.fsck.badEmail", value: "ignore" },
{ key: "receive.fsck.hasDotgit", value: "ignore" },
],
},
}
```
A comprehensive list of `fsck` errors can be found in the [Git documentation](https://git-scm.com/docs/git-fsck#_fsck_messages).
GitLab 16.1 and later [include an enhancement](https://gitlab.com/gitlab-org/gitaly/-/merge_requests/5879) that might resolve some of these issues.
[Gitaly issue 5625](https://gitlab.com/gitlab-org/gitaly/-/issues/5625) proposes to ensure that Geo replicates repositories even if the source repository contains
problematic commits.
### Related error `does not appear to be a git repository`
You can also get the error message `Synchronization failed - Error syncing repository` along with the following log messages.
This error indicates that the expected Geo remote is not present in the `.git/config` file
of a repository on the secondary Geo site's file system:
```json
{
"created": "@1603481145.084348757",
"description": "Error received from peer unix:/var/opt/gitlab/gitaly/gitaly.socket",
…
"grpc_message": "exit status 128",
"grpc_status": 13
}
{ …
"grpc.request.fullMethod": "/gitaly.RemoteService/FindRemoteRootRef",
"grpc.request.glProjectPath": "<namespace>/<project>",
…
"level": "error",
"msg": "fatal: 'geo' does not appear to be a git repository
fatal: Could not read from remote repository. …",
}
```
To solve this:
1. Sign in on the web interface for the secondary Geo site.
1. Back up [the `.git` folder](../../../repository_storage_paths.md#translate-hashed-storage-paths).
1. Optional. [Spot-check](../../../logs/log_parsing.md#find-all-projects-affected-by-a-fatal-git-problem)
a few of those IDs whether they indeed correspond
to a project with known Geo replication failures.
Use `fatal: 'geo'` as the `grep` term and the following API call:
```shell
curl --request GET --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/<first_failed_geo_sync_ID>"
```
1. Enter the [Rails console](../../../operations/rails_console.md) and run:
```ruby
failed_project_registries = Geo::ProjectRepositoryRegistry.failed
if failed_project_registries.any?
puts "Found #{failed_project_registries.count} failed project repository registry entries:"
failed_project_registries.each do |registry|
puts "ID: #{registry.id}, Project ID: #{registry.project_id}, Last Sync Failure: '#{registry.last_sync_failure}'"
end
else
puts "No failed project repository registry entries found."
end
```
1. Run the following commands to execute a new sync for each project:
```ruby
failed_project_registries.each do |registry|
registry.replicator.sync
puts "Sync initiated for registry ID: #{registry.id}, Project ID: #{registry.project_id}"
end
```
## Failures during backfill
During a [backfill](../../_index.md#backfill), failures are scheduled to be retried at the end
of the backfill queue, therefore these failures only clear up **after** the backfill completes.
## Message: `unexpected disconnect while reading sideband packet`
Unstable networking conditions can cause Gitaly to fail when trying to fetch large repository
data from the primary site. Those conditions can result in this error:
```plaintext
curl 18 transfer closed with outstanding read data remaining & fetch-pack:
unexpected disconnect while reading sideband packet
```
This error is more likely to happen if a repository has to be
replicated from scratch between sites.
Geo retries several times, but if the transmission is consistently interrupted
by network hiccups, an alternative method such as `rsync` can be used to circumvent `git` and
create the initial copy of any repository that fails to be replicated by Geo.
We recommend transferring each failing repository individually and checking for consistency
after each transfer. Follow the [single target `rsync` instructions](../../../operations/moving_repositories.md#single-rsync-to-another-server)
to transfer each affected repository from the primary to the secondary site.
## Find repository check failures in a Geo secondary site
{{< alert type="note" >}}
All repositories data types have been migrated to the Geo Self-Service Framework in GitLab 16.3. There is an [issue to implement this functionality back in the Geo Self-Service Framework](https://gitlab.com/gitlab-org/gitlab/-/issues/426659).
{{< /alert >}}
For GitLab 16.2 and earlier:
When [enabled for all projects](../../../repository_checks.md#enable-repository-checks-for-all-projects), [Repository checks](../../../repository_checks.md) are also performed on Geo secondary sites. The metadata is stored in the Geo tracking database.
Repository check failures on a Geo secondary site do not necessarily imply a replication problem. Here is a general approach to resolve these failures.
1. Find affected repositories as mentioned below, as well as their [logged errors](../../../repository_checks.md#what-to-do-if-a-check-failed).
1. Try to diagnose specific `git fsck` errors. The range of possible errors is wide, try putting them into search engines.
1. Test typical functions of the affected repositories. Pull from the secondary, view the files.
1. Check if the primary site's copy of the repository has an identical `git fsck` error. If you are planning a failover, then consider prioritizing that the secondary site has the same information that the primary site has. Ensure you have a backup of the primary, and follow [planned failover guidelines](../../disaster_recovery/planned_failover.md).
1. Push to the primary and check if the change gets replicated to the secondary site.
1. If replication is not automatically working, try to manually sync the repository.
[Start a Rails console session](../../../operations/rails_console.md#starting-a-rails-console-session)
to enact the following, basic troubleshooting steps.
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions. Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
### Get the number of repositories that failed the repository check
```ruby
Geo::ProjectRegistry.where(last_repository_check_failed: true).count
```
### Find the repositories that failed the repository check
```ruby
Geo::ProjectRegistry.where(last_repository_check_failed: true)
```
## Resetting Geo **secondary** site replication
If you get a **secondary** site in a broken state and want to reset the replication state,
to start again from scratch, there are a few steps that can help you:
1. Stop Sidekiq and the Geo Log Cursor.
It's possible to make Sidekiq stop gracefully, but making it stop getting new jobs and
wait until the current jobs to finish processing.
You need to send a **SIGTSTP** kill signal for the first phase and them a **SIGTERM**
when all jobs have finished. Otherwise just use the `gitlab-ctl stop` commands.
```shell
gitlab-ctl status sidekiq
# run: sidekiq: (pid 10180) <- this is the PID you will use
kill -TSTP 10180 # change to the correct PID
gitlab-ctl stop sidekiq
gitlab-ctl stop geo-logcursor
```
You can watch the [Sidekiq logs](../../../logs/_index.md#sidekiq-logs) to know when Sidekiq jobs processing has finished:
```shell
gitlab-ctl tail sidekiq
```
1. Clear Gitaly and Gitaly Cluster (Praefect) data.
{{< tabs >}}
{{< tab title="Gitaly" >}}
```shell
mv /var/opt/gitlab/git-data/repositories /var/opt/gitlab/git-data/repositories.old
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Gitaly Cluster (Praefect)" >}}
1. Optional. Disable the Praefect internal load balancer.
1. Stop Praefect on each Praefect server:
```shell
sudo gitlab-ctl stop praefect
```
1. Reset the Praefect database:
```shell
sudo /opt/gitlab/embedded/bin/psql -U praefect -d template1 -h localhost -c "DROP DATABASE praefect_production WITH (FORCE);"
sudo /opt/gitlab/embedded/bin/psql -U praefect -d template1 -h localhost -c "CREATE DATABASE praefect_production WITH OWNER=praefect ENCODING=UTF8;"
```
1. Rename/delete repository data from each Gitaly node:
```shell
sudo mv /var/opt/gitlab/git-data/repositories /var/opt/gitlab/git-data/repositories.old
sudo gitlab-ctl reconfigure
```
1. On your Praefect deploy node run reconfigure to set up the database:
```shell
sudo gitlab-ctl reconfigure
```
1. Start Praefect on each Praefect server:
```shell
sudo gitlab-ctl start praefect
```
1. Optional. If you disabled it, reactivate the Praefect internal load balancer.
{{< /tab >}}
{{< /tabs >}}
{{< alert type="note" >}}
You may want to remove the `/var/opt/gitlab/git-data/repositories.old` in the future
as soon as you confirmed that you don't need it anymore, to save disk space.
{{< /alert >}}
1. Optional. Rename other data folders and create new ones.
{{< alert type="warning" >}}
You may still have files on the **secondary** site that have been removed from the **primary** site, but this
removal has not been reflected. If you skip this step, these files are not removed from the Geo **secondary** site.
{{< /alert >}}
Any uploaded content (like file attachments, avatars, or LFS objects) is stored in a
subfolder in one of these paths:
- `/var/opt/gitlab/gitlab-rails/shared`
- `/var/opt/gitlab/gitlab-rails/uploads`
To rename all of them:
```shell
gitlab-ctl stop
mv /var/opt/gitlab/gitlab-rails/shared /var/opt/gitlab/gitlab-rails/shared.old
mkdir -p /var/opt/gitlab/gitlab-rails/shared
mv /var/opt/gitlab/gitlab-rails/uploads /var/opt/gitlab/gitlab-rails/uploads.old
mkdir -p /var/opt/gitlab/gitlab-rails/uploads
gitlab-ctl start postgresql
gitlab-ctl start geo-postgresql
```
Reconfigure to recreate the folders and make sure permissions and ownership
are correct:
```shell
gitlab-ctl reconfigure
```
1. Reset the Tracking Database.
{{< alert type="warning" >}}
If you skipped the optional step 3, be sure both `geo-postgresql` and `postgresql` services are running.
{{< /alert >}}
```shell
gitlab-rake db:drop:geo DISABLE_DATABASE_ENVIRONMENT_CHECK=1 # on a secondary app node
gitlab-ctl reconfigure # on the tracking database node
gitlab-rake db:migrate:geo # on a secondary app node
```
1. Restart previously stopped services.
```shell
gitlab-ctl start
```
|
https://docs.gitlab.com/administration/geo/replication/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/_index.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
_index.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting Geo
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When working with Geo, you might encounter the following issues:
- Basic troubleshooting and [common errors](common.md)
- [Client and HTTP response code errors](client_http.md)
- [PostgreSQL replication errors](postgresql_replication.md)
- [Synchronization and verification errors](synchronization_verification.md)
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting Geo
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When working with Geo, you might encounter the following issues:
- Basic troubleshooting and [common errors](common.md)
- [Client and HTTP response code errors](client_http.md)
- [PostgreSQL replication errors](postgresql_replication.md)
- [Synchronization and verification errors](synchronization_verification.md)
|
https://docs.gitlab.com/administration/geo/replication/postgresql_replication
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/replication/postgresql_replication.md
|
2025-08-13
|
doc/administration/geo/replication/troubleshooting
|
[
"doc",
"administration",
"geo",
"replication",
"troubleshooting"
] |
postgresql_replication.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting Geo PostgreSQL replication
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following sections outline troubleshooting steps for fixing replication error messages (indicated by `Database replication working? ... no` in the
[`geo:check` output](common.md#health-check-rake-task).
The instructions present here mostly assume a single-node Geo Linux package deployment, and might need to be adapted to different environments.
## Removing an inactive replication slot
Replication slots are marked as 'inactive' when the replication client (a secondary site) connected to the slot disconnects.
Inactive replication slots cause WAL files to be retained, because they are sent to the client when it reconnects and the slot becomes active once more.
If the secondary site is not able to reconnect, use the following steps to remove its corresponding inactive replication slot:
1. [Start a PostgreSQL console session](https://docs.gitlab.com/omnibus/settings/database.html#connecting-to-the-postgresql-database) on the Geo primary site's database node:
```shell
sudo gitlab-psql -d gitlabhq_production
```
{{< alert type="note" >}}
Using `gitlab-rails dbconsole` does not work, because managing replication slots requires superuser permissions.
{{< /alert >}}
1. View the replication slots and remove them if they are inactive:
```sql
SELECT * FROM pg_replication_slots;
```
Slots where `active` is `f` are inactive.
- If this slot should be active, because you have a **secondary** site configured using that slot:
- Look for the [PostgreSQL logs](../../../logs/_index.md#postgresql-logs) for the **secondary** site,
to view why the replication is not running.
- If the secondary site is no longer able to reconnect:
1. Remove the slot using the PostgreSQL console session:
```sql
SELECT pg_drop_replication_slot('<name_of_inactive_slot>');
```
1. [Re-initiate the replication process](../../setup/database.md#step-3-initiate-the-replication-process),
which recreates the replication slot correctly.
- If you are no longer using the slot (for example, you no longer have Geo enabled), follow the steps [to remove that Geo site](../remove_geo_site.md).
## Message: `WARNING: oldest xmin is far in the past` and `pg_wal` size growing
If a replication slot is inactive,
the `pg_wal` logs corresponding to the slot are reserved forever
(or until the slot is active again). This causes continuous disk usage growth
and the following messages appear repeatedly in the
[PostgreSQL logs](../../../logs/_index.md#postgresql-logs):
```plaintext
WARNING: oldest xmin is far in the past
HINT: Close open transactions soon to avoid wraparound problems.
You might also need to commit or roll back old prepared transactions, or drop stale replication slots.
```
To fix this, you should [remove the inactive replication slot](#removing-an-inactive-replication-slot) and re-initiate the replication.
## Message: `ERROR: replication slots can only be used if max_replication_slots > 0`?
This means that the `max_replication_slots` PostgreSQL variable needs to
be set on the **primary** database. This setting defaults to 1. You may need to
increase this value if you have more **secondary** sites.
Be sure to restart PostgreSQL for this to take effect. See the
[PostgreSQL replication setup](../../setup/database.md#postgresql-replication) guide for more details.
## Message: `replication slot "geo_secondary_my_domain_com" does not exist`
This error occurs when PostgreSQL does not have a replication slot for the
**secondary** site by that name:
```plaintext
FATAL: could not start WAL streaming: ERROR: replication slot "geo_secondary_my_domain_com" does not exist
```
You may want to rerun the [replication process](../../setup/database.md) on the **secondary** site .
## Message: "Command exceeded allowed execution time" when setting up replication?
This may happen while [initiating the replication process](../../setup/database.md#step-3-initiate-the-replication-process) on the **secondary** site,
and indicates your initial dataset is too large to be replicated in the default timeout (30 minutes).
Re-run `gitlab-ctl replicate-geo-database`, but include a larger value for
`--backup-timeout`:
```shell
sudo gitlab-ctl \
replicate-geo-database \
--host=<primary_node_hostname> \
--slot-name=<secondary_slot_name> \
--backup-timeout=21600
```
This gives the initial replication up to six hours to complete, rather than
the default 30 minutes. Adjust as required for your installation.
## Message: "PANIC: could not write to file `pg_xlog/xlogtemp.123`: No space left on device"
Determine if you have any unused replication slots in the **primary** database. This can cause large amounts of
log data to build up in `pg_xlog`.
[Removing the inactive slots](#removing-an-inactive-replication-slot) can reduce the amount of space used in the `pg_xlog`.
## Message: "ERROR: canceling statement due to conflict with recovery"
This error message occurs infrequently under typical usage, and the system is resilient
enough to recover.
However, under certain conditions, some database queries on secondaries may run
excessively long, which increases the frequency of this error message. This can lead to a situation
where some queries never complete due to being canceled on every replication.
These long-running queries are
[planned to be removed in the future](https://gitlab.com/gitlab-org/gitlab/-/issues/34269),
but as a workaround, we recommend enabling
[`hot_standby_feedback`](https://www.postgresql.org/docs/16/hot-standby.html#HOT-STANDBY-CONFLICT).
This increases the likelihood of bloat on the **primary** site as it prevents
`VACUUM` from removing recently-dead rows. However, it has been used
successfully in production on GitLab.com.
To enable `hot_standby_feedback`, add the following to `/etc/gitlab/gitlab.rb`
on the **secondary** site:
```ruby
postgresql['hot_standby_feedback'] = 'on'
```
Then reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
To help us resolve this problem, consider commenting on
[the issue](https://gitlab.com/gitlab-org/gitlab/-/issues/4489).
## Message: `server certificate for "PostgreSQL" does not match host name`
If you see this error:
```plaintext
FATAL: could not connect to the primary server: server certificate for "PostgreSQL" does not match host name
```
This happens because the PostgreSQL certificate that the Linux package automatically creates contains
the Common Name `PostgreSQL`, but the replication is connecting to a different host and GitLab attempts to use
the `verify-full` SSL mode by default.
To fix this issue, you can either:
- Use the `--sslmode=verify-ca` argument with the `replicate-geo-database` command.
- For an already replicated database, change `sslmode=verify-full` to `sslmode=verify-ca`
in `/var/opt/gitlab/postgresql/data/gitlab-geo.conf` and run `gitlab-ctl restart postgresql`.
- [Configure SSL for PostgreSQL](https://docs.gitlab.com/omnibus/settings/database.html#configuring-ssl)
with a custom certificate (including the host name that's used to connect to the database in the CN or SAN)
instead of using the automatically generated certificate.
## Message: `LOG: invalid CIDR mask in address`
This happens on wrongly-formatted addresses in `postgresql['md5_auth_cidr_addresses']`.
```plaintext
2020-03-20_23:59:57.60499 LOG: invalid CIDR mask in address "***"
2020-03-20_23:59:57.60501 CONTEXT: line 74 of configuration file "/var/opt/gitlab/postgresql/data/pg_hba.conf"
```
To fix this, update the IP addresses in `/etc/gitlab/gitlab.rb` under `postgresql['md5_auth_cidr_addresses']`
to respect the CIDR format (for example, `10.0.0.1/32`).
## Message: `LOG: invalid IP mask "md5": Name or service not known`
This happens when you have added IP addresses without a subnet mask in `postgresql['md5_auth_cidr_addresses']`.
```plaintext
2020-03-21_00:23:01.97353 LOG: invalid IP mask "md5": Name or service not known
2020-03-21_00:23:01.97354 CONTEXT: line 75 of configuration file "/var/opt/gitlab/postgresql/data/pg_hba.conf"
```
To fix this, add the subnet mask in `/etc/gitlab/gitlab.rb` under `postgresql['md5_auth_cidr_addresses']`
to respect the CIDR format (for example, `10.0.0.1/32`).
## Message: `Found data in the gitlabhq_production database`
If you receive the error `Found data in the gitlabhq_production database!` when running
`gitlab-ctl replicate-geo-database`, data was detected in the `projects` table. When one or more projects are detected, the operation
is aborted to prevent accidental data loss. To bypass this message, pass the `--force` option to the command.
## Message: `FATAL: could not map anonymous shared memory: Cannot allocate memory`
If you see this message, it means that the secondary site's PostgreSQL tries to request memory that is higher than the available memory. There is an [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/381585) that tracks this problem.
Example error message in Patroni logs (located at `/var/log/gitlab/patroni/current` for Linux package installations):
```plaintext
2023-11-21_23:55:18.63727 FATAL: could not map anonymous shared memory: Cannot allocate memory
2023-11-21_23:55:18.63729 HINT: This error usually means that PostgreSQL's request for a shared memory segment exceeded available memory, swap space, or huge pages. To reduce the request size (currently 17035526144 bytes), reduce PostgreSQL's shared memory usage, perhaps by reducing shared_buffers or max_connections.
```
The workaround is to increase the memory available to the secondary site's PostgreSQL nodes to match the memory requirements of the primary site's PostgreSQL nodes.
## Investigate causes of database replication lag
If the output of `sudo gitlab-rake geo:status` shows that `Database replication lag` remains significantly high over time, the primary node in database replication can be checked to determine the status of lag for
different parts of the database replication process. These values are known as `write_lag`, `flush_lag`, and `replay_lag`. For more information, see
[the official PostgreSQL documentation](https://www.postgresql.org/docs/16/monitoring-stats.html#MONITORING-PG-STAT-REPLICATION-VIEW).
Run the following command from the primary Geo node's database to provide relevant output:
```shell
gitlab-psql -xc 'SELECT write_lag,flush_lag,replay_lag FROM pg_stat_replication;'
-[ RECORD 1 ]---------------
write_lag | 00:00:00.072392
flush_lag | 00:00:00.108168
replay_lag | 00:00:00.108283
```
If one or more of these values is significantly high, this could indicate a problem and should be investigated further. When determining the cause, consider that:
- `write_lag` indicates the time since when WAL bytes have been sent by the primary, then received to the secondary, but not yet flushed or applied.
- A high `write_lag` value may indicate degraded network performance or insufficient network speed between the primary and secondary nodes.
- A high `flush_lag` value may indicate degraded or sub-optimal disk I/O performance with the secondary node's storage device.
- A high `replay_lag` value may indicate long running transactions in PostgreSQL, or the saturation of a needed resource like the CPU.
- The difference in time between `write_lag` and `flush_lag` indicates that WAL bytes have been sent to the underlying storage system, but it has not reported that they were flushed.
This data is most likely not fully written to a persistent storage, and likely held in some kind of volatile write cache.
- The difference between `flush_lag` and `replay_lag` indicates WAL bytes that have been successfully persisted to storage, but could not be replayed by the database system.
## Stuck at `Message: pg_basebackup: initiating base backup, waiting for checkpoint to complete`
If the initial replication is stuck at `Message: pg_basebackup: initiating base backup, waiting for checkpoint to complete`, this means that the primary Geo site
is not actively used. This mostly happens on a non-production GitLab server or on a brand new GitLab installation.
The workaround is to cause some database writes. For example, you can sign in to the primary site and create some issues and comments.
An alternative workaround is to run the SQL query `CHECKPOINT;` on the database of the primary site:
```shell
sudo gitlab-psql -xc 'CHECKPOINT;
```
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting Geo PostgreSQL replication
breadcrumbs:
- doc
- administration
- geo
- replication
- troubleshooting
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following sections outline troubleshooting steps for fixing replication error messages (indicated by `Database replication working? ... no` in the
[`geo:check` output](common.md#health-check-rake-task).
The instructions present here mostly assume a single-node Geo Linux package deployment, and might need to be adapted to different environments.
## Removing an inactive replication slot
Replication slots are marked as 'inactive' when the replication client (a secondary site) connected to the slot disconnects.
Inactive replication slots cause WAL files to be retained, because they are sent to the client when it reconnects and the slot becomes active once more.
If the secondary site is not able to reconnect, use the following steps to remove its corresponding inactive replication slot:
1. [Start a PostgreSQL console session](https://docs.gitlab.com/omnibus/settings/database.html#connecting-to-the-postgresql-database) on the Geo primary site's database node:
```shell
sudo gitlab-psql -d gitlabhq_production
```
{{< alert type="note" >}}
Using `gitlab-rails dbconsole` does not work, because managing replication slots requires superuser permissions.
{{< /alert >}}
1. View the replication slots and remove them if they are inactive:
```sql
SELECT * FROM pg_replication_slots;
```
Slots where `active` is `f` are inactive.
- If this slot should be active, because you have a **secondary** site configured using that slot:
- Look for the [PostgreSQL logs](../../../logs/_index.md#postgresql-logs) for the **secondary** site,
to view why the replication is not running.
- If the secondary site is no longer able to reconnect:
1. Remove the slot using the PostgreSQL console session:
```sql
SELECT pg_drop_replication_slot('<name_of_inactive_slot>');
```
1. [Re-initiate the replication process](../../setup/database.md#step-3-initiate-the-replication-process),
which recreates the replication slot correctly.
- If you are no longer using the slot (for example, you no longer have Geo enabled), follow the steps [to remove that Geo site](../remove_geo_site.md).
## Message: `WARNING: oldest xmin is far in the past` and `pg_wal` size growing
If a replication slot is inactive,
the `pg_wal` logs corresponding to the slot are reserved forever
(or until the slot is active again). This causes continuous disk usage growth
and the following messages appear repeatedly in the
[PostgreSQL logs](../../../logs/_index.md#postgresql-logs):
```plaintext
WARNING: oldest xmin is far in the past
HINT: Close open transactions soon to avoid wraparound problems.
You might also need to commit or roll back old prepared transactions, or drop stale replication slots.
```
To fix this, you should [remove the inactive replication slot](#removing-an-inactive-replication-slot) and re-initiate the replication.
## Message: `ERROR: replication slots can only be used if max_replication_slots > 0`?
This means that the `max_replication_slots` PostgreSQL variable needs to
be set on the **primary** database. This setting defaults to 1. You may need to
increase this value if you have more **secondary** sites.
Be sure to restart PostgreSQL for this to take effect. See the
[PostgreSQL replication setup](../../setup/database.md#postgresql-replication) guide for more details.
## Message: `replication slot "geo_secondary_my_domain_com" does not exist`
This error occurs when PostgreSQL does not have a replication slot for the
**secondary** site by that name:
```plaintext
FATAL: could not start WAL streaming: ERROR: replication slot "geo_secondary_my_domain_com" does not exist
```
You may want to rerun the [replication process](../../setup/database.md) on the **secondary** site .
## Message: "Command exceeded allowed execution time" when setting up replication?
This may happen while [initiating the replication process](../../setup/database.md#step-3-initiate-the-replication-process) on the **secondary** site,
and indicates your initial dataset is too large to be replicated in the default timeout (30 minutes).
Re-run `gitlab-ctl replicate-geo-database`, but include a larger value for
`--backup-timeout`:
```shell
sudo gitlab-ctl \
replicate-geo-database \
--host=<primary_node_hostname> \
--slot-name=<secondary_slot_name> \
--backup-timeout=21600
```
This gives the initial replication up to six hours to complete, rather than
the default 30 minutes. Adjust as required for your installation.
## Message: "PANIC: could not write to file `pg_xlog/xlogtemp.123`: No space left on device"
Determine if you have any unused replication slots in the **primary** database. This can cause large amounts of
log data to build up in `pg_xlog`.
[Removing the inactive slots](#removing-an-inactive-replication-slot) can reduce the amount of space used in the `pg_xlog`.
## Message: "ERROR: canceling statement due to conflict with recovery"
This error message occurs infrequently under typical usage, and the system is resilient
enough to recover.
However, under certain conditions, some database queries on secondaries may run
excessively long, which increases the frequency of this error message. This can lead to a situation
where some queries never complete due to being canceled on every replication.
These long-running queries are
[planned to be removed in the future](https://gitlab.com/gitlab-org/gitlab/-/issues/34269),
but as a workaround, we recommend enabling
[`hot_standby_feedback`](https://www.postgresql.org/docs/16/hot-standby.html#HOT-STANDBY-CONFLICT).
This increases the likelihood of bloat on the **primary** site as it prevents
`VACUUM` from removing recently-dead rows. However, it has been used
successfully in production on GitLab.com.
To enable `hot_standby_feedback`, add the following to `/etc/gitlab/gitlab.rb`
on the **secondary** site:
```ruby
postgresql['hot_standby_feedback'] = 'on'
```
Then reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
To help us resolve this problem, consider commenting on
[the issue](https://gitlab.com/gitlab-org/gitlab/-/issues/4489).
## Message: `server certificate for "PostgreSQL" does not match host name`
If you see this error:
```plaintext
FATAL: could not connect to the primary server: server certificate for "PostgreSQL" does not match host name
```
This happens because the PostgreSQL certificate that the Linux package automatically creates contains
the Common Name `PostgreSQL`, but the replication is connecting to a different host and GitLab attempts to use
the `verify-full` SSL mode by default.
To fix this issue, you can either:
- Use the `--sslmode=verify-ca` argument with the `replicate-geo-database` command.
- For an already replicated database, change `sslmode=verify-full` to `sslmode=verify-ca`
in `/var/opt/gitlab/postgresql/data/gitlab-geo.conf` and run `gitlab-ctl restart postgresql`.
- [Configure SSL for PostgreSQL](https://docs.gitlab.com/omnibus/settings/database.html#configuring-ssl)
with a custom certificate (including the host name that's used to connect to the database in the CN or SAN)
instead of using the automatically generated certificate.
## Message: `LOG: invalid CIDR mask in address`
This happens on wrongly-formatted addresses in `postgresql['md5_auth_cidr_addresses']`.
```plaintext
2020-03-20_23:59:57.60499 LOG: invalid CIDR mask in address "***"
2020-03-20_23:59:57.60501 CONTEXT: line 74 of configuration file "/var/opt/gitlab/postgresql/data/pg_hba.conf"
```
To fix this, update the IP addresses in `/etc/gitlab/gitlab.rb` under `postgresql['md5_auth_cidr_addresses']`
to respect the CIDR format (for example, `10.0.0.1/32`).
## Message: `LOG: invalid IP mask "md5": Name or service not known`
This happens when you have added IP addresses without a subnet mask in `postgresql['md5_auth_cidr_addresses']`.
```plaintext
2020-03-21_00:23:01.97353 LOG: invalid IP mask "md5": Name or service not known
2020-03-21_00:23:01.97354 CONTEXT: line 75 of configuration file "/var/opt/gitlab/postgresql/data/pg_hba.conf"
```
To fix this, add the subnet mask in `/etc/gitlab/gitlab.rb` under `postgresql['md5_auth_cidr_addresses']`
to respect the CIDR format (for example, `10.0.0.1/32`).
## Message: `Found data in the gitlabhq_production database`
If you receive the error `Found data in the gitlabhq_production database!` when running
`gitlab-ctl replicate-geo-database`, data was detected in the `projects` table. When one or more projects are detected, the operation
is aborted to prevent accidental data loss. To bypass this message, pass the `--force` option to the command.
## Message: `FATAL: could not map anonymous shared memory: Cannot allocate memory`
If you see this message, it means that the secondary site's PostgreSQL tries to request memory that is higher than the available memory. There is an [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/381585) that tracks this problem.
Example error message in Patroni logs (located at `/var/log/gitlab/patroni/current` for Linux package installations):
```plaintext
2023-11-21_23:55:18.63727 FATAL: could not map anonymous shared memory: Cannot allocate memory
2023-11-21_23:55:18.63729 HINT: This error usually means that PostgreSQL's request for a shared memory segment exceeded available memory, swap space, or huge pages. To reduce the request size (currently 17035526144 bytes), reduce PostgreSQL's shared memory usage, perhaps by reducing shared_buffers or max_connections.
```
The workaround is to increase the memory available to the secondary site's PostgreSQL nodes to match the memory requirements of the primary site's PostgreSQL nodes.
## Investigate causes of database replication lag
If the output of `sudo gitlab-rake geo:status` shows that `Database replication lag` remains significantly high over time, the primary node in database replication can be checked to determine the status of lag for
different parts of the database replication process. These values are known as `write_lag`, `flush_lag`, and `replay_lag`. For more information, see
[the official PostgreSQL documentation](https://www.postgresql.org/docs/16/monitoring-stats.html#MONITORING-PG-STAT-REPLICATION-VIEW).
Run the following command from the primary Geo node's database to provide relevant output:
```shell
gitlab-psql -xc 'SELECT write_lag,flush_lag,replay_lag FROM pg_stat_replication;'
-[ RECORD 1 ]---------------
write_lag | 00:00:00.072392
flush_lag | 00:00:00.108168
replay_lag | 00:00:00.108283
```
If one or more of these values is significantly high, this could indicate a problem and should be investigated further. When determining the cause, consider that:
- `write_lag` indicates the time since when WAL bytes have been sent by the primary, then received to the secondary, but not yet flushed or applied.
- A high `write_lag` value may indicate degraded network performance or insufficient network speed between the primary and secondary nodes.
- A high `flush_lag` value may indicate degraded or sub-optimal disk I/O performance with the secondary node's storage device.
- A high `replay_lag` value may indicate long running transactions in PostgreSQL, or the saturation of a needed resource like the CPU.
- The difference in time between `write_lag` and `flush_lag` indicates that WAL bytes have been sent to the underlying storage system, but it has not reported that they were flushed.
This data is most likely not fully written to a persistent storage, and likely held in some kind of volatile write cache.
- The difference between `flush_lag` and `replay_lag` indicates WAL bytes that have been successfully persisted to storage, but could not be replayed by the database system.
## Stuck at `Message: pg_basebackup: initiating base backup, waiting for checkpoint to complete`
If the initial replication is stuck at `Message: pg_basebackup: initiating base backup, waiting for checkpoint to complete`, this means that the primary Geo site
is not actively used. This mostly happens on a non-production GitLab server or on a brand new GitLab installation.
The workaround is to cause some database writes. For example, you can sign in to the primary site and create some issues and comments.
An alternative workaround is to run the SQL query `CHECKPOINT;` on the database of the primary site:
```shell
sudo gitlab-psql -xc 'CHECKPOINT;
```
|
https://docs.gitlab.com/administration/geo/runners
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/runners.md
|
2025-08-13
|
doc/administration/geo/secondary_proxy
|
[
"doc",
"administration",
"geo",
"secondary_proxy"
] |
runners.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Secondary runners
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/9779) in GitLab 16.8 [with a flag](../../feature_flags/_index.md) named `geo_proxy_check_pipeline_refs`. Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/434041) in GitLab 16.9.
{{< /history >}}
With [Geo proxying for secondary sites](_index.md), it is possible to register a `gitlab-runner` with a secondary site. This offloads load from the primary instance.
{{< alert type="note" >}}
The jobs that start during the first stage of a pipeline almost always have their Git clone requests forwarded to the primary site. This is because those clones usually occur before the Git data is replicated and verified by the secondary site. Later stages are not guaranteed to be served by the secondary site either, for example if the Git change is large, bandwidth is small, or pipeline stages are short. In most cases, the subsequent stages of the pipeline serve Git data from the secondary site. [Issue 446176](https://gitlab.com/gitlab-org/gitlab/-/issues/446176) proposes an enhancement to increase the chance of the first stage clone request is served from the secondary site.
{{< /alert >}}
## Use secondary runners with a Location Aware public URL (Unified URL)
{{< details >}}
- Offering: GitLab Self-Managed
{{< /details >}}
Using [Location-Aware DNS](_index.md#configure-location-aware-dns), with the feature flag enabled works with no extra configuration. After you install and register a runner in the same location as a secondary site, it automatically talks to the closest site, and only proxies to the primary if the secondary is out of date.
## Use secondary runners with separate URLs
Using separate secondary URLs, the runners should be:
1. Registered with the secondary external URL.
1. Configured with [`clone_url`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-clone_url-works) set to the `external_url` of the secondary instance.
## Handling a Planned Failover with secondary runners
When executing [a planned failover](../disaster_recovery/planned_failover.md), secondary runners try to keep talking to their local instance. This leads to decreased runner capacity, and may need to be accounted for.
### With Location Aware public URL
{{< details >}}
- Offering: GitLab Self-Managed
{{< /details >}}
When using [Location-Aware DNS](_index.md#configure-location-aware-dns), all runners automatically connect to the closest Geo site.
When failing over to a new primary:
- While the old primary is still in the DNS record, any runners previously connected to your old primary still attempt to pick up jobs from the old primary. If it is unreachable, the runners [detect this](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-unhealthy_requests_limit-and-unhealthy_interval-works), and stop requesting for an extended period of time after the instance returns.
- If you have [multiple secondary nodes](../disaster_recovery/_index.md#promoting-secondary-geo-replica-in-multi-secondary-configurations), after the initial failover the remaining secondaries are in an unhealthy state until they are [replicated](../disaster_recovery/_index.md#step-2-initiate-the-replication-process) with the new primary. The runners attached to them are then unable to check in, and their health check also kicks in.
- If you remove any of the unhealthy nodes from the Geo DNS entry, the runners pick the next closest instance. Depending on your architecture, this may not be what you want because you could overwhelm your site in its reduced state.
To alleviate any of these issues, you can [pause](#pausing-runners) or shutdown some of the runners until the site is back up to 100%.
If you are not concerned about these issues, there is nothing to do here.
### With separate URLs
- If you are returning the old primary to service, you can pause the old primary runners until it is back online. This prevents the health check from kicking in.
- If the old primary is not returning, or you want to avoid temporarily reduced runner capacity, the primary runners should be reconfigured to connect to the new primary.
- If multiple secondaries are being used, the runners should be [paused](#pausing-runners), shutdown, or reconfigured to connect to the new primary while they are being replicated to the new primary.
### Pausing runners
You must have administrator access to use any of the following methods:
- Through the **Admin** area:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Runners**.
1. Identify the runners you would like to pause.
1. Select the `pause` button next to each runner you would like to pause.
1. After the failover is complete, unpause the runners you paused in the previous step.
- Use the [Runners API](../../../api/runners.md):
1. Fetch or create a [personal access token](../../../user/profile/personal_access_tokens.md) with administrator access.
1. Get the list of runners. You can filter the list [using the API](../../../api/runners.md#list-all-runners).
1. Identify the runners you would like to pause, and make note of their `id`.
1. [Follow the API documentation](../../../api/runners.md#pause-a-runner) to pause each runner.
1. After the failover is complete, unpause the list of runners using the API by setting `paused=false`.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: true
title: Secondary runners
breadcrumbs:
- doc
- administration
- geo
- secondary_proxy
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/9779) in GitLab 16.8 [with a flag](../../feature_flags/_index.md) named `geo_proxy_check_pipeline_refs`. Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/434041) in GitLab 16.9.
{{< /history >}}
With [Geo proxying for secondary sites](_index.md), it is possible to register a `gitlab-runner` with a secondary site. This offloads load from the primary instance.
{{< alert type="note" >}}
The jobs that start during the first stage of a pipeline almost always have their Git clone requests forwarded to the primary site. This is because those clones usually occur before the Git data is replicated and verified by the secondary site. Later stages are not guaranteed to be served by the secondary site either, for example if the Git change is large, bandwidth is small, or pipeline stages are short. In most cases, the subsequent stages of the pipeline serve Git data from the secondary site. [Issue 446176](https://gitlab.com/gitlab-org/gitlab/-/issues/446176) proposes an enhancement to increase the chance of the first stage clone request is served from the secondary site.
{{< /alert >}}
## Use secondary runners with a Location Aware public URL (Unified URL)
{{< details >}}
- Offering: GitLab Self-Managed
{{< /details >}}
Using [Location-Aware DNS](_index.md#configure-location-aware-dns), with the feature flag enabled works with no extra configuration. After you install and register a runner in the same location as a secondary site, it automatically talks to the closest site, and only proxies to the primary if the secondary is out of date.
## Use secondary runners with separate URLs
Using separate secondary URLs, the runners should be:
1. Registered with the secondary external URL.
1. Configured with [`clone_url`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-clone_url-works) set to the `external_url` of the secondary instance.
## Handling a Planned Failover with secondary runners
When executing [a planned failover](../disaster_recovery/planned_failover.md), secondary runners try to keep talking to their local instance. This leads to decreased runner capacity, and may need to be accounted for.
### With Location Aware public URL
{{< details >}}
- Offering: GitLab Self-Managed
{{< /details >}}
When using [Location-Aware DNS](_index.md#configure-location-aware-dns), all runners automatically connect to the closest Geo site.
When failing over to a new primary:
- While the old primary is still in the DNS record, any runners previously connected to your old primary still attempt to pick up jobs from the old primary. If it is unreachable, the runners [detect this](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-unhealthy_requests_limit-and-unhealthy_interval-works), and stop requesting for an extended period of time after the instance returns.
- If you have [multiple secondary nodes](../disaster_recovery/_index.md#promoting-secondary-geo-replica-in-multi-secondary-configurations), after the initial failover the remaining secondaries are in an unhealthy state until they are [replicated](../disaster_recovery/_index.md#step-2-initiate-the-replication-process) with the new primary. The runners attached to them are then unable to check in, and their health check also kicks in.
- If you remove any of the unhealthy nodes from the Geo DNS entry, the runners pick the next closest instance. Depending on your architecture, this may not be what you want because you could overwhelm your site in its reduced state.
To alleviate any of these issues, you can [pause](#pausing-runners) or shutdown some of the runners until the site is back up to 100%.
If you are not concerned about these issues, there is nothing to do here.
### With separate URLs
- If you are returning the old primary to service, you can pause the old primary runners until it is back online. This prevents the health check from kicking in.
- If the old primary is not returning, or you want to avoid temporarily reduced runner capacity, the primary runners should be reconfigured to connect to the new primary.
- If multiple secondaries are being used, the runners should be [paused](#pausing-runners), shutdown, or reconfigured to connect to the new primary while they are being replicated to the new primary.
### Pausing runners
You must have administrator access to use any of the following methods:
- Through the **Admin** area:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Runners**.
1. Identify the runners you would like to pause.
1. Select the `pause` button next to each runner you would like to pause.
1. After the failover is complete, unpause the runners you paused in the previous step.
- Use the [Runners API](../../../api/runners.md):
1. Fetch or create a [personal access token](../../../user/profile/personal_access_tokens.md) with administrator access.
1. Get the list of runners. You can filter the list [using the API](../../../api/runners.md#list-all-runners).
1. Identify the runners you would like to pause, and make note of their `id`.
1. [Follow the API documentation](../../../api/runners.md#pause-a-runner) to pause each runner.
1. After the failover is complete, unpause the list of runners using the API by setting `paused=false`.
|
https://docs.gitlab.com/administration/geo/secondary_proxy
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/geo/_index.md
|
2025-08-13
|
doc/administration/geo/secondary_proxy
|
[
"doc",
"administration",
"geo",
"secondary_proxy"
] |
_index.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Geo proxying for secondary sites
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- HTTP proxying for secondary sites with separate URLs [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/346112) in GitLab 14.5 [with a flag](../../feature_flags/_index.md) named `geo_secondary_proxy_separate_urls`. Disabled by default.
- [Enabled on GitLab.com, GitLab Self-Managed, and GitLab Dedicated](https://gitlab.com/gitlab-org/gitlab/-/issues/346112) in GitLab 15.1.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
The `geo_secondary_proxy_separate_urls` feature flag is planned to be deprecated and removed in a future release.
Support for read-only Geo secondary sites is proposed in [issue 366810](https://gitlab.com/gitlab-org/gitlab/-/issues/366810).
{{< /alert >}}
Secondary sites behave as full read-write GitLab instances. They transparently proxy all operations to the primary site, with [some notable exceptions](#features-accelerated-by-secondary-geo-sites).
This behavior enables use-cases including:
- Putting all Geo sites behind a single URL, to deliver a consistent, seamless, and comprehensive experience whichever site the user lands on. Users don't need to juggle multiple GitLab URLs.
- Geographically load-balancing traffic without worrying about write access.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Geo proxying for secondary sites](https://www.youtube.com/watch?v=TALLy7__Na8).
<!-- Video published on 2022-01-26 -->
For known issues, see [proxying-related items in the Geo documentation](../_index.md#known-issues).
## Set up a unified URL for Geo sites
Secondary sites can transparently serve read-write traffic. Therefore, you can
use a single external URL so that requests can hit either the primary Geo site
or any secondary Geo sites. This delivers a consistent, seamless, and
comprehensive experience whichever site the user lands on. Users don't need to
juggle multiple URLs or even be aware of the idea of multiple sites.
You can route traffic to Geo sites with:
- Geo-location aware DNS. To route traffic to the closest Geo site, whether primary or secondary. For an example, follow [Configure location-aware DNS](#configure-location-aware-dns).
- Round-robin DNS.
- A load-balancer. It must use sticky sessions to avoid authentication failures and cross-site request errors. DNS routing is inherently sticky so it does not share this caveat.
### Configure location-aware DNS
Follow this example to route traffic to the closest Geo site, whether primary or secondary.
#### Prerequisites
This example creates a `gitlab.example.com` subdomain that automatically directs
requests:
- From Europe to a **secondary** site.
- From all other locations to the **primary** site.
For this example, you need:
- A working Geo **primary** site and **secondary** site, see the [Geo setup instructions](../setup/_index.md).
- A DNS zone managing your domain. Although the following instructions use
[AWS Route53](https://aws.amazon.com/route53/)
and [GCP cloud DNS](https://cloud.google.com/dns/), other services such as
[Cloudflare](https://www.cloudflare.com/) can be used as well.
#### AWS Route53
In this example, you use a Route53 Hosted Zone managing your domain for the Route53 setup.
In a Route53 Hosted Zone, traffic policies can be used to set up a variety of
routing configurations. To create a traffic policy:
1. Go to the
[Route53 dashboard](https://console.aws.amazon.com/route53/home) and select
**Traffic policies**.
1. Select **Create traffic policy**.
1. Fill in the **Policy Name** field with `Single Git Host` and select **Next**.
1. Leave **DNS type** as `A: IP Address in IPv4 format`.
1. Select **Connect to**, then select **Geolocation rule**.
1. For the first **Location**:
1. Leave it as `Default`.
1. Select **Connect to**, then select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **primary** IP address>`.
1. For the second **Location**:
1. Choose `Europe`.
1. Select **Connect to**, then select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **secondary** IP address>`.

1. Select **Create traffic policy**.
1. Fill in **Policy record DNS name** with `gitlab`.

1. Select **Create policy records**.
You have successfully set up a single host, like `gitlab.example.com`, which
distributes traffic to your Geo sites by geolocation.
#### GCP
In this example, you create a GCP Cloud DNS zone managing your domain.
When creating Geo-Based record sets, GCP applies a nearest match for the source region when the source of the traffic doesn't match any policy items exactly. To create a Geo-Based record set:
1. Select **Network Services** > **Cloud DNS**.
1. Select the Zone configured for your domain.
1. Select **Add Record Set**.
1. Enter the DNS Name for your Location-aware public URL, for example, `gitlab.example.com`.
1. Select the **Routing Policy**: **Geo-Based**.
1. Select **Add Managed RRData**.
1. Select **Source Region**: **us-central1**.
1. Enter your `<**primary** IP address>`.
1. Select **Done**.
1. Select **Add Managed RRData**.
1. Select **Source Region**: **europe-west1**.
1. Enter your `<**secondary** IP address>`.
1. Select **Done**.
1. Select **Create**.
You have successfully set up a single host, like `gitlab.example.com`, which
distributes traffic to your Geo sites using a location-aware URL.
### Configure each site to use the same external URL
After you have set up routing from a single URL to all of your Geo sites, follow
the following steps if your sites use different URLs:
1. On each GitLab site, SSH into **each** node running Rails (Puma, Sidekiq, Log-Cursor)
and set the `external_url` to that of the single URL:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. To match the new external URL set on the secondary Geo sites, the primary database
needs to reflect this change.
In the Geo administration page of the **primary** site, edit each Geo secondary that
is using the secondary proxying and set the `URL` field to the single URL.
Make sure the primary site is also using this URL.
To allow the sites to talk to each other, [make sure the `Internal URL` field is unique for each site](../../geo_sites.md#set-up-the-internal-urls).
In Kubernetes, you can [use the same domain under `global.hosts.domain` as for the primary site](https://docs.gitlab.com/charts/advanced/geo/).
## Set up a separate URL for a secondary Geo site
You can use different external URLs per site. You can use this to offer a specific site to a specific set of users. Alternatively, you can give users control over which site they use, though they must understand the implications of their choice.
{{< alert type="note" >}}
GitLab does not support multiple external URLs, see [issue 21319](https://gitlab.com/gitlab-org/gitlab/-/issues/21319). An inherent problem is there are many cases where a site needs to produce an absolute URL outside of the context of an HTTP request, such as when sending emails that were not triggered by a request.
{{< /alert >}}
### Configure a secondary Geo site to a different external URL than the primary site
If your secondary site uses the same external URL as the primary site,
but you want to change it to use a different URL:
1. On the secondary site, SSH into **each** node running Rails (Puma, Sidekiq, Log-Cursor)
and set the `external_url` to the desired URL for the secondary site:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. To match the new external URL set on the secondary Geo site, the primary database
needs to reflect this change.
In the Geo administration page of the **primary** site, edit the target secondary site and set the `URL` field to the desired URL.
To allow the sites to talk to each other, [make sure the `Internal URL` field is unique for each site](../../geo_sites.md#set-up-the-internal-urls). If the desired URL is unique to this site, then you can clear the `Internal URL` field. On save, it defaults to the external URL.
## Behavior of secondary sites when the primary Geo site is down
Considering that web traffic is proxied to the primary, the behavior of the secondary sites differs when the primary
site is inaccessible:
- UI and API traffic return the same errors as the primary (or fail if the primary is not accessible at all) because they are proxied.
- For repositories that are fully up-to-date on the specific secondary site being accessed, Git read operations still work as expected,
including authentication through HTTP(s) or SSH. However, Git reads performed by GitLab Runners will fail.
- Git operations for repositories that are not replicated to the secondary site return the same errors
as the primary site because they are proxied.
- All Git write operations return the same errors as the primary site because they are proxied.
## Features accelerated by secondary Geo sites
Most HTTP traffic sent to a secondary Geo site is proxied to the primary Geo site. With this architecture,
secondary Geo sites are able to support write requests, and avoid read-after-write problems. Certain
**read** requests are handled locally by secondary sites for improved latency and bandwidth nearby.
The following table details the components tested through the Geo secondary site Workhorse proxy.
It does not cover all data types.
In this context, accelerated reads refer to read requests served from the secondary site, provided that the data is up to date for the component on the secondary site. If the data on the secondary site is determined to be out of date, the request is forwarded to the primary site. Read requests for components not listed in the table below are always automatically forwarded to the primary site.
| Feature / component | Accelerated reads? | Notes |
|:----------------------------------------------------|:-------------------------------------|-------|
| Project, wiki, design repository (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Project, wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| Project, Personal Snippet (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Project, Personal Snippet (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| Group wiki repository (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Group wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| User uploads | {{< icon name="dotted-circle" >}} No | |
| LFS objects (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| LFS objects (using Git) | {{< icon name="check-circle" >}} Yes | |
| Pages | {{< icon name="dotted-circle" >}} No | Pages can use the same URL (without access control), but must be configured separately and are not proxied. |
| Advanced search (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Container registry | {{< icon name="dotted-circle" >}} No | The container registry is only recommended for Disaster Recovery scenarios. If the secondary site's container registry is not up to date, the read request is served with old data as the request is not forwarded to the primary site. Accelerating the container registry is planned, upvote or comment in the [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) to indicate your interest or ask your GitLab representative to do so on your behalf. |
| Dependency Proxy | {{< icon name="dotted-circle" >}} No | Read requests to a Geo secondary site's Dependency Proxy are always proxied to the primary site. |
| All other data | {{< icon name="dotted-circle" >}} No | Read requests for components not listed in this table are always automatically forwarded to the primary site. |
To request acceleration of a feature, check if an issue already exists in [epic 8239](https://gitlab.com/groups/gitlab-org/-/epics/8239) and upvote or comment on it to indicate your interest or ask your GitLab representative to do so on your behalf. If an applicable issue doesn't exist, open one and mention it in the epic.
## Disable secondary site HTTP proxying
Secondary site HTTP proxying is enabled by default on a secondary site when it uses a unified URL, meaning, it is configured with the same `external_url` as the primary site. Disabling proxying in this case tends not to be helpful due to completely different behavior being served at the same URL, depending on routing. When HTTP proxying is disabled on a secondary Geo site, the site operates in read-only mode, with several important limitations you should be aware of.
### What happens if you disable secondary proxying
Disabling the proxying feature flag has the following general effects.
#### HTTP and Git requests
- The secondary site does not proxy HTTP requests to the primary site. Instead, it attempts to serve them itself, or fail.
- Git requests generally succeed. Git pushes are redirected or proxied to the primary site.
- Other than Git requests, any HTTP request which may write data fails. Read requests generally succeed.
- The secondary site UI shows a banner: 
| Feature / component | Succeed | Notes |
|:----------------------------------------------------|:----------------------------------------|-------|
| Project, wiki, design repository (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Project, wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Project, Personal Snippet (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Project, Personal Snippet (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Group wiki repository (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Group wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| User uploads | {{< icon name="dotted-circle" >}} Maybe | Upload files are served from the locally stored data. Attempting to upload a file on a secondary causes an error. |
| LFS objects (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| LFS objects (using Git) | {{< icon name="check-circle" >}} Yes | LFS objects are served from the locally stored data, while pushes get proxied to the primary. If an LFS object doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Pages | {{< icon name="dotted-circle" >}} Maybe | Pages can use the same URL (without access control), but must be configured separately and are not proxied. |
| Advanced search (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Container registry | {{< icon name="dotted-circle" >}} No | The container registry is only recommended for Disaster Recovery scenarios. If the secondary site's container registry is not up to date, the read request is served with old data as the request is not forwarded to the primary site. Accelerating the container registry is planned, upvote or comment in the [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) to indicate your interest or ask your GitLab representative to do so on your behalf. |
| Dependency Proxy | {{< icon name="dotted-circle" >}} No | |
| All other data | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
You should use the feature flag over using the `GEO_SECONDARY_PROXY` environment variable.
HTTP proxying is enabled by default in GitLab 15.1 on a secondary site even without a unified URL.
#### Terms of service acceptance
When proxying is disabled, users who access only the secondary site cannot properly accept terms of service or other legal agreements. This creates the following issues:
- **No record of acceptance**: If an employee only logs into the secondary site, their acceptance of terms and conditions is not recorded in the primary database because write operations (including terms acceptance) are not proxied when secondary proxying is disabled, even though they may be presented with the terms message.
- **Legal compliance concerns**: Organizations may lack proper legal coverage if employees use GitLab services through a secondary-only access pattern, since there's no verifiable record of their agreement to the terms and conditions.
As a workaround, you must access the primary site at least once to properly accept terms and conditions. After accepted on the primary, this information is replicated to secondary sites through normal Geo synchronization.
{{< alert type="note" >}}
This limitation affects organizations that require documented acceptance of terms and conditions for compliance or legal purposes. Ensure users have access to the primary site for the initial terms acceptance.
{{< /alert >}}
### Disable proxy on all secondary sites
If you need to disable proxying on all secondary sites, it is easiest to disable the feature flag:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into a node which is running Puma or Sidekiq on your primary Geo site and run:
```shell
sudo gitlab-rails runner "Feature.disable(:geo_secondary_proxy_separate_urls)"
```
1. Restart Puma on all nodes which are running it on your secondary Geo site:
```shell
sudo gitlab-ctl restart puma
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. On your primary Geo site, run this command in the Toolbox pod:
```shell
kubectl exec -it <toolbox-pod-name> -- gitlab-rails runner "Feature.disable(:geo_secondary_proxy_separate_urls)"
```
1. Restart the Webservice pods on your secondary Geo site:
```shell
kubectl rollout restart deployment -l app=webservice
```
{{< /tab >}}
{{< /tabs >}}
To revert the changes so secondary site proxying is enabled again:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into a node which is running Puma or Sidekiq on your primary Geo site and run:
```shell
sudo gitlab-rails runner "Feature.enable(:geo_secondary_proxy_separate_urls)"
```
1. Restart Puma on all nodes which are running it on your secondary Geo site:
```shell
sudo gitlab-ctl restart puma
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. On your primary Geo site, run this command in the Toolbox pod:
```shell
kubectl exec -it <toolbox-pod-name> -- gitlab-rails runner "Feature.enable(:geo_secondary_proxy_separate_urls)"
```
1. Restart the Webservice pods on your secondary Geo site:
```shell
kubectl rollout restart deployment -l app=webservice
```
{{< /tab >}}
{{< /tabs >}}
### Disable secondary site HTTP proxying per site
If there are multiple secondary sites, you can disable HTTP proxying on each secondary site separately, by following these steps:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into each application node (serving user traffic directly) on your secondary Geo site
and add the following environment variable:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
```ruby
gitlab_workhorse['env'] = {
"GEO_SECONDARY_PROXY" => "0"
}
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
You can use `--set gitlab.webservice.extraEnv.GEO_SECONDARY_PROXY="0"`,
or specify the following in your values file:
```yaml
gitlab:
webservice:
extraEnv:
GEO_SECONDARY_PROXY: "0"
```
{{< /tab >}}
{{< /tabs >}}
### Disable secondary site Git proxying
It is not possible to disable forwarding of:
- Git push over SSH
- Git pull over SSH when the Git repository is out-of-date on the secondary site
- Git push over HTTP
- Git pull over HTTP when the Git repository is out-of-date on the secondary site
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Geo proxying for secondary sites
breadcrumbs:
- doc
- administration
- geo
- secondary_proxy
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- HTTP proxying for secondary sites with separate URLs [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/346112) in GitLab 14.5 [with a flag](../../feature_flags/_index.md) named `geo_secondary_proxy_separate_urls`. Disabled by default.
- [Enabled on GitLab.com, GitLab Self-Managed, and GitLab Dedicated](https://gitlab.com/gitlab-org/gitlab/-/issues/346112) in GitLab 15.1.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
The `geo_secondary_proxy_separate_urls` feature flag is planned to be deprecated and removed in a future release.
Support for read-only Geo secondary sites is proposed in [issue 366810](https://gitlab.com/gitlab-org/gitlab/-/issues/366810).
{{< /alert >}}
Secondary sites behave as full read-write GitLab instances. They transparently proxy all operations to the primary site, with [some notable exceptions](#features-accelerated-by-secondary-geo-sites).
This behavior enables use-cases including:
- Putting all Geo sites behind a single URL, to deliver a consistent, seamless, and comprehensive experience whichever site the user lands on. Users don't need to juggle multiple GitLab URLs.
- Geographically load-balancing traffic without worrying about write access.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Geo proxying for secondary sites](https://www.youtube.com/watch?v=TALLy7__Na8).
<!-- Video published on 2022-01-26 -->
For known issues, see [proxying-related items in the Geo documentation](../_index.md#known-issues).
## Set up a unified URL for Geo sites
Secondary sites can transparently serve read-write traffic. Therefore, you can
use a single external URL so that requests can hit either the primary Geo site
or any secondary Geo sites. This delivers a consistent, seamless, and
comprehensive experience whichever site the user lands on. Users don't need to
juggle multiple URLs or even be aware of the idea of multiple sites.
You can route traffic to Geo sites with:
- Geo-location aware DNS. To route traffic to the closest Geo site, whether primary or secondary. For an example, follow [Configure location-aware DNS](#configure-location-aware-dns).
- Round-robin DNS.
- A load-balancer. It must use sticky sessions to avoid authentication failures and cross-site request errors. DNS routing is inherently sticky so it does not share this caveat.
### Configure location-aware DNS
Follow this example to route traffic to the closest Geo site, whether primary or secondary.
#### Prerequisites
This example creates a `gitlab.example.com` subdomain that automatically directs
requests:
- From Europe to a **secondary** site.
- From all other locations to the **primary** site.
For this example, you need:
- A working Geo **primary** site and **secondary** site, see the [Geo setup instructions](../setup/_index.md).
- A DNS zone managing your domain. Although the following instructions use
[AWS Route53](https://aws.amazon.com/route53/)
and [GCP cloud DNS](https://cloud.google.com/dns/), other services such as
[Cloudflare](https://www.cloudflare.com/) can be used as well.
#### AWS Route53
In this example, you use a Route53 Hosted Zone managing your domain for the Route53 setup.
In a Route53 Hosted Zone, traffic policies can be used to set up a variety of
routing configurations. To create a traffic policy:
1. Go to the
[Route53 dashboard](https://console.aws.amazon.com/route53/home) and select
**Traffic policies**.
1. Select **Create traffic policy**.
1. Fill in the **Policy Name** field with `Single Git Host` and select **Next**.
1. Leave **DNS type** as `A: IP Address in IPv4 format`.
1. Select **Connect to**, then select **Geolocation rule**.
1. For the first **Location**:
1. Leave it as `Default`.
1. Select **Connect to**, then select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **primary** IP address>`.
1. For the second **Location**:
1. Choose `Europe`.
1. Select **Connect to**, then select **New endpoint**.
1. Choose **Type** `value` and fill it in with `<your **secondary** IP address>`.

1. Select **Create traffic policy**.
1. Fill in **Policy record DNS name** with `gitlab`.

1. Select **Create policy records**.
You have successfully set up a single host, like `gitlab.example.com`, which
distributes traffic to your Geo sites by geolocation.
#### GCP
In this example, you create a GCP Cloud DNS zone managing your domain.
When creating Geo-Based record sets, GCP applies a nearest match for the source region when the source of the traffic doesn't match any policy items exactly. To create a Geo-Based record set:
1. Select **Network Services** > **Cloud DNS**.
1. Select the Zone configured for your domain.
1. Select **Add Record Set**.
1. Enter the DNS Name for your Location-aware public URL, for example, `gitlab.example.com`.
1. Select the **Routing Policy**: **Geo-Based**.
1. Select **Add Managed RRData**.
1. Select **Source Region**: **us-central1**.
1. Enter your `<**primary** IP address>`.
1. Select **Done**.
1. Select **Add Managed RRData**.
1. Select **Source Region**: **europe-west1**.
1. Enter your `<**secondary** IP address>`.
1. Select **Done**.
1. Select **Create**.
You have successfully set up a single host, like `gitlab.example.com`, which
distributes traffic to your Geo sites using a location-aware URL.
### Configure each site to use the same external URL
After you have set up routing from a single URL to all of your Geo sites, follow
the following steps if your sites use different URLs:
1. On each GitLab site, SSH into **each** node running Rails (Puma, Sidekiq, Log-Cursor)
and set the `external_url` to that of the single URL:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. To match the new external URL set on the secondary Geo sites, the primary database
needs to reflect this change.
In the Geo administration page of the **primary** site, edit each Geo secondary that
is using the secondary proxying and set the `URL` field to the single URL.
Make sure the primary site is also using this URL.
To allow the sites to talk to each other, [make sure the `Internal URL` field is unique for each site](../../geo_sites.md#set-up-the-internal-urls).
In Kubernetes, you can [use the same domain under `global.hosts.domain` as for the primary site](https://docs.gitlab.com/charts/advanced/geo/).
## Set up a separate URL for a secondary Geo site
You can use different external URLs per site. You can use this to offer a specific site to a specific set of users. Alternatively, you can give users control over which site they use, though they must understand the implications of their choice.
{{< alert type="note" >}}
GitLab does not support multiple external URLs, see [issue 21319](https://gitlab.com/gitlab-org/gitlab/-/issues/21319). An inherent problem is there are many cases where a site needs to produce an absolute URL outside of the context of an HTTP request, such as when sending emails that were not triggered by a request.
{{< /alert >}}
### Configure a secondary Geo site to a different external URL than the primary site
If your secondary site uses the same external URL as the primary site,
but you want to change it to use a different URL:
1. On the secondary site, SSH into **each** node running Rails (Puma, Sidekiq, Log-Cursor)
and set the `external_url` to the desired URL for the secondary site:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. To match the new external URL set on the secondary Geo site, the primary database
needs to reflect this change.
In the Geo administration page of the **primary** site, edit the target secondary site and set the `URL` field to the desired URL.
To allow the sites to talk to each other, [make sure the `Internal URL` field is unique for each site](../../geo_sites.md#set-up-the-internal-urls). If the desired URL is unique to this site, then you can clear the `Internal URL` field. On save, it defaults to the external URL.
## Behavior of secondary sites when the primary Geo site is down
Considering that web traffic is proxied to the primary, the behavior of the secondary sites differs when the primary
site is inaccessible:
- UI and API traffic return the same errors as the primary (or fail if the primary is not accessible at all) because they are proxied.
- For repositories that are fully up-to-date on the specific secondary site being accessed, Git read operations still work as expected,
including authentication through HTTP(s) or SSH. However, Git reads performed by GitLab Runners will fail.
- Git operations for repositories that are not replicated to the secondary site return the same errors
as the primary site because they are proxied.
- All Git write operations return the same errors as the primary site because they are proxied.
## Features accelerated by secondary Geo sites
Most HTTP traffic sent to a secondary Geo site is proxied to the primary Geo site. With this architecture,
secondary Geo sites are able to support write requests, and avoid read-after-write problems. Certain
**read** requests are handled locally by secondary sites for improved latency and bandwidth nearby.
The following table details the components tested through the Geo secondary site Workhorse proxy.
It does not cover all data types.
In this context, accelerated reads refer to read requests served from the secondary site, provided that the data is up to date for the component on the secondary site. If the data on the secondary site is determined to be out of date, the request is forwarded to the primary site. Read requests for components not listed in the table below are always automatically forwarded to the primary site.
| Feature / component | Accelerated reads? | Notes |
|:----------------------------------------------------|:-------------------------------------|-------|
| Project, wiki, design repository (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Project, wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| Project, Personal Snippet (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Project, Personal Snippet (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| Group wiki repository (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Group wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the local secondary while pushes get proxied to the primary. Selective sync or cases where repositories don't exist locally on the Geo secondary throw a "not found" error. |
| User uploads | {{< icon name="dotted-circle" >}} No | |
| LFS objects (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| LFS objects (using Git) | {{< icon name="check-circle" >}} Yes | |
| Pages | {{< icon name="dotted-circle" >}} No | Pages can use the same URL (without access control), but must be configured separately and are not proxied. |
| Advanced search (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Container registry | {{< icon name="dotted-circle" >}} No | The container registry is only recommended for Disaster Recovery scenarios. If the secondary site's container registry is not up to date, the read request is served with old data as the request is not forwarded to the primary site. Accelerating the container registry is planned, upvote or comment in the [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) to indicate your interest or ask your GitLab representative to do so on your behalf. |
| Dependency Proxy | {{< icon name="dotted-circle" >}} No | Read requests to a Geo secondary site's Dependency Proxy are always proxied to the primary site. |
| All other data | {{< icon name="dotted-circle" >}} No | Read requests for components not listed in this table are always automatically forwarded to the primary site. |
To request acceleration of a feature, check if an issue already exists in [epic 8239](https://gitlab.com/groups/gitlab-org/-/epics/8239) and upvote or comment on it to indicate your interest or ask your GitLab representative to do so on your behalf. If an applicable issue doesn't exist, open one and mention it in the epic.
## Disable secondary site HTTP proxying
Secondary site HTTP proxying is enabled by default on a secondary site when it uses a unified URL, meaning, it is configured with the same `external_url` as the primary site. Disabling proxying in this case tends not to be helpful due to completely different behavior being served at the same URL, depending on routing. When HTTP proxying is disabled on a secondary Geo site, the site operates in read-only mode, with several important limitations you should be aware of.
### What happens if you disable secondary proxying
Disabling the proxying feature flag has the following general effects.
#### HTTP and Git requests
- The secondary site does not proxy HTTP requests to the primary site. Instead, it attempts to serve them itself, or fail.
- Git requests generally succeed. Git pushes are redirected or proxied to the primary site.
- Other than Git requests, any HTTP request which may write data fails. Read requests generally succeed.
- The secondary site UI shows a banner: 
| Feature / component | Succeed | Notes |
|:----------------------------------------------------|:----------------------------------------|-------|
| Project, wiki, design repository (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Project, wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Project, Personal Snippet (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Project, Personal Snippet (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Group wiki repository (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| Group wiki repository (using Git) | {{< icon name="check-circle" >}} Yes | Git reads are served from the locally stored data, while pushes get proxied to the primary. If a repository doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| User uploads | {{< icon name="dotted-circle" >}} Maybe | Upload files are served from the locally stored data. Attempting to upload a file on a secondary causes an error. |
| LFS objects (using the web UI) | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
| LFS objects (using Git) | {{< icon name="check-circle" >}} Yes | LFS objects are served from the locally stored data, while pushes get proxied to the primary. If an LFS object doesn't exist locally on the Geo secondary, for example due to exclusion by selective sync, it causes a "not found" error. |
| Pages | {{< icon name="dotted-circle" >}} Maybe | Pages can use the same URL (without access control), but must be configured separately and are not proxied. |
| Advanced search (using the web UI) | {{< icon name="dotted-circle" >}} No | |
| Container registry | {{< icon name="dotted-circle" >}} No | The container registry is only recommended for Disaster Recovery scenarios. If the secondary site's container registry is not up to date, the read request is served with old data as the request is not forwarded to the primary site. Accelerating the container registry is planned, upvote or comment in the [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/365864) to indicate your interest or ask your GitLab representative to do so on your behalf. |
| Dependency Proxy | {{< icon name="dotted-circle" >}} No | |
| All other data | {{< icon name="dotted-circle" >}} Maybe | Reads are served from the locally stored data. Writes cause an error. |
You should use the feature flag over using the `GEO_SECONDARY_PROXY` environment variable.
HTTP proxying is enabled by default in GitLab 15.1 on a secondary site even without a unified URL.
#### Terms of service acceptance
When proxying is disabled, users who access only the secondary site cannot properly accept terms of service or other legal agreements. This creates the following issues:
- **No record of acceptance**: If an employee only logs into the secondary site, their acceptance of terms and conditions is not recorded in the primary database because write operations (including terms acceptance) are not proxied when secondary proxying is disabled, even though they may be presented with the terms message.
- **Legal compliance concerns**: Organizations may lack proper legal coverage if employees use GitLab services through a secondary-only access pattern, since there's no verifiable record of their agreement to the terms and conditions.
As a workaround, you must access the primary site at least once to properly accept terms and conditions. After accepted on the primary, this information is replicated to secondary sites through normal Geo synchronization.
{{< alert type="note" >}}
This limitation affects organizations that require documented acceptance of terms and conditions for compliance or legal purposes. Ensure users have access to the primary site for the initial terms acceptance.
{{< /alert >}}
### Disable proxy on all secondary sites
If you need to disable proxying on all secondary sites, it is easiest to disable the feature flag:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into a node which is running Puma or Sidekiq on your primary Geo site and run:
```shell
sudo gitlab-rails runner "Feature.disable(:geo_secondary_proxy_separate_urls)"
```
1. Restart Puma on all nodes which are running it on your secondary Geo site:
```shell
sudo gitlab-ctl restart puma
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. On your primary Geo site, run this command in the Toolbox pod:
```shell
kubectl exec -it <toolbox-pod-name> -- gitlab-rails runner "Feature.disable(:geo_secondary_proxy_separate_urls)"
```
1. Restart the Webservice pods on your secondary Geo site:
```shell
kubectl rollout restart deployment -l app=webservice
```
{{< /tab >}}
{{< /tabs >}}
To revert the changes so secondary site proxying is enabled again:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into a node which is running Puma or Sidekiq on your primary Geo site and run:
```shell
sudo gitlab-rails runner "Feature.enable(:geo_secondary_proxy_separate_urls)"
```
1. Restart Puma on all nodes which are running it on your secondary Geo site:
```shell
sudo gitlab-ctl restart puma
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. On your primary Geo site, run this command in the Toolbox pod:
```shell
kubectl exec -it <toolbox-pod-name> -- gitlab-rails runner "Feature.enable(:geo_secondary_proxy_separate_urls)"
```
1. Restart the Webservice pods on your secondary Geo site:
```shell
kubectl rollout restart deployment -l app=webservice
```
{{< /tab >}}
{{< /tabs >}}
### Disable secondary site HTTP proxying per site
If there are multiple secondary sites, you can disable HTTP proxying on each secondary site separately, by following these steps:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. SSH into each application node (serving user traffic directly) on your secondary Geo site
and add the following environment variable:
```shell
sudo -e /etc/gitlab/gitlab.rb
```
```ruby
gitlab_workhorse['env'] = {
"GEO_SECONDARY_PROXY" => "0"
}
```
1. Reconfigure the updated nodes for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
You can use `--set gitlab.webservice.extraEnv.GEO_SECONDARY_PROXY="0"`,
or specify the following in your values file:
```yaml
gitlab:
webservice:
extraEnv:
GEO_SECONDARY_PROXY: "0"
```
{{< /tab >}}
{{< /tabs >}}
### Disable secondary site Git proxying
It is not possible to disable forwarding of:
- Git push over SSH
- Git pull over SSH when the Git repository is out-of-date on the secondary site
- Git push over HTTP
- Git pull over HTTP when the Git repository is out-of-date on the secondary site
|
https://docs.gitlab.com/administration/fast_ssh_key_lookup
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/fast_ssh_key_lookup.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
fast_ssh_key_lookup.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Fast lookup of SSH keys
|
Configure a faster SSH authorization method for GitLab instances with many users.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When the number of users grows, SSH operations become slow because OpenSSH performs a
linear search through the `authorized_keys` file to authenticate users.
This process requires significant time and disk I/O, which delays users attempting to
push or pull to a repository.
If users add or remove keys frequently, the operating system may not cache the
`authorized_keys` file, which causes repeated disk reads.
Instead of using the `authorized_keys` file, you can configure GitLab Shell to look up
SSH keys. It is faster because the lookup is indexed in the GitLab database.
{{< alert type="note" >}}
For standard (non-deploy key) users, consider using [SSH certificates](ssh_certificates.md).
They are faster than database lookups, but are not a drop-in replacement for the `authorized_keys` file.
{{< /alert >}}
## Fast lookup is required for Geo
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Unlike [Cloud Native GitLab](https://docs.gitlab.com/charts/), by default Linux package installations
manage an `authorized_keys` file that is located in the `git` user's home directory. For most installations,
this file is located under `/var/opt/gitlab/.ssh/authorized_keys`. Use this command to locate the
`authorized_keys` on your system:
```shell
getent passwd git | cut -d: -f6 | awk '{print $1"/.ssh/authorized_keys"}'
```
The `authorized_keys` file contains all the public SSH keys for users allowed to access GitLab. However, to maintain a
single source of truth, [Geo](../geo/_index.md) must be configured to perform SSH fingerprint
lookups with database lookup.
When you [set up Geo](../geo/setup/_index.md), you must follow the steps below
for both the primary and secondary nodes. Do not select **Write to `authorized keys` file** on the
primary node, because it is reflected automatically on the secondary if database replication is working.
## Set up fast lookup
GitLab Shell provides a way to authorize SSH users with a fast, indexed lookup
to the GitLab database. GitLab Shell uses the fingerprint of the SSH key to
check whether the user is authorized to access GitLab.
Fast lookup can be enabled with the following SSH servers:
- [`gitlab-sshd`](gitlab_sshd.md)
- OpenSSH
You can run both services simultaneously by using separate ports for each service.
### With `gitlab-sshd`
To set up `gitlab-sshd`, see [the `gitlab-sshd` documentation](gitlab_sshd.md).
After `gitlab-sshd` is enabled, GitLab Shell and `gitlab-sshd` are configured
to use fast lookup automatically.
### With OpenSSH
Prerequisites:
- OpenSSH 6.9 or later is required because `AuthorizedKeysCommand` must
accept a fingerprint. To check your version, run `sshd -V`.
To set up fast lookup with OpenSSH:
1. Add the following to your `sshd_config` file:
```plaintext
Match User git # Apply the AuthorizedKeysCommands to the git user only
AuthorizedKeysCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-keys-check git %u %k
AuthorizedKeysCommandUser git
Match all # End match, settings apply to all users again
```
This file is usually located in:
- Linux package installations: `/etc/ssh/sshd_config`
- Docker installations: `/assets/sshd_config`
- Self-compiled installations: If you followed the instructions for
[installing GitLab Shell from source](../../install/self_compiled/_index.md#install-gitlab-shell), the command should be
located at `/home/git/gitlab-shell/bin/gitlab-shell-authorized-keys-check`.
Consider creating a wrapper script somewhere else because this command must be owned by `root`,
and not be writable by a group or others.
Also consider changing the ownership of this command as needed, but this might require temporary
ownership changes during `gitlab-shell` upgrades.
1. Reload OpenSSH:
```shell
# Debian or Ubuntu installations
sudo service ssh reload
# CentOS installations
sudo service sshd reload
```
1. Confirm that SSH is working:
1. Comment out your user's key in the `authorized_keys` file. To do this, start the line with `#`.
1. From your local machine, attempt to pull a repository or run:
```shell
ssh -T git@gitlab.example.com
```
A successful pull or [welcome message](../../user/ssh.md#verify-that-you-can-connect)
means that GitLab found the key in the database because the key is not present in the file.
If there are lookup failures, the `authorized_keys` file is still scanned.
Git SSH performance might still be slow for many users, as long as the large file exists.
To resolve this, you can disable writes to the `authorized_keys` file:
1. Confirm SSH works. This step is important because otherwise the file quickly becomes out-of-date.
1. Disable writes to the `authorized_keys` file:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Network**.
1. Expand **Performance optimization**.
1. Clear the **Use `authorized_keys` file to authenticate SSH keys** checkbox.
1. Select **Save changes**.
1. Verify the change:
1. Remove your SSH key in the UI.
1. Add a new key.
1. Try to pull a repository.
1. Back up and delete your `authorized_keys` file.
The current users' keys are already present in the database, so there is no need for migration
or for users to re-add their keys.
### How to go back to using the `authorized_keys` file
This overview is brief. Refer to the previous instructions for more context.
1. Enable writes to the `authorized_keys` file.
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings > Network**.
1. Expand **Performance optimization**.
1. Select the **Use `authorized_keys` file to authenticate SSH keys** checkbox.
1. [Rebuild the `authorized_keys` file](../raketasks/maintenance.md#rebuild-authorized_keys-file).
1. Remove the `AuthorizedKeysCommand` lines from `/etc/ssh/sshd_config` or from `/assets/sshd_config` if you are using Docker
from a Linux package installation.
1. Reload `sshd`: `sudo service sshd reload`.
## SELinux support
GitLab supports `authorized_keys` database lookups with [SELinux](https://en.wikipedia.org/wiki/Security-Enhanced_Linux).
Because the SELinux policy is static, GitLab doesn't support changing
internal web server ports. Administrators would have to create a special `.te`
file for the environment because it isn't generated dynamically.
### Additional documentation
Additional technical documentation for `gitlab-sshd` may be found in the
GitLab Shell documentation.
## Troubleshooting
### SSH traffic slow or high CPU load
If your SSH traffic is [slow](https://github.com/linux-pam/linux-pam/issues/270)
or causing high CPU load:
- Check the size of `/var/log/btmp`.
- Ensure it is rotated on a regular basis, or after reaching a certain size.
If this file is very large, GitLab SSH fast lookup can cause the bottleneck to be hit more frequently,
thus decreasing performance even further. Consider disabling
[`UsePAM` in your `sshd_config`](https://linux.die.net/man/5/sshd_config) to avoid reading `/var/log/btmp` altogether.
Running `strace` and `lsof` on a running `sshd: git` process returns debugging information.
To get an `strace` on an in-progress Git over SSH connection for IP `x.x.x.x`, run:
```plaintext
sudo strace -s 10000 -p $(sudo netstat -tp | grep x.x.x.x | egrep 'ssh.*: git' | sed -e 's/.*ESTABLISHED *//' -e 's#/.*##')
```
Or get an `lsof` for a running Git over SSH process:
```plaintext
sudo lsof -p $(sudo netstat -tp | egrep 'ssh.*: git' | head -1 | sed -e 's/.*ESTABLISHED *//' -e 's#/.*##')
```
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
description: Configure a faster SSH authorization method for GitLab instances with
many users.
title: Fast lookup of SSH keys
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When the number of users grows, SSH operations become slow because OpenSSH performs a
linear search through the `authorized_keys` file to authenticate users.
This process requires significant time and disk I/O, which delays users attempting to
push or pull to a repository.
If users add or remove keys frequently, the operating system may not cache the
`authorized_keys` file, which causes repeated disk reads.
Instead of using the `authorized_keys` file, you can configure GitLab Shell to look up
SSH keys. It is faster because the lookup is indexed in the GitLab database.
{{< alert type="note" >}}
For standard (non-deploy key) users, consider using [SSH certificates](ssh_certificates.md).
They are faster than database lookups, but are not a drop-in replacement for the `authorized_keys` file.
{{< /alert >}}
## Fast lookup is required for Geo
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Unlike [Cloud Native GitLab](https://docs.gitlab.com/charts/), by default Linux package installations
manage an `authorized_keys` file that is located in the `git` user's home directory. For most installations,
this file is located under `/var/opt/gitlab/.ssh/authorized_keys`. Use this command to locate the
`authorized_keys` on your system:
```shell
getent passwd git | cut -d: -f6 | awk '{print $1"/.ssh/authorized_keys"}'
```
The `authorized_keys` file contains all the public SSH keys for users allowed to access GitLab. However, to maintain a
single source of truth, [Geo](../geo/_index.md) must be configured to perform SSH fingerprint
lookups with database lookup.
When you [set up Geo](../geo/setup/_index.md), you must follow the steps below
for both the primary and secondary nodes. Do not select **Write to `authorized keys` file** on the
primary node, because it is reflected automatically on the secondary if database replication is working.
## Set up fast lookup
GitLab Shell provides a way to authorize SSH users with a fast, indexed lookup
to the GitLab database. GitLab Shell uses the fingerprint of the SSH key to
check whether the user is authorized to access GitLab.
Fast lookup can be enabled with the following SSH servers:
- [`gitlab-sshd`](gitlab_sshd.md)
- OpenSSH
You can run both services simultaneously by using separate ports for each service.
### With `gitlab-sshd`
To set up `gitlab-sshd`, see [the `gitlab-sshd` documentation](gitlab_sshd.md).
After `gitlab-sshd` is enabled, GitLab Shell and `gitlab-sshd` are configured
to use fast lookup automatically.
### With OpenSSH
Prerequisites:
- OpenSSH 6.9 or later is required because `AuthorizedKeysCommand` must
accept a fingerprint. To check your version, run `sshd -V`.
To set up fast lookup with OpenSSH:
1. Add the following to your `sshd_config` file:
```plaintext
Match User git # Apply the AuthorizedKeysCommands to the git user only
AuthorizedKeysCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-keys-check git %u %k
AuthorizedKeysCommandUser git
Match all # End match, settings apply to all users again
```
This file is usually located in:
- Linux package installations: `/etc/ssh/sshd_config`
- Docker installations: `/assets/sshd_config`
- Self-compiled installations: If you followed the instructions for
[installing GitLab Shell from source](../../install/self_compiled/_index.md#install-gitlab-shell), the command should be
located at `/home/git/gitlab-shell/bin/gitlab-shell-authorized-keys-check`.
Consider creating a wrapper script somewhere else because this command must be owned by `root`,
and not be writable by a group or others.
Also consider changing the ownership of this command as needed, but this might require temporary
ownership changes during `gitlab-shell` upgrades.
1. Reload OpenSSH:
```shell
# Debian or Ubuntu installations
sudo service ssh reload
# CentOS installations
sudo service sshd reload
```
1. Confirm that SSH is working:
1. Comment out your user's key in the `authorized_keys` file. To do this, start the line with `#`.
1. From your local machine, attempt to pull a repository or run:
```shell
ssh -T git@gitlab.example.com
```
A successful pull or [welcome message](../../user/ssh.md#verify-that-you-can-connect)
means that GitLab found the key in the database because the key is not present in the file.
If there are lookup failures, the `authorized_keys` file is still scanned.
Git SSH performance might still be slow for many users, as long as the large file exists.
To resolve this, you can disable writes to the `authorized_keys` file:
1. Confirm SSH works. This step is important because otherwise the file quickly becomes out-of-date.
1. Disable writes to the `authorized_keys` file:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Network**.
1. Expand **Performance optimization**.
1. Clear the **Use `authorized_keys` file to authenticate SSH keys** checkbox.
1. Select **Save changes**.
1. Verify the change:
1. Remove your SSH key in the UI.
1. Add a new key.
1. Try to pull a repository.
1. Back up and delete your `authorized_keys` file.
The current users' keys are already present in the database, so there is no need for migration
or for users to re-add their keys.
### How to go back to using the `authorized_keys` file
This overview is brief. Refer to the previous instructions for more context.
1. Enable writes to the `authorized_keys` file.
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings > Network**.
1. Expand **Performance optimization**.
1. Select the **Use `authorized_keys` file to authenticate SSH keys** checkbox.
1. [Rebuild the `authorized_keys` file](../raketasks/maintenance.md#rebuild-authorized_keys-file).
1. Remove the `AuthorizedKeysCommand` lines from `/etc/ssh/sshd_config` or from `/assets/sshd_config` if you are using Docker
from a Linux package installation.
1. Reload `sshd`: `sudo service sshd reload`.
## SELinux support
GitLab supports `authorized_keys` database lookups with [SELinux](https://en.wikipedia.org/wiki/Security-Enhanced_Linux).
Because the SELinux policy is static, GitLab doesn't support changing
internal web server ports. Administrators would have to create a special `.te`
file for the environment because it isn't generated dynamically.
### Additional documentation
Additional technical documentation for `gitlab-sshd` may be found in the
GitLab Shell documentation.
## Troubleshooting
### SSH traffic slow or high CPU load
If your SSH traffic is [slow](https://github.com/linux-pam/linux-pam/issues/270)
or causing high CPU load:
- Check the size of `/var/log/btmp`.
- Ensure it is rotated on a regular basis, or after reaching a certain size.
If this file is very large, GitLab SSH fast lookup can cause the bottleneck to be hit more frequently,
thus decreasing performance even further. Consider disabling
[`UsePAM` in your `sshd_config`](https://linux.die.net/man/5/sshd_config) to avoid reading `/var/log/btmp` altogether.
Running `strace` and `lsof` on a running `sshd: git` process returns debugging information.
To get an `strace` on an in-progress Git over SSH connection for IP `x.x.x.x`, run:
```plaintext
sudo strace -s 10000 -p $(sudo netstat -tp | grep x.x.x.x | egrep 'ssh.*: git' | sed -e 's/.*ESTABLISHED *//' -e 's#/.*##')
```
Or get an `lsof` for a running Git over SSH process:
```plaintext
sudo lsof -p $(sudo netstat -tp | egrep 'ssh.*: git' | head -1 | sed -e 's/.*ESTABLISHED *//' -e 's#/.*##')
```
|
https://docs.gitlab.com/administration/moving_repositories
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/moving_repositories.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
moving_repositories.md
|
Data Access
|
Gitaly
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Moving repositories managed by GitLab
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can move all repositories managed by GitLab to another file system or another server.
## Moving data in a GitLab instance
The GitLab API is the recommended way to move Git repositories:
- Between servers.
- Between different storages.
- From single-node Gitaly to Gitaly Cluster (Praefect).
For more information, see:
- [Configuring additional storage for Gitaly](../gitaly/configure_gitaly.md#network-architecture). This
example configures additional storage called `storage1` and `storage2`.
- [The API documentation](../../api/project_repository_storage_moves.md) details the endpoints for
querying and scheduling project repository moves.
- [The API documentation](../../api/snippet_repository_storage_moves.md) details the endpoints for
querying and scheduling snippet repository moves.
- [The API documentation](../../api/group_repository_storage_moves.md) details the endpoints for
querying and scheduling group repository moves.
- [Migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
### Moving Repositories
GitLab repositories can be associated with projects, groups, and snippets. Each of these types
has a separate API to schedule the respective repositories to move. To move all repositories
on a GitLab instance, each of these types must be scheduled to move for each storage.
Each repository is made read-only for the duration of the move. The repository is not writable
until the move has completed.
To move repositories:
1. Ensure all [local and cluster storages](../gitaly/configure_gitaly.md#mixed-configuration) are accessible to the GitLab instance. In
this example, these are `<original_storage_name>` and `<cluster_storage_name>`.
1. [Configure repository storage weights](../repository_storage_paths.md#configure-where-new-repositories-are-stored)
so that the new storages receives all new projects. This stops new projects from being created
on existing storages while the migration is in progress.
1. Schedule repository moves for:
- [All projects](#move-all-projects) or
[individual projects](../../api/project_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-project).
- [All snippets](#move-all-snippets) or
[individual snippets](../../api/snippet_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-snippet).
- [All groups](#move-all-groups) or
[individual groups](../../api/group_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-group).
1. If [Geo](../geo/_index.md) is enabled,
[resync all repositories](../geo/replication/troubleshooting/synchronization_verification.md#resync-all-resources-of-one-component).
#### Move all projects
To move all projects by using the API:
1. [Schedule repository storage moves for all projects on a storage shard](../../api/project_repository_storage_moves.md#schedule-repository-storage-moves-for-all-projects-on-a-storage-shard)
using the API. For example:
```shell
curl --request POST --header "Private-Token: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/project_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/project_repository_storage_moves.md#retrieve-all-project-repository-storage-moves)
using the API. The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use the API to [query projects](../../api/projects.md#list-all-projects) and confirm that all projects have moved. None of the projects should be returned with the
`repository_storage` field set to the old storage. For example:
```shell
curl --header "Private-Token: <your_access_token>" --header "Content-Type: application/json" \
"https://gitlab.example.com/api/v4/projects?repository_storage=<original_storage_name>"
```
Alternatively use [the rails console](rails_console.md) to confirm that all
projects have moved. Run the following in the rails console:
```ruby
ProjectRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
#### Move all snippets
To move all snippets by using the API:
1. [Schedule repository storage moves for all snippets on a storage shard](../../api/snippet_repository_storage_moves.md#schedule-repository-storage-moves-for-all-snippets-on-a-storage-shard). For example:
```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/snippet_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/snippet_repository_storage_moves.md#retrieve-all-snippet-repository-storage-moves).
The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use [the rails console](rails_console.md) to confirm
that all snippets have moved. No snippets should be returned for the original storage. Run the
following in the rails console:
```ruby
SnippetRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
#### Move all groups
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To move all groups by using the API:
1. [Schedule repository storage moves for all groups on a storage shard](../../api/group_repository_storage_moves.md#schedule-repository-storage-moves-for-all-groups-on-a-storage-shard).
For example:
```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/group_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/group_repository_storage_moves.md#retrieve-all-group-repository-storage-moves).
The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use [the rails console](rails_console.md) to confirm
that all groups have moved. No groups should be returned for the original storage. Run the
following in the rails console:
```ruby
GroupWikiRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
## Migrating to another GitLab instance
[Using the API](#moving-data-in-a-gitlab-instance) isn't an option if you are migrating to a new
GitLab environment, for example:
- From a single-node GitLab to a scaled-out architecture.
- From a GitLab instance in your private data center to a cloud provider.
The rest of the document looks
at some of the ways you can copy all your repositories from
`/var/opt/gitlab/git-data/repositories` to `/mnt/gitlab/repositories`.
We look at three scenarios:
- The target directory is empty.
- The target directory contains an outdated copy of the repositories.
- How to deal with thousands of repositories.
{{< alert type="warning" >}}
Each of the approaches we list can or does overwrite data in the target directory
`/mnt/gitlab/repositories`. Do not mix up the source and the target.
{{< /alert >}}
### Recommended approach in all cases
For either Gitaly or Gitaly Cluster (Praefect) targets, the GitLab [backup and restore capability](../backup_restore/_index.md)
should be used. Git repositories are accessed, managed, and stored on GitLab servers by Gitaly as a database. Data loss
can result from directly accessing and copying Gitaly files using tools like `rsync`.
- Backup performance can be improved by
[processing multiple repositories concurrently](../backup_restore/backup_gitlab.md#back-up-git-repositories-concurrently).
- Backups can be created of just the repositories using the
[skip feature](../backup_restore/backup_gitlab.md#excluding-specific-data-from-the-backup).
No other method works for Gitaly Cluster (Praefect) targets.
### Target directory is empty: use a `tar` pipe
For Gitaly targets, if the target directory `/mnt/gitlab/repositories` is empty, use a `tar` pipe. This method has low overhead and `tar` is usually pre-installed on your system.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases) instead.
However, it is not possible to resume an interrupted `tar` pipe; if that happens then all data must be copied again.
```shell
sudo -u git sh -c 'tar -C /var/opt/gitlab/git-data/repositories -cf - -- . |\
tar -C /mnt/gitlab/repositories -xf -'
```
If you want to see progress, replace `-xf` with `-xvf`.
#### `tar` pipe to another server
For Gitaly targets, you can use a `tar` pipe to copy data to another server. If your `git` user has SSH access to the new server as `git@newserver`, you can pipe the data through SSH.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
```shell
sudo -u git sh -c 'tar -C /var/opt/gitlab/git-data/repositories -cf - -- . |\
ssh git@newserver tar -C /mnt/gitlab/repositories -xf -'
```
If you want to compress the data before it goes over the network
(which costs you CPU cycles) you can replace `ssh` with `ssh -C`.
### The target directory contains an outdated copy of the repositories: use `rsync`
{{< alert type="warning" >}}
Using `rsync` to migrate Git data can cause data loss and repository corruption.
[These instructions are being reviewed](https://gitlab.com/gitlab-org/gitlab/-/issues/270422).
{{< /alert >}}
If the target directory already contains a partial or outdated copy of the repositories, copying all the data again with `tar` is inefficient. For Gitaly targets, use `rsync` instead.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
This utility is either already installed on your system, or installable using `apt` or `yum`.
```shell
sudo -u git sh -c 'rsync -a --delete /var/opt/gitlab/git-data/repositories/. \
/mnt/gitlab/repositories'
```
The `/.` in the previous command is very important, without it you can
get the wrong directory structure in the target directory.
If you want to see progress, replace `-a` with `-av`.
#### Single `rsync` to another server
{{< alert type="warning" >}}
Using `rsync` to migrate Git data can cause data loss and repository corruption.
[These instructions are being reviewed](https://gitlab.com/gitlab-org/gitlab/-/issues/270422).
{{< /alert >}}
For Gitaly targets, you can send the repositories over the network with `rsync` if the `git` user on your source system has SSH access to the target server.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
```shell
sudo -u git sh -c 'rsync -a --delete /var/opt/gitlab/git-data/repositories/. \
git@newserver:/mnt/gitlab/repositories'
```
|
---
stage: Data Access
group: Gitaly
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Moving repositories managed by GitLab
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can move all repositories managed by GitLab to another file system or another server.
## Moving data in a GitLab instance
The GitLab API is the recommended way to move Git repositories:
- Between servers.
- Between different storages.
- From single-node Gitaly to Gitaly Cluster (Praefect).
For more information, see:
- [Configuring additional storage for Gitaly](../gitaly/configure_gitaly.md#network-architecture). This
example configures additional storage called `storage1` and `storage2`.
- [The API documentation](../../api/project_repository_storage_moves.md) details the endpoints for
querying and scheduling project repository moves.
- [The API documentation](../../api/snippet_repository_storage_moves.md) details the endpoints for
querying and scheduling snippet repository moves.
- [The API documentation](../../api/group_repository_storage_moves.md) details the endpoints for
querying and scheduling group repository moves.
- [Migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
### Moving Repositories
GitLab repositories can be associated with projects, groups, and snippets. Each of these types
has a separate API to schedule the respective repositories to move. To move all repositories
on a GitLab instance, each of these types must be scheduled to move for each storage.
Each repository is made read-only for the duration of the move. The repository is not writable
until the move has completed.
To move repositories:
1. Ensure all [local and cluster storages](../gitaly/configure_gitaly.md#mixed-configuration) are accessible to the GitLab instance. In
this example, these are `<original_storage_name>` and `<cluster_storage_name>`.
1. [Configure repository storage weights](../repository_storage_paths.md#configure-where-new-repositories-are-stored)
so that the new storages receives all new projects. This stops new projects from being created
on existing storages while the migration is in progress.
1. Schedule repository moves for:
- [All projects](#move-all-projects) or
[individual projects](../../api/project_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-project).
- [All snippets](#move-all-snippets) or
[individual snippets](../../api/snippet_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-snippet).
- [All groups](#move-all-groups) or
[individual groups](../../api/group_repository_storage_moves.md#schedule-a-repository-storage-move-for-a-group).
1. If [Geo](../geo/_index.md) is enabled,
[resync all repositories](../geo/replication/troubleshooting/synchronization_verification.md#resync-all-resources-of-one-component).
#### Move all projects
To move all projects by using the API:
1. [Schedule repository storage moves for all projects on a storage shard](../../api/project_repository_storage_moves.md#schedule-repository-storage-moves-for-all-projects-on-a-storage-shard)
using the API. For example:
```shell
curl --request POST --header "Private-Token: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/project_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/project_repository_storage_moves.md#retrieve-all-project-repository-storage-moves)
using the API. The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use the API to [query projects](../../api/projects.md#list-all-projects) and confirm that all projects have moved. None of the projects should be returned with the
`repository_storage` field set to the old storage. For example:
```shell
curl --header "Private-Token: <your_access_token>" --header "Content-Type: application/json" \
"https://gitlab.example.com/api/v4/projects?repository_storage=<original_storage_name>"
```
Alternatively use [the rails console](rails_console.md) to confirm that all
projects have moved. Run the following in the rails console:
```ruby
ProjectRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
#### Move all snippets
To move all snippets by using the API:
1. [Schedule repository storage moves for all snippets on a storage shard](../../api/snippet_repository_storage_moves.md#schedule-repository-storage-moves-for-all-snippets-on-a-storage-shard). For example:
```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/snippet_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/snippet_repository_storage_moves.md#retrieve-all-snippet-repository-storage-moves).
The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use [the rails console](rails_console.md) to confirm
that all snippets have moved. No snippets should be returned for the original storage. Run the
following in the rails console:
```ruby
SnippetRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
#### Move all groups
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To move all groups by using the API:
1. [Schedule repository storage moves for all groups on a storage shard](../../api/group_repository_storage_moves.md#schedule-repository-storage-moves-for-all-groups-on-a-storage-shard).
For example:
```shell
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--data '{"source_storage_name":"<original_storage_name>","destination_storage_name":"<cluster_storage_name>"}' \
"https://gitlab.example.com/api/v4/group_repository_storage_moves"
```
1. [Query the most recent repository moves](../../api/group_repository_storage_moves.md#retrieve-all-group-repository-storage-moves).
The response indicates either:
- The moves have completed successfully. The `state` field is `finished`.
- The moves are in progress. Re-query the repository move until it completes successfully.
- The moves have failed. Most failures are temporary and are solved by rescheduling the move.
1. After the moves are complete, use [the rails console](rails_console.md) to confirm
that all groups have moved. No groups should be returned for the original storage. Run the
following in the rails console:
```ruby
GroupWikiRepository.for_repository_storage('<original_storage_name>')
```
1. Repeat for each storage as required.
## Migrating to another GitLab instance
[Using the API](#moving-data-in-a-gitlab-instance) isn't an option if you are migrating to a new
GitLab environment, for example:
- From a single-node GitLab to a scaled-out architecture.
- From a GitLab instance in your private data center to a cloud provider.
The rest of the document looks
at some of the ways you can copy all your repositories from
`/var/opt/gitlab/git-data/repositories` to `/mnt/gitlab/repositories`.
We look at three scenarios:
- The target directory is empty.
- The target directory contains an outdated copy of the repositories.
- How to deal with thousands of repositories.
{{< alert type="warning" >}}
Each of the approaches we list can or does overwrite data in the target directory
`/mnt/gitlab/repositories`. Do not mix up the source and the target.
{{< /alert >}}
### Recommended approach in all cases
For either Gitaly or Gitaly Cluster (Praefect) targets, the GitLab [backup and restore capability](../backup_restore/_index.md)
should be used. Git repositories are accessed, managed, and stored on GitLab servers by Gitaly as a database. Data loss
can result from directly accessing and copying Gitaly files using tools like `rsync`.
- Backup performance can be improved by
[processing multiple repositories concurrently](../backup_restore/backup_gitlab.md#back-up-git-repositories-concurrently).
- Backups can be created of just the repositories using the
[skip feature](../backup_restore/backup_gitlab.md#excluding-specific-data-from-the-backup).
No other method works for Gitaly Cluster (Praefect) targets.
### Target directory is empty: use a `tar` pipe
For Gitaly targets, if the target directory `/mnt/gitlab/repositories` is empty, use a `tar` pipe. This method has low overhead and `tar` is usually pre-installed on your system.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases) instead.
However, it is not possible to resume an interrupted `tar` pipe; if that happens then all data must be copied again.
```shell
sudo -u git sh -c 'tar -C /var/opt/gitlab/git-data/repositories -cf - -- . |\
tar -C /mnt/gitlab/repositories -xf -'
```
If you want to see progress, replace `-xf` with `-xvf`.
#### `tar` pipe to another server
For Gitaly targets, you can use a `tar` pipe to copy data to another server. If your `git` user has SSH access to the new server as `git@newserver`, you can pipe the data through SSH.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
```shell
sudo -u git sh -c 'tar -C /var/opt/gitlab/git-data/repositories -cf - -- . |\
ssh git@newserver tar -C /mnt/gitlab/repositories -xf -'
```
If you want to compress the data before it goes over the network
(which costs you CPU cycles) you can replace `ssh` with `ssh -C`.
### The target directory contains an outdated copy of the repositories: use `rsync`
{{< alert type="warning" >}}
Using `rsync` to migrate Git data can cause data loss and repository corruption.
[These instructions are being reviewed](https://gitlab.com/gitlab-org/gitlab/-/issues/270422).
{{< /alert >}}
If the target directory already contains a partial or outdated copy of the repositories, copying all the data again with `tar` is inefficient. For Gitaly targets, use `rsync` instead.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
This utility is either already installed on your system, or installable using `apt` or `yum`.
```shell
sudo -u git sh -c 'rsync -a --delete /var/opt/gitlab/git-data/repositories/. \
/mnt/gitlab/repositories'
```
The `/.` in the previous command is very important, without it you can
get the wrong directory structure in the target directory.
If you want to see progress, replace `-a` with `-av`.
#### Single `rsync` to another server
{{< alert type="warning" >}}
Using `rsync` to migrate Git data can cause data loss and repository corruption.
[These instructions are being reviewed](https://gitlab.com/gitlab-org/gitlab/-/issues/270422).
{{< /alert >}}
For Gitaly targets, you can send the repositories over the network with `rsync` if the `git` user on your source system has SSH access to the target server.
For Gitaly Cluster (Praefect) targets, use the [recommended approach](#recommended-approach-in-all-cases).
```shell
sudo -u git sh -c 'rsync -a --delete /var/opt/gitlab/git-data/repositories/. \
git@newserver:/mnt/gitlab/repositories'
```
|
https://docs.gitlab.com/administration/puma
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/puma.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
puma.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configure the bundled Puma instance of the GitLab package
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Puma is a fast, multi-threaded, and highly concurrent HTTP 1.1 server for
Ruby applications. It runs the core Rails application that provides the user-facing
features of GitLab.
## Reducing memory use
To reduce memory use, Puma forks worker processes. Each time a worker is created,
it shares memory with the primary process. The worker uses additional memory only
when it changes or adds to its memory pages. This can lead to Puma workers using
more physical memory over time as workers handle additional web requests. The amount of memory
used over time depends on the use of GitLab. The more features used by GitLab users,
the higher the expected memory use over time.
To stop uncontrolled memory growth, the GitLab Rails application runs a supervision thread
that automatically restarts workers if they exceed a given resident set size (RSS) threshold
for a certain amount of time.
GitLab sets a default of `1200Mb` for the memory limit. To override the default value,
set `per_worker_max_memory_mb` to the new RSS limit in megabytes:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['per_worker_max_memory_mb'] = 1024 # 1 GB
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
When workers are restarted, capacity to run GitLab is reduced for a short
period of time. Set `per_worker_max_memory_mb` to a higher value if workers are replaced too often.
Worker count is calculated based on CPU cores. A small GitLab deployment
with 4-8 workers might experience performance issues if workers are being restarted
too often (once or more per minute).
A higher value of `1200` or more could be beneficial if the server has free memory.
### Monitor worker restarts
GitLab emits log events if workers are restarted due to high memory use.
The following is an example of one of these log events in `/var/log/gitlab/gitlab-rails/application_json.log`:
```json
{
"severity": "WARN",
"time": "2023-01-04T09:45:16.173Z",
"correlation_id": null,
"pid": 2725,
"worker_id": "puma_0",
"memwd_handler_class": "Gitlab::Memory::Watchdog::PumaHandler",
"memwd_sleep_time_s": 5,
"memwd_rss_bytes": 1077682176,
"memwd_max_rss_bytes": 629145600,
"memwd_max_strikes": 5,
"memwd_cur_strikes": 6,
"message": "rss memory limit exceeded"
}
```
`memwd_rss_bytes` is the actual amount of memory consumed, and `memwd_max_rss_bytes` is the
RSS limit set through `per_worker_max_memory_mb`.
## Change the worker timeout
The default Puma [timeout is 60 seconds](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/rack_timeout.rb).
{{< alert type="note" >}}
The `puma['worker_timeout']` setting does not set the maximum request duration.
{{< /alert >}}
To change the worker timeout to 600 seconds:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['env'] = {
'GITLAB_RAILS_RACK_TIMEOUT' => 600
}
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## Disable Puma clustered mode in memory-constrained environments
{{< alert type="warning" >}}
This feature is an [experiment](../../policy/development_stages_support.md#experiment) and subject to change without notice. This feature
is not ready for production use. If you want to use this feature, you should test
outside of production first. See the [known issues](#puma-single-mode-known-issues)
for additional details.
{{< /alert >}}
In a memory-constrained environment with less than 4 GB of RAM available, consider disabling Puma
[clustered mode](https://github.com/puma/puma#clustered-mode).
Set the number of `workers` to `0` to reduce memory usage by hundreds of MB:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['worker_processes'] = 0
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
Unlike in a clustered mode, which is set up by default, only a single Puma process would serve the application.
For details on Puma worker and thread settings, see the [Puma requirements](../../install/requirements.md#puma).
The downside of running Puma in this configuration is the reduced throughput, which can be
considered a fair tradeoff in a memory-constrained environment.
Remember to have sufficient swap available to avoid out of memory (OOM)
conditions. View the [Memory requirements](../../install/requirements.md#memory)
for details.
### Puma single mode known issues
When running Puma in single mode, some features are not supported:
- [Phased restart](https://gitlab.com/gitlab-org/gitlab/-/issues/300665)
- [Memory killers](#reducing-memory-use)
For more information, see [epic 5303](https://gitlab.com/groups/gitlab-org/-/epics/5303).
## Configuring Puma to listen over SSL
Puma, when deployed with a Linux package installation, listens over a Unix socket by
default. To configure Puma to listen over an HTTPS port instead, follow the
steps below:
1. Generate an SSL certificate key-pair for the address where Puma will
listen. For the example below, this is `127.0.0.1`.
{{< alert type="note" >}}
If using a self-signed certificate from a custom Certificate Authority (CA),
follow [the documentation](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates)
to make them trusted by other GitLab components.
{{< /alert >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['ssl_listen'] = '127.0.0.1'
puma['ssl_port'] = 9111
puma['ssl_certificate'] = '<path_to_certificate>'
puma['ssl_certificate_key'] = '<path_to_key>'
# Disable UNIX socket
puma['socket'] = ""
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< alert type="note" >}}
In addition to the Unix socket, Puma also listens over HTTP on port 8080 for
providing metrics to be scraped by Prometheus. It is not currently possible to
make Prometheus scrape them over HTTPS, and support for it is being discussed
[in this issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/6811).
Hence, it is not technically possible to turn off this HTTP listener without
losing Prometheus metrics.
{{< /alert >}}
### Using an encrypted SSL key
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7799) in GitLab 16.1.
{{< /history >}}
Puma supports the use of an encrypted private SSL key, which can be
decrypted at runtime. The following instructions illustrate how to
configure this:
1. Encrypt the key with a password if it is not already:
```shell
openssl rsa -aes256 -in /path/to/ssl-key.pem -out /path/to/encrypted-ssl-key.pem
```
Enter in a password twice to write the encrypted file. In this
example, we use `some-password-here`.
1. Create a script or executable that prints the password. For
example, create a basic script in
`/var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password` that echoes
the password:
```shell
#!/bin/sh
echo some-password-here
```
Avoid storing the password on disk, and use a secure mechanism for retrieving a password, such as
Vault. For example, the script might look like:
```shell
#!/bin/sh
export VAULT_ADDR=http://vault-password-distribution-point:8200
export VAULT_TOKEN=<some token>
echo "$(vault kv get -mount=secret puma-ssl-password)"
```
1. Ensure the Puma process has sufficient permissions to execute the
script and to read the encrypted key:
```shell
chown git:git /var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password
chmod 770 /var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password
chmod 660 /path/to/encrypted-ssl-key.pem
```
1. Edit `/etc/gitlab/gitlab.rb`, and replace `puma['ssl_certificate_key']` with the encrypted key and specify
`puma['ssl_key_password_command]`:
```ruby
puma['ssl_certificate_key'] = '/path/to/encrypted-ssl-key.pem'
puma['ssl_key_password_command'] = '/var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password'
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
1. If GitLab comes up successfully, you should be able to remove the
unencrypted SSL key that was stored on the GitLab instance.
## Switch from Unicorn to Puma
{{< alert type="note" >}}
For Helm-based deployments, see the
[`webservice` chart documentation](https://docs.gitlab.com/charts/charts/gitlab/webservice/).
{{< /alert >}}
Puma is the default web server and Unicorn is no longer supported.
Puma has a multi-thread architecture that uses less memory than a multi-process
application server like Unicorn. On GitLab.com, we saw a 40% reduction in memory
consumption. Most Rails application requests usually include a proportion of I/O wait time.
During I/O wait time, MRI Ruby releases the GVL to other threads.
Multi-threaded Puma can therefore still serve more requests than a single process.
When switching to Puma, any Unicorn server configuration will not carry over
automatically, due to differences between the two application servers.
To switch from Unicorn to Puma:
1. Determine suitable Puma [worker and thread settings](../../install/requirements.md#puma).
1. Convert any custom Unicorn settings to Puma in `/etc/gitlab/gitlab.rb`.
The table below summarizes which Unicorn configuration keys correspond to those
in Puma when using the Linux package, and which ones have no corresponding counterpart.
| Unicorn | Puma |
| ------------------------------------ | ---------------------------------- |
| `unicorn['enable']` | `puma['enable']` |
| `unicorn['worker_timeout']` | `puma['worker_timeout']` |
| `unicorn['worker_processes']` | `puma['worker_processes']` |
| Not applicable | `puma['ha']` |
| Not applicable | `puma['min_threads']` |
| Not applicable | `puma['max_threads']` |
| `unicorn['listen']` | `puma['listen']` |
| `unicorn['port']` | `puma['port']` |
| `unicorn['socket']` | `puma['socket']` |
| `unicorn['pidfile']` | `puma['pidfile']` |
| `unicorn['tcp_nopush']` | Not applicable |
| `unicorn['backlog_socket']` | Not applicable |
| `unicorn['somaxconn']` | `puma['somaxconn']` |
| Not applicable | `puma['state_path']` |
| `unicorn['log_directory']` | `puma['log_directory']` |
| `unicorn['worker_memory_limit_min']` | Not applicable |
| `unicorn['worker_memory_limit_max']` | `puma['per_worker_max_memory_mb']` |
| `unicorn['exporter_enabled']` | `puma['exporter_enabled']` |
| `unicorn['exporter_address']` | `puma['exporter_address']` |
| `unicorn['exporter_port']` | `puma['exporter_port']` |
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
1. Optional. For multi-node deployments, configure the load balancer to use the
[readiness check](../load_balancer.md#readiness-check).
## Troubleshooting Puma
### 502 Gateway Timeout after Puma spins at 100% CPU
This error occurs when the Web server times out (default: 60 s) after not
hearing back from the Puma worker. If the CPU spins to 100% while this is in
progress, there might be something taking longer than it should.
To fix this issue, we first must figure out what is happening. The
following tips are only recommended if you do not mind users being affected by
downtime. Otherwise, skip to the next section.
1. Load the problematic URL
1. Run `sudo gdb -p <PID>` to attach to the Puma process.
1. In the GDB window, type:
```plaintext
call (void) rb_backtrace()
```
1. This forces the process to generate a Ruby backtrace. Check
`/var/log/gitlab/puma/puma_stderr.log` for the backtrace. For example, you might see:
```plaintext
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:33:in `block in start'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:33:in `loop'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:36:in `block (2 levels) in start'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:44:in `sample'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `sample_objects'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `each_with_object'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `each'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:69:in `block in sample_objects'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:69:in `name'
```
1. To see the current threads, run:
```plaintext
thread apply all bt
```
1. Once you're done debugging with `gdb`, be sure to detach from the process and exit:
```plaintext
detach
exit
```
GDB reports an error if the Puma process terminates before you can run these commands.
To buy more time, you can always raise the
Puma worker timeout. For Linux package installation users, you can edit `/etc/gitlab/gitlab.rb` and
increase it from 60 seconds to 600:
```ruby
gitlab_rails['env'] = {
'GITLAB_RAILS_RACK_TIMEOUT' => 600
}
```
For self-compiled installations, set the environment variable.
Refer to [Puma Worker timeout](puma.md#change-the-worker-timeout).
[Reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
#### Troubleshooting without affecting other users
The previous section attached to a running Puma process, which might have
undesirable effects on users trying to access GitLab during this time. If you
are concerned about affecting others during a production system, you can run a
separate Rails process to debug the issue:
1. Sign in to your GitLab account.
1. Copy the URL that is causing problems (for example, `https://gitlab.com/ABC`).
1. Create a personal access token for your user (User Settings -> Access tokens).
1. Bring up the [GitLab Rails console.](rails_console.md#starting-a-rails-console-session)
1. At the Rails console, run:
```ruby
app.get '<URL FROM STEP 2>/?private_token=<TOKEN FROM STEP 3>'
```
For example:
```ruby
app.get 'https://gitlab.com/gitlab-org/gitlab-foss/-/issues/1?private_token=123456'
```
1. In a new window, run `top`. It should show this Ruby process using 100% CPU. Write down the PID.
1. Follow step 2 from the previous section on using GDB.
### GitLab: API is not accessible
This often occurs when GitLab Shell attempts to request authorization via the
internal API (for example, `http://localhost:8080/api/v4/internal/allowed`), and
something in the check fails. This issue might occur for the following reasons:
1. Timeout connecting to a database (for example, PostgreSQL or Redis)
1. Error in Git hooks or push rules
1. Error accessing the repository (for example, stale NFS handles)
To diagnose this problem, try to reproduce the problem and then see if there
is a Puma worker that is spinning via `top`. Try to use the `gdb`
techniques documented previously. In addition, using `strace` might help isolate issues:
```shell
strace -ttTfyyy -s 1024 -p <PID of puma worker> -o /tmp/puma.txt
```
If you cannot isolate which Puma worker is the issue, try to run `strace`
on all the Puma workers to see where the
`/internal/allowed` endpoint gets stuck:
```shell
ps auwx | grep puma | awk '{ print " -p " $2}' | xargs strace -ttTfyyy -s 1024 -o /tmp/puma.txt
```
The output in `/tmp/puma.txt` might help diagnose the root cause.
## Related topics
- [Use a dedicated metrics server to export web metrics](../monitoring/prometheus/web_exporter.md)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Configure the bundled Puma instance of the GitLab package
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Puma is a fast, multi-threaded, and highly concurrent HTTP 1.1 server for
Ruby applications. It runs the core Rails application that provides the user-facing
features of GitLab.
## Reducing memory use
To reduce memory use, Puma forks worker processes. Each time a worker is created,
it shares memory with the primary process. The worker uses additional memory only
when it changes or adds to its memory pages. This can lead to Puma workers using
more physical memory over time as workers handle additional web requests. The amount of memory
used over time depends on the use of GitLab. The more features used by GitLab users,
the higher the expected memory use over time.
To stop uncontrolled memory growth, the GitLab Rails application runs a supervision thread
that automatically restarts workers if they exceed a given resident set size (RSS) threshold
for a certain amount of time.
GitLab sets a default of `1200Mb` for the memory limit. To override the default value,
set `per_worker_max_memory_mb` to the new RSS limit in megabytes:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['per_worker_max_memory_mb'] = 1024 # 1 GB
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
When workers are restarted, capacity to run GitLab is reduced for a short
period of time. Set `per_worker_max_memory_mb` to a higher value if workers are replaced too often.
Worker count is calculated based on CPU cores. A small GitLab deployment
with 4-8 workers might experience performance issues if workers are being restarted
too often (once or more per minute).
A higher value of `1200` or more could be beneficial if the server has free memory.
### Monitor worker restarts
GitLab emits log events if workers are restarted due to high memory use.
The following is an example of one of these log events in `/var/log/gitlab/gitlab-rails/application_json.log`:
```json
{
"severity": "WARN",
"time": "2023-01-04T09:45:16.173Z",
"correlation_id": null,
"pid": 2725,
"worker_id": "puma_0",
"memwd_handler_class": "Gitlab::Memory::Watchdog::PumaHandler",
"memwd_sleep_time_s": 5,
"memwd_rss_bytes": 1077682176,
"memwd_max_rss_bytes": 629145600,
"memwd_max_strikes": 5,
"memwd_cur_strikes": 6,
"message": "rss memory limit exceeded"
}
```
`memwd_rss_bytes` is the actual amount of memory consumed, and `memwd_max_rss_bytes` is the
RSS limit set through `per_worker_max_memory_mb`.
## Change the worker timeout
The default Puma [timeout is 60 seconds](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/initializers/rack_timeout.rb).
{{< alert type="note" >}}
The `puma['worker_timeout']` setting does not set the maximum request duration.
{{< /alert >}}
To change the worker timeout to 600 seconds:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['env'] = {
'GITLAB_RAILS_RACK_TIMEOUT' => 600
}
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## Disable Puma clustered mode in memory-constrained environments
{{< alert type="warning" >}}
This feature is an [experiment](../../policy/development_stages_support.md#experiment) and subject to change without notice. This feature
is not ready for production use. If you want to use this feature, you should test
outside of production first. See the [known issues](#puma-single-mode-known-issues)
for additional details.
{{< /alert >}}
In a memory-constrained environment with less than 4 GB of RAM available, consider disabling Puma
[clustered mode](https://github.com/puma/puma#clustered-mode).
Set the number of `workers` to `0` to reduce memory usage by hundreds of MB:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['worker_processes'] = 0
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
Unlike in a clustered mode, which is set up by default, only a single Puma process would serve the application.
For details on Puma worker and thread settings, see the [Puma requirements](../../install/requirements.md#puma).
The downside of running Puma in this configuration is the reduced throughput, which can be
considered a fair tradeoff in a memory-constrained environment.
Remember to have sufficient swap available to avoid out of memory (OOM)
conditions. View the [Memory requirements](../../install/requirements.md#memory)
for details.
### Puma single mode known issues
When running Puma in single mode, some features are not supported:
- [Phased restart](https://gitlab.com/gitlab-org/gitlab/-/issues/300665)
- [Memory killers](#reducing-memory-use)
For more information, see [epic 5303](https://gitlab.com/groups/gitlab-org/-/epics/5303).
## Configuring Puma to listen over SSL
Puma, when deployed with a Linux package installation, listens over a Unix socket by
default. To configure Puma to listen over an HTTPS port instead, follow the
steps below:
1. Generate an SSL certificate key-pair for the address where Puma will
listen. For the example below, this is `127.0.0.1`.
{{< alert type="note" >}}
If using a self-signed certificate from a custom Certificate Authority (CA),
follow [the documentation](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates)
to make them trusted by other GitLab components.
{{< /alert >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
puma['ssl_listen'] = '127.0.0.1'
puma['ssl_port'] = 9111
puma['ssl_certificate'] = '<path_to_certificate>'
puma['ssl_certificate_key'] = '<path_to_key>'
# Disable UNIX socket
puma['socket'] = ""
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< alert type="note" >}}
In addition to the Unix socket, Puma also listens over HTTP on port 8080 for
providing metrics to be scraped by Prometheus. It is not currently possible to
make Prometheus scrape them over HTTPS, and support for it is being discussed
[in this issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/6811).
Hence, it is not technically possible to turn off this HTTP listener without
losing Prometheus metrics.
{{< /alert >}}
### Using an encrypted SSL key
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7799) in GitLab 16.1.
{{< /history >}}
Puma supports the use of an encrypted private SSL key, which can be
decrypted at runtime. The following instructions illustrate how to
configure this:
1. Encrypt the key with a password if it is not already:
```shell
openssl rsa -aes256 -in /path/to/ssl-key.pem -out /path/to/encrypted-ssl-key.pem
```
Enter in a password twice to write the encrypted file. In this
example, we use `some-password-here`.
1. Create a script or executable that prints the password. For
example, create a basic script in
`/var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password` that echoes
the password:
```shell
#!/bin/sh
echo some-password-here
```
Avoid storing the password on disk, and use a secure mechanism for retrieving a password, such as
Vault. For example, the script might look like:
```shell
#!/bin/sh
export VAULT_ADDR=http://vault-password-distribution-point:8200
export VAULT_TOKEN=<some token>
echo "$(vault kv get -mount=secret puma-ssl-password)"
```
1. Ensure the Puma process has sufficient permissions to execute the
script and to read the encrypted key:
```shell
chown git:git /var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password
chmod 770 /var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password
chmod 660 /path/to/encrypted-ssl-key.pem
```
1. Edit `/etc/gitlab/gitlab.rb`, and replace `puma['ssl_certificate_key']` with the encrypted key and specify
`puma['ssl_key_password_command]`:
```ruby
puma['ssl_certificate_key'] = '/path/to/encrypted-ssl-key.pem'
puma['ssl_key_password_command'] = '/var/opt/gitlab/gitlab-rails/etc/puma-ssl-key-password'
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
1. If GitLab comes up successfully, you should be able to remove the
unencrypted SSL key that was stored on the GitLab instance.
## Switch from Unicorn to Puma
{{< alert type="note" >}}
For Helm-based deployments, see the
[`webservice` chart documentation](https://docs.gitlab.com/charts/charts/gitlab/webservice/).
{{< /alert >}}
Puma is the default web server and Unicorn is no longer supported.
Puma has a multi-thread architecture that uses less memory than a multi-process
application server like Unicorn. On GitLab.com, we saw a 40% reduction in memory
consumption. Most Rails application requests usually include a proportion of I/O wait time.
During I/O wait time, MRI Ruby releases the GVL to other threads.
Multi-threaded Puma can therefore still serve more requests than a single process.
When switching to Puma, any Unicorn server configuration will not carry over
automatically, due to differences between the two application servers.
To switch from Unicorn to Puma:
1. Determine suitable Puma [worker and thread settings](../../install/requirements.md#puma).
1. Convert any custom Unicorn settings to Puma in `/etc/gitlab/gitlab.rb`.
The table below summarizes which Unicorn configuration keys correspond to those
in Puma when using the Linux package, and which ones have no corresponding counterpart.
| Unicorn | Puma |
| ------------------------------------ | ---------------------------------- |
| `unicorn['enable']` | `puma['enable']` |
| `unicorn['worker_timeout']` | `puma['worker_timeout']` |
| `unicorn['worker_processes']` | `puma['worker_processes']` |
| Not applicable | `puma['ha']` |
| Not applicable | `puma['min_threads']` |
| Not applicable | `puma['max_threads']` |
| `unicorn['listen']` | `puma['listen']` |
| `unicorn['port']` | `puma['port']` |
| `unicorn['socket']` | `puma['socket']` |
| `unicorn['pidfile']` | `puma['pidfile']` |
| `unicorn['tcp_nopush']` | Not applicable |
| `unicorn['backlog_socket']` | Not applicable |
| `unicorn['somaxconn']` | `puma['somaxconn']` |
| Not applicable | `puma['state_path']` |
| `unicorn['log_directory']` | `puma['log_directory']` |
| `unicorn['worker_memory_limit_min']` | Not applicable |
| `unicorn['worker_memory_limit_max']` | `puma['per_worker_max_memory_mb']` |
| `unicorn['exporter_enabled']` | `puma['exporter_enabled']` |
| `unicorn['exporter_address']` | `puma['exporter_address']` |
| `unicorn['exporter_port']` | `puma['exporter_port']` |
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
1. Optional. For multi-node deployments, configure the load balancer to use the
[readiness check](../load_balancer.md#readiness-check).
## Troubleshooting Puma
### 502 Gateway Timeout after Puma spins at 100% CPU
This error occurs when the Web server times out (default: 60 s) after not
hearing back from the Puma worker. If the CPU spins to 100% while this is in
progress, there might be something taking longer than it should.
To fix this issue, we first must figure out what is happening. The
following tips are only recommended if you do not mind users being affected by
downtime. Otherwise, skip to the next section.
1. Load the problematic URL
1. Run `sudo gdb -p <PID>` to attach to the Puma process.
1. In the GDB window, type:
```plaintext
call (void) rb_backtrace()
```
1. This forces the process to generate a Ruby backtrace. Check
`/var/log/gitlab/puma/puma_stderr.log` for the backtrace. For example, you might see:
```plaintext
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:33:in `block in start'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:33:in `loop'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:36:in `block (2 levels) in start'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:44:in `sample'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `sample_objects'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `each_with_object'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:68:in `each'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:69:in `block in sample_objects'
from /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/metrics/sampler.rb:69:in `name'
```
1. To see the current threads, run:
```plaintext
thread apply all bt
```
1. Once you're done debugging with `gdb`, be sure to detach from the process and exit:
```plaintext
detach
exit
```
GDB reports an error if the Puma process terminates before you can run these commands.
To buy more time, you can always raise the
Puma worker timeout. For Linux package installation users, you can edit `/etc/gitlab/gitlab.rb` and
increase it from 60 seconds to 600:
```ruby
gitlab_rails['env'] = {
'GITLAB_RAILS_RACK_TIMEOUT' => 600
}
```
For self-compiled installations, set the environment variable.
Refer to [Puma Worker timeout](puma.md#change-the-worker-timeout).
[Reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
#### Troubleshooting without affecting other users
The previous section attached to a running Puma process, which might have
undesirable effects on users trying to access GitLab during this time. If you
are concerned about affecting others during a production system, you can run a
separate Rails process to debug the issue:
1. Sign in to your GitLab account.
1. Copy the URL that is causing problems (for example, `https://gitlab.com/ABC`).
1. Create a personal access token for your user (User Settings -> Access tokens).
1. Bring up the [GitLab Rails console.](rails_console.md#starting-a-rails-console-session)
1. At the Rails console, run:
```ruby
app.get '<URL FROM STEP 2>/?private_token=<TOKEN FROM STEP 3>'
```
For example:
```ruby
app.get 'https://gitlab.com/gitlab-org/gitlab-foss/-/issues/1?private_token=123456'
```
1. In a new window, run `top`. It should show this Ruby process using 100% CPU. Write down the PID.
1. Follow step 2 from the previous section on using GDB.
### GitLab: API is not accessible
This often occurs when GitLab Shell attempts to request authorization via the
internal API (for example, `http://localhost:8080/api/v4/internal/allowed`), and
something in the check fails. This issue might occur for the following reasons:
1. Timeout connecting to a database (for example, PostgreSQL or Redis)
1. Error in Git hooks or push rules
1. Error accessing the repository (for example, stale NFS handles)
To diagnose this problem, try to reproduce the problem and then see if there
is a Puma worker that is spinning via `top`. Try to use the `gdb`
techniques documented previously. In addition, using `strace` might help isolate issues:
```shell
strace -ttTfyyy -s 1024 -p <PID of puma worker> -o /tmp/puma.txt
```
If you cannot isolate which Puma worker is the issue, try to run `strace`
on all the Puma workers to see where the
`/internal/allowed` endpoint gets stuck:
```shell
ps auwx | grep puma | awk '{ print " -p " $2}' | xargs strace -ttTfyyy -s 1024 -o /tmp/puma.txt
```
The output in `/tmp/puma.txt` might help diagnose the root cause.
## Related topics
- [Use a dedicated metrics server to export web metrics](../monitoring/prometheus/web_exporter.md)
|
https://docs.gitlab.com/administration/rails_console
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/rails_console.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
rails_console.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Rails console
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
At the heart of GitLab is a web application
[built using the Ruby on Rails framework](https://about.gitlab.com/blog/2018/10/29/why-we-use-rails-to-build-gitlab/).
The [Rails console](https://guides.rubyonrails.org/command_line.html#rails-console)
provides a way to interact with your GitLab instance from the command line, and also grants access to the amazing tools built right into Rails.
{{< alert type="warning" >}}
The Rails console interacts directly with GitLab. In many cases,
there are no handrails to prevent you from permanently modifying, corrupting
or destroying production data. If you would like to explore the Rails console
with no consequences, you are strongly advised to do so in a test environment.
{{< /alert >}}
The Rails console is for GitLab system administrators who are troubleshooting
a problem or need to retrieve some data that can only be done through direct
access of the GitLab application. Basic knowledge of Ruby is needed (try
[this 30-minute tutorial](https://try.ruby-lang.org/) for a quick introduction).
Rails experience is useful but not required.
## Starting a Rails console session
The process for starting a Rails console session depends on the type of GitLab installation.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rails console
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it <container-id> gitlab-rails console
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rails console -e production
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
```shell
# find the pod
kubectl get pods --namespace <namespace> -lapp=toolbox
# open the Rails console
kubectl exec -it -c toolbox <toolbox-pod-name> -- gitlab-rails console
```
{{< /tab >}}
{{< /tabs >}}
To exit the console, type: `quit`.
### Disable autocompletion
Ruby autocompletion can slow down the terminal. If you want to:
- Disable autocompletion, run `Reline.autocompletion = IRB.conf[:USE_AUTOCOMPLETE] = false`.
- Re-enable autocompletion, run `Reline.autocompletion = IRB.conf[:USE_AUTOCOMPLETE] = true`.
## Enable Active Record logging
You can enable output of Active Record debug logging in the Rails console
session by running:
```ruby
ActiveRecord::Base.logger = Logger.new($stdout)
```
By default, the previous script logs to the standard output. You can specify a log file to redirect
output to, by replacing `$stdout` with the desired file path. For example, this code logs everything
to `/tmp/output.log`:
```ruby
ActiveRecord::Base.logger = Logger.new('/tmp/output.log')
```
This shows information about database queries triggered by any Ruby code
you may run in the console. To turn off logging again, run:
```ruby
ActiveRecord::Base.logger = nil
```
## Attributes
View available attributes, formatted using pretty print (`pp`).
For example, determine what attributes contain users' names and email addresses:
```ruby
u = User.find_by_username('someuser')
pp u.attributes
```
Partial output:
```plaintext
{"id"=>1234,
"email"=>"someuser@example.com",
"sign_in_count"=>99,
"name"=>"S User",
"username"=>"someuser",
"first_name"=>nil,
"last_name"=>nil,
"bot_type"=>nil}
```
Then make use of the attributes, [testing SMTP, for example](https://docs.gitlab.com/omnibus/settings/smtp.html#testing-the-smtp-configuration):
```ruby
e = u.email
n = u.name
Notify.test_email(e, "Test email for #{n}", 'Test email').deliver_now
#
Notify.test_email(u.email, "Test email for #{u.name}", 'Test email').deliver_now
```
## Disable database statement timeout
You can disable the PostgreSQL statement timeout for the current Rails console
session.
In GitLab 15.11 and earlier, to disable the database statement timeout, run:
```ruby
ActiveRecord::Base.connection.execute('SET statement_timeout TO 0')
```
In GitLab 16.0 and later, [GitLab uses two database connections by default](../../update/versions/gitlab_16_changes.md#1600). To disable the database statement timeout, run:
```ruby
ActiveRecord::Base.connection.execute('SET statement_timeout TO 0')
Ci::ApplicationRecord.connection.execute('SET statement_timeout TO 0')
```
Instances running GitLab 16.0 and later reconfigured to use a single database connection should disable the database statement timeout using the code for GitLab 15.11 and earlier.
Disabling the database statement timeout affects only the current Rails console session and is
not persisted in the GitLab production environment or in the next Rails
console session.
## Output Rails console session history
Enter the following command on the rails console to display
your command history.
```ruby
puts Reline::HISTORY.to_a
```
You can then copy it to your clipboard and save for future reference.
## Using the Rails Runner
If you need to run some Ruby code in the context of your GitLab production
environment, you can do so using the [Rails Runner](https://guides.rubyonrails.org/command_line.html#rails-runner).
When executing a script file, the script must be accessible by the `git` user.
When the command or script completes, the Rails Runner process finishes.
It is useful for running in other scripts or cron jobs for example.
- For Linux package installations:
```shell
sudo gitlab-rails runner "RAILS_COMMAND"
# Example with a two-line Ruby script
sudo gitlab-rails runner "user = User.first; puts user.username"
# Example with a ruby script file (make sure to use the full path)
sudo gitlab-rails runner /path/to/script.rb
```
- For self-compiled installations:
```shell
sudo -u git -H bundle exec rails runner -e production "RAILS_COMMAND"
# Example with a two-line Ruby script
sudo -u git -H bundle exec rails runner -e production "user = User.first; puts user.username"
# Example with a ruby script file (make sure to use the full path)
sudo -u git -H bundle exec rails runner -e production /path/to/script.rb
```
Rails Runner does not produce the same output as the console.
If you set a variable on the console, the console generates useful debug output
such as the variable contents or properties of referenced entity:
```ruby
irb(main):001:0> user = User.first
=> #<User id:1 @root>
```
Rails Runner does not do this: you have to be explicit about generating
output:
```shell
$ sudo gitlab-rails runner "user = User.first"
$ sudo gitlab-rails runner "user = User.first; puts user.username ; puts user.id"
root
1
```
Some basic knowledge of Ruby is very useful. Try
[this 30-minute tutorial](https://try.ruby-lang.org/) for a quick introduction.
Rails experience is helpful but not essential.
## Find specific methods for an object
```ruby
Array.methods.select { |m| m.to_s.include? "sing" }
Array.methods.grep(/sing/)
```
## Find method source
```ruby
instance_of_object.method(:foo).source_location
# Example for when we would call project.private?
project.method(:private?).source_location
```
## Limiting output
Adding a semicolon(`;`) and a follow-up statement at the end of a statement prevents the default implicit return output. This can be used if you are already explicitly printing details and potentially have a lot of return output:
```ruby
puts ActiveRecord::Base.descendants; :ok
Project.select(&:pages_deployed?).each {|p| puts p.path }; true
```
## Get or store the result of last operation
Underscore(`_`) represents the implicit return of the previous statement. You can use this to quickly assign a variable from the output of the previous command:
```ruby
Project.last
# => #<Project id:2537 root/discard>>
project = _
# => #<Project id:2537 root/discard>>
project.id
# => 2537
```
## Time an operation
If you'd like to time one or more operations, use the following format, replacing
the placeholder `<operation>` with your Ruby or Rails commands of choice:
```ruby
# A single operation
Benchmark.measure { <operation> }
# A breakdown of multiple operations
Benchmark.bm do |x|
x.report(:label1) { <operation_1> }
x.report(:label2) { <operation_2> }
end
```
For more information, review our developer documentation about benchmarks.
## Active Record objects
### Looking up database-persisted objects
Under the hood, Rails uses [Active Record](https://guides.rubyonrails.org/active_record_basics.html),
an object-relational mapping system, to read, write, and map application objects
to the PostgreSQL database. These mappings are handled by Active Record models,
which are Ruby classes defined in a Rails app. For GitLab, the model classes
can be found at `/opt/gitlab/embedded/service/gitlab-rails/app/models`.
Let's enable debug logging for Active Record so we can see the underlying
database queries made:
```ruby
ActiveRecord::Base.logger = Logger.new($stdout)
```
Now, let's try retrieving a user from the database:
```ruby
user = User.find(1)
```
Which would return:
```ruby
D, [2020-03-05T16:46:25.571238 #910] DEBUG -- : User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> #<User id:1 @root>
```
We can see that we've queried the `users` table in the database for a row whose
`id` column has the value `1`, and Active Record has translated that database
record into a Ruby object that we can interact with. Try some of the following:
- `user.username`
- `user.created_at`
- `user.admin`
By convention, column names are directly translated into Ruby object attributes,
so you should be able to do `user.<column_name>` to view the attribute's value.
Also by convention, Active Record class names (singular and in camel case) map
directly onto table names (plural and in snake case) and vice versa. For example,
the `users` table maps to the `User` class, while the `application_settings`
table maps to the `ApplicationSetting` class.
You can find a list of tables and column names in the Rails database schema,
available at `/opt/gitlab/embedded/service/gitlab-rails/db/schema.rb`.
You can also look up an object from the database by attribute name:
```ruby
user = User.find_by(username: 'root')
```
Which would return:
```ruby
D, [2020-03-05T17:03:24.696493 #910] DEBUG -- : User Load (2.1ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'root' LIMIT 1
=> #<User id:1 @root>
```
Give the following a try:
- `User.find_by(username: 'root')`
- `User.where.not(admin: true)`
- `User.where('created_at < ?', 7.days.ago)`
Did you notice that the last two commands returned an `ActiveRecord::Relation`
object that appeared to contain multiple `User` objects?
Up to now, we've been using `.find` or `.find_by`, which are designed to return
only a single object (notice the `LIMIT 1` in the generated SQL query?).
`.where` is used when it is desirable to get a collection of objects.
Let's get a collection of non-administrator users and see what we can do with it:
```ruby
users = User.where.not(admin: true)
```
Which would return:
```ruby
D, [2020-03-05T17:11:16.845387 #910] DEBUG -- : User Load (2.8ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE LIMIT 11
=> #<ActiveRecord::Relation [#<User id:3 @support-bot>, #<User id:7 @alert-bot>, #<User id:5 @carrie>, #<User id:4 @bernice>, #<User id:2 @anne>]>
```
Now, try the following:
- `users.count`
- `users.order(created_at: :desc)`
- `users.where(username: 'support-bot')`
In the last command, we see that we can chain `.where` statements to generate
more complex queries. Notice also that while the collection returned contains
only a single object, we cannot directly interact with it:
```ruby
users.where(username: 'support-bot').username
```
Which would return:
```ruby
Traceback (most recent call last):
1: from (irb):37
D, [2020-03-05T17:18:25.637607 #910] DEBUG -- : User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE AND "users"."username" = 'support-bot' LIMIT 11
NoMethodError (undefined method `username' for #<ActiveRecord::Relation [#<User id:3 @support-bot>]>)
Did you mean? by_username
```
Let's retrieve the single object from the collection by using the `.first`
method to get the first item in the collection:
```ruby
users.where(username: 'support-bot').first.username
```
We now get the result we wanted:
```ruby
D, [2020-03-05T17:18:30.406047 #910] DEBUG -- : User Load (2.6ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE AND "users"."username" = 'support-bot' ORDER BY "users"."id" ASC LIMIT 1
=> "support-bot"
```
For more on different ways to retrieve data from the database using Active
Record, see the [Active Record Query Interface documentation](https://guides.rubyonrails.org/active_record_querying.html).
## Query the database using an Active Record model
```ruby
m = Model.where('attribute like ?', 'ex%')
# for example to query the projects
projects = Project.where('path like ?', 'Oumua%')
```
### Modifying Active Record objects
In the previous section, we learned about retrieving database records using
Active Record. Now, let's learn how to write changes to the database.
First, let's retrieve the `root` user:
```ruby
user = User.find_by(username: 'root')
```
Next, let's try updating the user's password:
```ruby
user.password = 'password'
user.save
```
Which would return:
```ruby
Enqueued ActionMailer::MailDeliveryJob (Job ID: 05915c4e-c849-4e14-80bb-696d5ae22065) to Sidekiq(mailers) with arguments: "DeviseMailer", "password_change", "deliver_now", #<GlobalID:0x00007f42d8ccebe8 @uri=#<URI::GID gid://gitlab/User/1>>
=> true
```
Here, we see that the `.save` command returned `true`, indicating that the
password change was successfully saved to the database.
We also see that the save operation triggered some other action -- in this case
a background job to deliver an email notification. This is an example of an
[Active Record callback](https://guides.rubyonrails.org/active_record_callbacks.html)
-- code which is designated to run in response to events in the Active Record
object lifecycle. This is also why using the Rails console is preferred when
direct changes to data is necessary as changes made via direct database queries
do not trigger these callbacks.
It's also possible to update attributes in a single line:
```ruby
user.update(password: 'password')
```
Or update multiple attributes at once:
```ruby
user.update(password: 'password', email: 'hunter2@example.com')
```
Now, let's try something different:
```ruby
# Retrieve the object again so we get its latest state
user = User.find_by(username: 'root')
user.password = 'password'
user.password_confirmation = 'hunter2'
user.save
```
This returns `false`, indicating that the changes we made were not saved to the
database. You can probably guess why, but let's find out for sure:
```ruby
user.save!
```
This should return:
```ruby
Traceback (most recent call last):
1: from (irb):64
ActiveRecord::RecordInvalid (Validation failed: Password confirmation doesn't match Password)
```
Aha! We've tripped an [Active Record Validation](https://guides.rubyonrails.org/active_record_validations.html).
Validations are business logic put in place at the application-level to prevent
unwanted data from being saved to the database and in most cases come with
helpful messages letting you know how to fix the problem inputs.
We can also add the bang (Ruby speak for `!`) to `.update`:
```ruby
user.update!(password: 'password', password_confirmation: 'hunter2')
```
In Ruby, method names ending with `!` are commonly known as "bang methods." By
convention, the bang indicates that the method directly modifies the object it
is acting on, as opposed to returning the transformed result and leaving the
underlying object untouched. For Active Record methods that write to the
database, bang methods also serve an additional function: they raise an
explicit exception whenever an error occurs, instead of just returning `false`.
We can also skip validations entirely:
```ruby
# Retrieve the object again so we get its latest state
user = User.find_by(username: 'root')
user.password = 'password'
user.password_confirmation = 'hunter2'
user.save!(validate: false)
```
This is not recommended because validations are usually put in place to ensure the
integrity and consistency of user-provided data.
A validation error prevents the entire object from being saved to
the database. You can see a little of this in the section below. If you're getting
a mysterious red banner in the GitLab UI when submitting a form, this can often
be the fastest way to get to the root of the problem.
### Interacting with Active Record objects
At the end of the day, Active Record objects are just standard Ruby objects. As
such, we can define methods on them which perform arbitrary actions.
For example, GitLab developers have added some methods which help with
two-factor authentication:
```ruby
def disable_two_factor!
transaction do
update(
otp_required_for_login: false,
encrypted_otp_secret: nil,
encrypted_otp_secret_iv: nil,
encrypted_otp_secret_salt: nil,
otp_grace_period_started_at: nil,
otp_backup_codes: nil
)
self.webauthn_registrations.destroy_all # rubocop: disable DestroyAll
end
end
def two_factor_enabled?
two_factor_otp_enabled? || two_factor_webauthn_enabled?
end
```
(See: `/opt/gitlab/embedded/service/gitlab-rails/app/models/user.rb`)
We can then use these methods on any user object:
```ruby
user = User.find_by(username: 'root')
user.two_factor_enabled?
user.disable_two_factor!
```
Some methods are defined by gems, or Ruby software packages, which GitLab uses.
For example, the [StateMachines](https://github.com/state-machines/state_machines-activerecord)
gem which GitLab uses to manage user state:
```ruby
state_machine :state, initial: :active do
event :block do
...
event :activate do
...
end
```
Give it a try:
```ruby
user = User.find_by(username: 'root')
user.state
user.block
user.state
user.activate
user.state
```
Earlier, we mentioned that a validation error prevents the entire object
from being saved to the database. Let's see how this can have unexpected
interactions:
```ruby
user.password = 'password'
user.password_confirmation = 'hunter2'
user.block
```
We get `false` returned! Let's find out what happened by adding a bang as we did
earlier:
```ruby
user.block!
```
Which would return:
```ruby
Traceback (most recent call last):
1: from (irb):87
StateMachines::InvalidTransition (Cannot transition state via :block from :active (Reason(s): Password confirmation doesn't match Password))
```
We see that a validation error from what feels like a completely separate
attribute comes back to haunt us when we try to update the user in any way.
In practical terms, we sometimes see this happen with GitLab administration settings --
validations are sometimes added or changed in a GitLab update, resulting in
previously saved settings now failing validation. Because you can only update
a subset of settings at once through the UI, in this case the only way to get
back to a good state is direct manipulation via Rails console.
### Commonly used Active Record models and how to look up objects
**Get a user by primary email address or username**:
```ruby
User.find_by(email: 'admin@example.com')
User.find_by(username: 'root')
```
**Get a user by primary OR secondary email address**:
```ruby
User.find_by_any_email('user@example.com')
```
The `find_by_any_email` method is a custom method added by GitLab developers rather
than a Rails-provided default method.
**Get a collection of administrator users**:
```ruby
User.admins
```
`admins` is a [scope convenience method](https://guides.rubyonrails.org/active_record_querying.html#scopes)
which does `where(admin: true)` under the hood.
**Get a project by its path**:
```ruby
Project.find_by_full_path('group/subgroup/project')
```
`find_by_full_path` is a custom method added by GitLab developers rather
than a Rails-provided default method.
**Get a project's issue or merge request by its numeric ID**:
```ruby
project = Project.find_by_full_path('group/subgroup/project')
project.issues.find_by(iid: 42)
project.merge_requests.find_by(iid: 42)
```
`iid` means "internal ID" and is how we keep issue and merge request IDs
scoped to each GitLab project.
**Get a group by its path**:
```ruby
Group.find_by_full_path('group/subgroup')
```
**Get a group's related groups**:
```ruby
group = Group.find_by_full_path('group/subgroup')
# Get a group's parent group
group.parent
# Get a group's child groups
group.children
```
**Get a group's projects**:
```ruby
group = Group.find_by_full_path('group/subgroup')
# Get group's immediate child projects
group.projects
# Get group's child projects, including those in subgroups
group.all_projects
```
**Get CI pipeline or builds**:
```ruby
Ci::Pipeline.find(4151)
Ci::Build.find(66124)
```
The pipeline and job ID numbers increment globally across your GitLab
instance, so there's no requirement to use an internal ID attribute to look them up,
unlike with issues or merge requests.
**Get the current application settings object**:
```ruby
ApplicationSetting.current
```
### Open object in `irb`
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions. Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
Sometimes it is easier to go through a method if you are in the context of the object. You can shim into the namespace of `Object` to let you open `irb` in the context of any object:
```ruby
Object.define_method(:irb) { binding.irb }
project = Project.last
# => #<Project id:2537 root/discard>>
project.irb
# Notice new context
irb(#<Project>)> web_url
# => "https://gitlab-example/root/discard"
```
## Troubleshooting
### Rails Runner `syntax error`
The `gitlab-rails` command executes Rails Runner using a non-root account and group, by default: `git:git`.
If the non-root account cannot find the Ruby script filename passed to `gitlab-rails runner`
you may get a syntax error, not an error that the file couldn't be accessed.
A common reason for this is that the script has been put in the root account's home directory.
`runner` tries to parse the path and file parameter as Ruby code.
For example:
```plaintext
[root ~]# echo 'puts "hello world"' > ./helloworld.rb
[root ~]# sudo gitlab-rails runner ./helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
/opt/gitlab/..../runner_command.rb:45: syntax error, unexpected '.'
./helloworld.rb
^
[root ~]# sudo gitlab-rails runner /root/helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
/opt/gitlab/..../runner_command.rb:45: unknown regexp options - hllwrld
[root ~]# mv ~/helloworld.rb /tmp
[root ~]# sudo gitlab-rails runner /tmp/helloworld.rb
hello world
```
A meaningful error should be generated if the directory can be accessed, but the file cannot:
```plaintext
[root ~]# chmod 400 /tmp/helloworld.rb
[root ~]# sudo gitlab-rails runner /tmp/helloworld.rb
Traceback (most recent call last):
[traceback removed]
/opt/gitlab/..../runner_command.rb:42:in `load': cannot load such file -- /tmp/helloworld.rb (LoadError)
```
In case you encounter a similar error to this:
```plaintext
[root ~]# sudo gitlab-rails runner helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
undefined local variable or method `helloworld' for main:Object
```
You can either move the file to the `/tmp` directory or create a new directory owned by the user `git` and save the script in that directory as illustrated below:
```shell
sudo mkdir /scripts
sudo mv /script_path/helloworld.rb /scripts
sudo chown -R git:git /scripts
sudo chmod 700 /scripts
sudo gitlab-rails runner /scripts/helloworld.rb
```
### Filtered console output
Some output in the console might be filtered by default to prevent leaks of certain values
like variables, logs, or secrets. This output displays as `[FILTERED]`. For example:
```plaintext
> Plan.default.actual_limits
=> ci_instance_level_variables: "[FILTERED]",
```
To work around the filtering, read the values directly from the object. For example:
```plaintext
> Plan.default.limits.ci_instance_level_variables
=> 25
```
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Rails console
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
At the heart of GitLab is a web application
[built using the Ruby on Rails framework](https://about.gitlab.com/blog/2018/10/29/why-we-use-rails-to-build-gitlab/).
The [Rails console](https://guides.rubyonrails.org/command_line.html#rails-console)
provides a way to interact with your GitLab instance from the command line, and also grants access to the amazing tools built right into Rails.
{{< alert type="warning" >}}
The Rails console interacts directly with GitLab. In many cases,
there are no handrails to prevent you from permanently modifying, corrupting
or destroying production data. If you would like to explore the Rails console
with no consequences, you are strongly advised to do so in a test environment.
{{< /alert >}}
The Rails console is for GitLab system administrators who are troubleshooting
a problem or need to retrieve some data that can only be done through direct
access of the GitLab application. Basic knowledge of Ruby is needed (try
[this 30-minute tutorial](https://try.ruby-lang.org/) for a quick introduction).
Rails experience is useful but not required.
## Starting a Rails console session
The process for starting a Rails console session depends on the type of GitLab installation.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rails console
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it <container-id> gitlab-rails console
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rails console -e production
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
```shell
# find the pod
kubectl get pods --namespace <namespace> -lapp=toolbox
# open the Rails console
kubectl exec -it -c toolbox <toolbox-pod-name> -- gitlab-rails console
```
{{< /tab >}}
{{< /tabs >}}
To exit the console, type: `quit`.
### Disable autocompletion
Ruby autocompletion can slow down the terminal. If you want to:
- Disable autocompletion, run `Reline.autocompletion = IRB.conf[:USE_AUTOCOMPLETE] = false`.
- Re-enable autocompletion, run `Reline.autocompletion = IRB.conf[:USE_AUTOCOMPLETE] = true`.
## Enable Active Record logging
You can enable output of Active Record debug logging in the Rails console
session by running:
```ruby
ActiveRecord::Base.logger = Logger.new($stdout)
```
By default, the previous script logs to the standard output. You can specify a log file to redirect
output to, by replacing `$stdout` with the desired file path. For example, this code logs everything
to `/tmp/output.log`:
```ruby
ActiveRecord::Base.logger = Logger.new('/tmp/output.log')
```
This shows information about database queries triggered by any Ruby code
you may run in the console. To turn off logging again, run:
```ruby
ActiveRecord::Base.logger = nil
```
## Attributes
View available attributes, formatted using pretty print (`pp`).
For example, determine what attributes contain users' names and email addresses:
```ruby
u = User.find_by_username('someuser')
pp u.attributes
```
Partial output:
```plaintext
{"id"=>1234,
"email"=>"someuser@example.com",
"sign_in_count"=>99,
"name"=>"S User",
"username"=>"someuser",
"first_name"=>nil,
"last_name"=>nil,
"bot_type"=>nil}
```
Then make use of the attributes, [testing SMTP, for example](https://docs.gitlab.com/omnibus/settings/smtp.html#testing-the-smtp-configuration):
```ruby
e = u.email
n = u.name
Notify.test_email(e, "Test email for #{n}", 'Test email').deliver_now
#
Notify.test_email(u.email, "Test email for #{u.name}", 'Test email').deliver_now
```
## Disable database statement timeout
You can disable the PostgreSQL statement timeout for the current Rails console
session.
In GitLab 15.11 and earlier, to disable the database statement timeout, run:
```ruby
ActiveRecord::Base.connection.execute('SET statement_timeout TO 0')
```
In GitLab 16.0 and later, [GitLab uses two database connections by default](../../update/versions/gitlab_16_changes.md#1600). To disable the database statement timeout, run:
```ruby
ActiveRecord::Base.connection.execute('SET statement_timeout TO 0')
Ci::ApplicationRecord.connection.execute('SET statement_timeout TO 0')
```
Instances running GitLab 16.0 and later reconfigured to use a single database connection should disable the database statement timeout using the code for GitLab 15.11 and earlier.
Disabling the database statement timeout affects only the current Rails console session and is
not persisted in the GitLab production environment or in the next Rails
console session.
## Output Rails console session history
Enter the following command on the rails console to display
your command history.
```ruby
puts Reline::HISTORY.to_a
```
You can then copy it to your clipboard and save for future reference.
## Using the Rails Runner
If you need to run some Ruby code in the context of your GitLab production
environment, you can do so using the [Rails Runner](https://guides.rubyonrails.org/command_line.html#rails-runner).
When executing a script file, the script must be accessible by the `git` user.
When the command or script completes, the Rails Runner process finishes.
It is useful for running in other scripts or cron jobs for example.
- For Linux package installations:
```shell
sudo gitlab-rails runner "RAILS_COMMAND"
# Example with a two-line Ruby script
sudo gitlab-rails runner "user = User.first; puts user.username"
# Example with a ruby script file (make sure to use the full path)
sudo gitlab-rails runner /path/to/script.rb
```
- For self-compiled installations:
```shell
sudo -u git -H bundle exec rails runner -e production "RAILS_COMMAND"
# Example with a two-line Ruby script
sudo -u git -H bundle exec rails runner -e production "user = User.first; puts user.username"
# Example with a ruby script file (make sure to use the full path)
sudo -u git -H bundle exec rails runner -e production /path/to/script.rb
```
Rails Runner does not produce the same output as the console.
If you set a variable on the console, the console generates useful debug output
such as the variable contents or properties of referenced entity:
```ruby
irb(main):001:0> user = User.first
=> #<User id:1 @root>
```
Rails Runner does not do this: you have to be explicit about generating
output:
```shell
$ sudo gitlab-rails runner "user = User.first"
$ sudo gitlab-rails runner "user = User.first; puts user.username ; puts user.id"
root
1
```
Some basic knowledge of Ruby is very useful. Try
[this 30-minute tutorial](https://try.ruby-lang.org/) for a quick introduction.
Rails experience is helpful but not essential.
## Find specific methods for an object
```ruby
Array.methods.select { |m| m.to_s.include? "sing" }
Array.methods.grep(/sing/)
```
## Find method source
```ruby
instance_of_object.method(:foo).source_location
# Example for when we would call project.private?
project.method(:private?).source_location
```
## Limiting output
Adding a semicolon(`;`) and a follow-up statement at the end of a statement prevents the default implicit return output. This can be used if you are already explicitly printing details and potentially have a lot of return output:
```ruby
puts ActiveRecord::Base.descendants; :ok
Project.select(&:pages_deployed?).each {|p| puts p.path }; true
```
## Get or store the result of last operation
Underscore(`_`) represents the implicit return of the previous statement. You can use this to quickly assign a variable from the output of the previous command:
```ruby
Project.last
# => #<Project id:2537 root/discard>>
project = _
# => #<Project id:2537 root/discard>>
project.id
# => 2537
```
## Time an operation
If you'd like to time one or more operations, use the following format, replacing
the placeholder `<operation>` with your Ruby or Rails commands of choice:
```ruby
# A single operation
Benchmark.measure { <operation> }
# A breakdown of multiple operations
Benchmark.bm do |x|
x.report(:label1) { <operation_1> }
x.report(:label2) { <operation_2> }
end
```
For more information, review our developer documentation about benchmarks.
## Active Record objects
### Looking up database-persisted objects
Under the hood, Rails uses [Active Record](https://guides.rubyonrails.org/active_record_basics.html),
an object-relational mapping system, to read, write, and map application objects
to the PostgreSQL database. These mappings are handled by Active Record models,
which are Ruby classes defined in a Rails app. For GitLab, the model classes
can be found at `/opt/gitlab/embedded/service/gitlab-rails/app/models`.
Let's enable debug logging for Active Record so we can see the underlying
database queries made:
```ruby
ActiveRecord::Base.logger = Logger.new($stdout)
```
Now, let's try retrieving a user from the database:
```ruby
user = User.find(1)
```
Which would return:
```ruby
D, [2020-03-05T16:46:25.571238 #910] DEBUG -- : User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> #<User id:1 @root>
```
We can see that we've queried the `users` table in the database for a row whose
`id` column has the value `1`, and Active Record has translated that database
record into a Ruby object that we can interact with. Try some of the following:
- `user.username`
- `user.created_at`
- `user.admin`
By convention, column names are directly translated into Ruby object attributes,
so you should be able to do `user.<column_name>` to view the attribute's value.
Also by convention, Active Record class names (singular and in camel case) map
directly onto table names (plural and in snake case) and vice versa. For example,
the `users` table maps to the `User` class, while the `application_settings`
table maps to the `ApplicationSetting` class.
You can find a list of tables and column names in the Rails database schema,
available at `/opt/gitlab/embedded/service/gitlab-rails/db/schema.rb`.
You can also look up an object from the database by attribute name:
```ruby
user = User.find_by(username: 'root')
```
Which would return:
```ruby
D, [2020-03-05T17:03:24.696493 #910] DEBUG -- : User Load (2.1ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'root' LIMIT 1
=> #<User id:1 @root>
```
Give the following a try:
- `User.find_by(username: 'root')`
- `User.where.not(admin: true)`
- `User.where('created_at < ?', 7.days.ago)`
Did you notice that the last two commands returned an `ActiveRecord::Relation`
object that appeared to contain multiple `User` objects?
Up to now, we've been using `.find` or `.find_by`, which are designed to return
only a single object (notice the `LIMIT 1` in the generated SQL query?).
`.where` is used when it is desirable to get a collection of objects.
Let's get a collection of non-administrator users and see what we can do with it:
```ruby
users = User.where.not(admin: true)
```
Which would return:
```ruby
D, [2020-03-05T17:11:16.845387 #910] DEBUG -- : User Load (2.8ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE LIMIT 11
=> #<ActiveRecord::Relation [#<User id:3 @support-bot>, #<User id:7 @alert-bot>, #<User id:5 @carrie>, #<User id:4 @bernice>, #<User id:2 @anne>]>
```
Now, try the following:
- `users.count`
- `users.order(created_at: :desc)`
- `users.where(username: 'support-bot')`
In the last command, we see that we can chain `.where` statements to generate
more complex queries. Notice also that while the collection returned contains
only a single object, we cannot directly interact with it:
```ruby
users.where(username: 'support-bot').username
```
Which would return:
```ruby
Traceback (most recent call last):
1: from (irb):37
D, [2020-03-05T17:18:25.637607 #910] DEBUG -- : User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE AND "users"."username" = 'support-bot' LIMIT 11
NoMethodError (undefined method `username' for #<ActiveRecord::Relation [#<User id:3 @support-bot>]>)
Did you mean? by_username
```
Let's retrieve the single object from the collection by using the `.first`
method to get the first item in the collection:
```ruby
users.where(username: 'support-bot').first.username
```
We now get the result we wanted:
```ruby
D, [2020-03-05T17:18:30.406047 #910] DEBUG -- : User Load (2.6ms) SELECT "users".* FROM "users" WHERE "users"."admin" != TRUE AND "users"."username" = 'support-bot' ORDER BY "users"."id" ASC LIMIT 1
=> "support-bot"
```
For more on different ways to retrieve data from the database using Active
Record, see the [Active Record Query Interface documentation](https://guides.rubyonrails.org/active_record_querying.html).
## Query the database using an Active Record model
```ruby
m = Model.where('attribute like ?', 'ex%')
# for example to query the projects
projects = Project.where('path like ?', 'Oumua%')
```
### Modifying Active Record objects
In the previous section, we learned about retrieving database records using
Active Record. Now, let's learn how to write changes to the database.
First, let's retrieve the `root` user:
```ruby
user = User.find_by(username: 'root')
```
Next, let's try updating the user's password:
```ruby
user.password = 'password'
user.save
```
Which would return:
```ruby
Enqueued ActionMailer::MailDeliveryJob (Job ID: 05915c4e-c849-4e14-80bb-696d5ae22065) to Sidekiq(mailers) with arguments: "DeviseMailer", "password_change", "deliver_now", #<GlobalID:0x00007f42d8ccebe8 @uri=#<URI::GID gid://gitlab/User/1>>
=> true
```
Here, we see that the `.save` command returned `true`, indicating that the
password change was successfully saved to the database.
We also see that the save operation triggered some other action -- in this case
a background job to deliver an email notification. This is an example of an
[Active Record callback](https://guides.rubyonrails.org/active_record_callbacks.html)
-- code which is designated to run in response to events in the Active Record
object lifecycle. This is also why using the Rails console is preferred when
direct changes to data is necessary as changes made via direct database queries
do not trigger these callbacks.
It's also possible to update attributes in a single line:
```ruby
user.update(password: 'password')
```
Or update multiple attributes at once:
```ruby
user.update(password: 'password', email: 'hunter2@example.com')
```
Now, let's try something different:
```ruby
# Retrieve the object again so we get its latest state
user = User.find_by(username: 'root')
user.password = 'password'
user.password_confirmation = 'hunter2'
user.save
```
This returns `false`, indicating that the changes we made were not saved to the
database. You can probably guess why, but let's find out for sure:
```ruby
user.save!
```
This should return:
```ruby
Traceback (most recent call last):
1: from (irb):64
ActiveRecord::RecordInvalid (Validation failed: Password confirmation doesn't match Password)
```
Aha! We've tripped an [Active Record Validation](https://guides.rubyonrails.org/active_record_validations.html).
Validations are business logic put in place at the application-level to prevent
unwanted data from being saved to the database and in most cases come with
helpful messages letting you know how to fix the problem inputs.
We can also add the bang (Ruby speak for `!`) to `.update`:
```ruby
user.update!(password: 'password', password_confirmation: 'hunter2')
```
In Ruby, method names ending with `!` are commonly known as "bang methods." By
convention, the bang indicates that the method directly modifies the object it
is acting on, as opposed to returning the transformed result and leaving the
underlying object untouched. For Active Record methods that write to the
database, bang methods also serve an additional function: they raise an
explicit exception whenever an error occurs, instead of just returning `false`.
We can also skip validations entirely:
```ruby
# Retrieve the object again so we get its latest state
user = User.find_by(username: 'root')
user.password = 'password'
user.password_confirmation = 'hunter2'
user.save!(validate: false)
```
This is not recommended because validations are usually put in place to ensure the
integrity and consistency of user-provided data.
A validation error prevents the entire object from being saved to
the database. You can see a little of this in the section below. If you're getting
a mysterious red banner in the GitLab UI when submitting a form, this can often
be the fastest way to get to the root of the problem.
### Interacting with Active Record objects
At the end of the day, Active Record objects are just standard Ruby objects. As
such, we can define methods on them which perform arbitrary actions.
For example, GitLab developers have added some methods which help with
two-factor authentication:
```ruby
def disable_two_factor!
transaction do
update(
otp_required_for_login: false,
encrypted_otp_secret: nil,
encrypted_otp_secret_iv: nil,
encrypted_otp_secret_salt: nil,
otp_grace_period_started_at: nil,
otp_backup_codes: nil
)
self.webauthn_registrations.destroy_all # rubocop: disable DestroyAll
end
end
def two_factor_enabled?
two_factor_otp_enabled? || two_factor_webauthn_enabled?
end
```
(See: `/opt/gitlab/embedded/service/gitlab-rails/app/models/user.rb`)
We can then use these methods on any user object:
```ruby
user = User.find_by(username: 'root')
user.two_factor_enabled?
user.disable_two_factor!
```
Some methods are defined by gems, or Ruby software packages, which GitLab uses.
For example, the [StateMachines](https://github.com/state-machines/state_machines-activerecord)
gem which GitLab uses to manage user state:
```ruby
state_machine :state, initial: :active do
event :block do
...
event :activate do
...
end
```
Give it a try:
```ruby
user = User.find_by(username: 'root')
user.state
user.block
user.state
user.activate
user.state
```
Earlier, we mentioned that a validation error prevents the entire object
from being saved to the database. Let's see how this can have unexpected
interactions:
```ruby
user.password = 'password'
user.password_confirmation = 'hunter2'
user.block
```
We get `false` returned! Let's find out what happened by adding a bang as we did
earlier:
```ruby
user.block!
```
Which would return:
```ruby
Traceback (most recent call last):
1: from (irb):87
StateMachines::InvalidTransition (Cannot transition state via :block from :active (Reason(s): Password confirmation doesn't match Password))
```
We see that a validation error from what feels like a completely separate
attribute comes back to haunt us when we try to update the user in any way.
In practical terms, we sometimes see this happen with GitLab administration settings --
validations are sometimes added or changed in a GitLab update, resulting in
previously saved settings now failing validation. Because you can only update
a subset of settings at once through the UI, in this case the only way to get
back to a good state is direct manipulation via Rails console.
### Commonly used Active Record models and how to look up objects
**Get a user by primary email address or username**:
```ruby
User.find_by(email: 'admin@example.com')
User.find_by(username: 'root')
```
**Get a user by primary OR secondary email address**:
```ruby
User.find_by_any_email('user@example.com')
```
The `find_by_any_email` method is a custom method added by GitLab developers rather
than a Rails-provided default method.
**Get a collection of administrator users**:
```ruby
User.admins
```
`admins` is a [scope convenience method](https://guides.rubyonrails.org/active_record_querying.html#scopes)
which does `where(admin: true)` under the hood.
**Get a project by its path**:
```ruby
Project.find_by_full_path('group/subgroup/project')
```
`find_by_full_path` is a custom method added by GitLab developers rather
than a Rails-provided default method.
**Get a project's issue or merge request by its numeric ID**:
```ruby
project = Project.find_by_full_path('group/subgroup/project')
project.issues.find_by(iid: 42)
project.merge_requests.find_by(iid: 42)
```
`iid` means "internal ID" and is how we keep issue and merge request IDs
scoped to each GitLab project.
**Get a group by its path**:
```ruby
Group.find_by_full_path('group/subgroup')
```
**Get a group's related groups**:
```ruby
group = Group.find_by_full_path('group/subgroup')
# Get a group's parent group
group.parent
# Get a group's child groups
group.children
```
**Get a group's projects**:
```ruby
group = Group.find_by_full_path('group/subgroup')
# Get group's immediate child projects
group.projects
# Get group's child projects, including those in subgroups
group.all_projects
```
**Get CI pipeline or builds**:
```ruby
Ci::Pipeline.find(4151)
Ci::Build.find(66124)
```
The pipeline and job ID numbers increment globally across your GitLab
instance, so there's no requirement to use an internal ID attribute to look them up,
unlike with issues or merge requests.
**Get the current application settings object**:
```ruby
ApplicationSetting.current
```
### Open object in `irb`
{{< alert type="warning" >}}
Commands that change data can cause damage if not run correctly or under the right conditions. Always run commands in a test environment first and have a backup instance ready to restore.
{{< /alert >}}
Sometimes it is easier to go through a method if you are in the context of the object. You can shim into the namespace of `Object` to let you open `irb` in the context of any object:
```ruby
Object.define_method(:irb) { binding.irb }
project = Project.last
# => #<Project id:2537 root/discard>>
project.irb
# Notice new context
irb(#<Project>)> web_url
# => "https://gitlab-example/root/discard"
```
## Troubleshooting
### Rails Runner `syntax error`
The `gitlab-rails` command executes Rails Runner using a non-root account and group, by default: `git:git`.
If the non-root account cannot find the Ruby script filename passed to `gitlab-rails runner`
you may get a syntax error, not an error that the file couldn't be accessed.
A common reason for this is that the script has been put in the root account's home directory.
`runner` tries to parse the path and file parameter as Ruby code.
For example:
```plaintext
[root ~]# echo 'puts "hello world"' > ./helloworld.rb
[root ~]# sudo gitlab-rails runner ./helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
/opt/gitlab/..../runner_command.rb:45: syntax error, unexpected '.'
./helloworld.rb
^
[root ~]# sudo gitlab-rails runner /root/helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
/opt/gitlab/..../runner_command.rb:45: unknown regexp options - hllwrld
[root ~]# mv ~/helloworld.rb /tmp
[root ~]# sudo gitlab-rails runner /tmp/helloworld.rb
hello world
```
A meaningful error should be generated if the directory can be accessed, but the file cannot:
```plaintext
[root ~]# chmod 400 /tmp/helloworld.rb
[root ~]# sudo gitlab-rails runner /tmp/helloworld.rb
Traceback (most recent call last):
[traceback removed]
/opt/gitlab/..../runner_command.rb:42:in `load': cannot load such file -- /tmp/helloworld.rb (LoadError)
```
In case you encounter a similar error to this:
```plaintext
[root ~]# sudo gitlab-rails runner helloworld.rb
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.
undefined local variable or method `helloworld' for main:Object
```
You can either move the file to the `/tmp` directory or create a new directory owned by the user `git` and save the script in that directory as illustrated below:
```shell
sudo mkdir /scripts
sudo mv /script_path/helloworld.rb /scripts
sudo chown -R git:git /scripts
sudo chmod 700 /scripts
sudo gitlab-rails runner /scripts/helloworld.rb
```
### Filtered console output
Some output in the console might be filtered by default to prevent leaks of certain values
like variables, logs, or secrets. This output displays as `[FILTERED]`. For example:
```plaintext
> Plan.default.actual_limits
=> ci_instance_level_variables: "[FILTERED]",
```
To work around the filtering, read the values directly from the object. For example:
```plaintext
> Plan.default.limits.ci_instance_level_variables
=> 25
```
|
https://docs.gitlab.com/administration/gitlab_sshd
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/gitlab_sshd.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
gitlab_sshd.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
`gitlab-sshd`
|
Configure `gitlab-sshd`, a lightweight alternative to OpenSSH, for your GitLab instance.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
`gitlab-sshd` is [a standalone SSH server](https://gitlab.com/gitlab-org/gitlab-shell/-/tree/main/internal/sshd)
written in Go. It is a lightweight alternative to OpenSSH. It is part of the `gitlab-shell` package and
handles [SSH operations](https://gitlab.com/gitlab-org/gitlab-shell/-/blob/71a7f34a476f778e62f8fe7a453d632d395eaf8f/doc/features.md).
While OpenSSH uses a restricted shell approach, `gitlab-sshd`:
- Functions as a modern multi-threaded server application.
- Uses Remote Procedure Calls (RPCs) instead of the SSH transport protocol.
- Uses less memory than OpenSSH.
- Supports [group access restriction by IP address](../../user/group/access_and_permissions.md#restrict-group-access-by-ip-address)
for applications running behind a proxy.
For more details about the implementation, see [the blog post](https://about.gitlab.com/blog/2022/08/17/why-we-have-implemented-our-own-sshd-solution-on-gitlab-sass/).
If you are considering switching from OpenSSH to `gitlab-sshd`, consider:
- PROXY protocol: `gitlab-sshd` supports the PROXY protocol, allowing it to run behind proxy
servers like HAProxy. This feature is not enabled by default but [can be enabled](#proxy-protocol-support).
- SSH certificates: `gitlab-sshd` does not support SSH certificates. For more information, see
[issue 655](https://gitlab.com/gitlab-org/gitlab-shell/-/issues/655).
- 2FA recovery codes: `gitlab-sshd` does not support 2FA recovery code regeneration.
Attempting to run `2fa_recovery_codes` results in the error:
`remote: ERROR: Unknown command: 2fa_recovery_codes`. See
[the discussion](https://gitlab.com/gitlab-org/gitlab-shell/-/issues/766#note_1906707753) for details.
The capabilities of GitLab Shell extend beyond Git operations and can be used for various
SSH-based interactions with GitLab.
## Enable `gitlab-sshd`
To use `gitlab-sshd`:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
The following instructions enable `gitlab-sshd` on a different port than OpenSSH:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_sshd['enable'] = true
gitlab_sshd['listen_address'] = '[::]:2222' # Adjust the port accordingly
```
1. Optional. By default, Linux package installations generate SSH host keys for `gitlab-sshd` if
they do not exist in `/var/opt/gitlab/gitlab-sshd`. If you wish to disable this automatic generation, add this line:
```ruby
gitlab_sshd['generate_host_keys'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
By default, `gitlab-sshd` runs as the `git` user. As a result, `gitlab-sshd` cannot
run on privileged port numbers lower than 1024. This means users must
access Git with the `gitlab-sshd` port, or use a load balancer that
directs SSH traffic to the `gitlab-sshd` port to hide this.
Users may see host key warnings because the newly-generated host keys
differ from the OpenSSH host keys. Consider disabling host key
generation and copy the existing OpenSSH host keys into
`/var/opt/gitlab/gitlab-sshd` if this is an issue.
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
The following instructions switch OpenSSH in favor of `gitlab-sshd`:
1. Set the `gitlab-shell` charts `sshDaemon` option to
[`gitlab-sshd`](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#installation-command-line-options).
For example:
```yaml
gitlab:
gitlab-shell:
sshDaemon: gitlab-sshd
```
1. Perform a Helm upgrade.
By default, `gitlab-sshd` listens for:
- External requests on port 22 (`global.shell.port`).
- Internal requests on port 2222 (`gitlab.gitlab-shell.service.internalPort`).
You can [configure different ports in the Helm chart](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#configuration).
{{< /tab >}}
{{< /tabs >}}
## PROXY protocol support
Load balancers in front of `gitlab-sshd` cause GitLab to report the proxy IP address instead of the
client IP address. To obtain the real IP address, `gitlab-sshd` supports the
[PROXY protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt).
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
To enable the PROXY protocol:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_sshd['proxy_protocol'] = true
# Proxy protocol policy ("use", "require", "reject", "ignore"), "use" is the default value
gitlab_sshd['proxy_policy'] = "use"
```
For more information about the `gitlab_sshd['proxy_policy']` options, see the
[`go-proxyproto` library](https://github.com/pires/go-proxyproto/blob/4ba2eb817d7a57a4aafdbd3b82ef0410806b533d/policy.go#L20-L35).
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Set the [`gitlab.gitlab-shell.config` options](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#installation-command-line-options). For example:
```yaml
gitlab:
gitlab-shell:
config:
proxyProtocol: true
proxyPolicy: "use"
```
1. Perform a Helm upgrade.
{{< /tab >}}
{{< /tabs >}}
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Configure `gitlab-sshd`, a lightweight alternative to OpenSSH, for your
GitLab instance.
title: '`gitlab-sshd`'
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
`gitlab-sshd` is [a standalone SSH server](https://gitlab.com/gitlab-org/gitlab-shell/-/tree/main/internal/sshd)
written in Go. It is a lightweight alternative to OpenSSH. It is part of the `gitlab-shell` package and
handles [SSH operations](https://gitlab.com/gitlab-org/gitlab-shell/-/blob/71a7f34a476f778e62f8fe7a453d632d395eaf8f/doc/features.md).
While OpenSSH uses a restricted shell approach, `gitlab-sshd`:
- Functions as a modern multi-threaded server application.
- Uses Remote Procedure Calls (RPCs) instead of the SSH transport protocol.
- Uses less memory than OpenSSH.
- Supports [group access restriction by IP address](../../user/group/access_and_permissions.md#restrict-group-access-by-ip-address)
for applications running behind a proxy.
For more details about the implementation, see [the blog post](https://about.gitlab.com/blog/2022/08/17/why-we-have-implemented-our-own-sshd-solution-on-gitlab-sass/).
If you are considering switching from OpenSSH to `gitlab-sshd`, consider:
- PROXY protocol: `gitlab-sshd` supports the PROXY protocol, allowing it to run behind proxy
servers like HAProxy. This feature is not enabled by default but [can be enabled](#proxy-protocol-support).
- SSH certificates: `gitlab-sshd` does not support SSH certificates. For more information, see
[issue 655](https://gitlab.com/gitlab-org/gitlab-shell/-/issues/655).
- 2FA recovery codes: `gitlab-sshd` does not support 2FA recovery code regeneration.
Attempting to run `2fa_recovery_codes` results in the error:
`remote: ERROR: Unknown command: 2fa_recovery_codes`. See
[the discussion](https://gitlab.com/gitlab-org/gitlab-shell/-/issues/766#note_1906707753) for details.
The capabilities of GitLab Shell extend beyond Git operations and can be used for various
SSH-based interactions with GitLab.
## Enable `gitlab-sshd`
To use `gitlab-sshd`:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
The following instructions enable `gitlab-sshd` on a different port than OpenSSH:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_sshd['enable'] = true
gitlab_sshd['listen_address'] = '[::]:2222' # Adjust the port accordingly
```
1. Optional. By default, Linux package installations generate SSH host keys for `gitlab-sshd` if
they do not exist in `/var/opt/gitlab/gitlab-sshd`. If you wish to disable this automatic generation, add this line:
```ruby
gitlab_sshd['generate_host_keys'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
By default, `gitlab-sshd` runs as the `git` user. As a result, `gitlab-sshd` cannot
run on privileged port numbers lower than 1024. This means users must
access Git with the `gitlab-sshd` port, or use a load balancer that
directs SSH traffic to the `gitlab-sshd` port to hide this.
Users may see host key warnings because the newly-generated host keys
differ from the OpenSSH host keys. Consider disabling host key
generation and copy the existing OpenSSH host keys into
`/var/opt/gitlab/gitlab-sshd` if this is an issue.
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
The following instructions switch OpenSSH in favor of `gitlab-sshd`:
1. Set the `gitlab-shell` charts `sshDaemon` option to
[`gitlab-sshd`](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#installation-command-line-options).
For example:
```yaml
gitlab:
gitlab-shell:
sshDaemon: gitlab-sshd
```
1. Perform a Helm upgrade.
By default, `gitlab-sshd` listens for:
- External requests on port 22 (`global.shell.port`).
- Internal requests on port 2222 (`gitlab.gitlab-shell.service.internalPort`).
You can [configure different ports in the Helm chart](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#configuration).
{{< /tab >}}
{{< /tabs >}}
## PROXY protocol support
Load balancers in front of `gitlab-sshd` cause GitLab to report the proxy IP address instead of the
client IP address. To obtain the real IP address, `gitlab-sshd` supports the
[PROXY protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt).
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
To enable the PROXY protocol:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_sshd['proxy_protocol'] = true
# Proxy protocol policy ("use", "require", "reject", "ignore"), "use" is the default value
gitlab_sshd['proxy_policy'] = "use"
```
For more information about the `gitlab_sshd['proxy_policy']` options, see the
[`go-proxyproto` library](https://github.com/pires/go-proxyproto/blob/4ba2eb817d7a57a4aafdbd3b82ef0410806b533d/policy.go#L20-L35).
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Set the [`gitlab.gitlab-shell.config` options](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/#installation-command-line-options). For example:
```yaml
gitlab:
gitlab-shell:
config:
proxyProtocol: true
proxyPolicy: "use"
```
1. Perform a Helm upgrade.
{{< /tab >}}
{{< /tabs >}}
|
https://docs.gitlab.com/administration/ssh_certificates
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/ssh_certificates.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
ssh_certificates.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
User lookup via OpenSSH's AuthorizedPrincipalsCommand
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The default SSH authentication for GitLab requires users to upload their SSH
public keys before they can use the SSH transport.
In centralized (for example, corporate) environments this can be a hassle
operationally, particularly if the SSH keys are temporary keys issued to the
user, including ones that expire 24 hours after issuing.
In such setups some external automated process is needed to constantly
upload the new keys to GitLab.
{{< alert type="warning" >}}
OpenSSH version 6.9+ is required because `AuthorizedKeysCommand` must be
able to accept a fingerprint. Check the version of OpenSSH on your server.
{{< /alert >}}
## Why use OpenSSH certificates?
When you use OpenSSH certificates, information about which GitLab user owns the key is
encoded in the key itself. OpenSSH guarantees that users can't fake this because they need
access to the private CA signing key.
When correctly set up, this does away with the requirement of
uploading user SSH keys to GitLab entirely.
## Setting up SSH certificate lookup via GitLab Shell
How to fully set up SSH certificates is outside the scope of this
document. See
[OpenSSH's`PROTOCOL.certkeys`](https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD)
for how it works, for example
[RedHat's documentation about it](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/sec-using_openssh_certificate_authentication).
We assume that you already have SSH certificates set up, and have
added the `TrustedUserCAKeys` of your CA to your `sshd_config`, for example:
```plaintext
TrustedUserCAKeys /etc/security/mycompany_user_ca.pub
```
Usually `TrustedUserCAKeys` would not be scoped under a `Match User git`
in such a setup because it would also be used for system logins to
the GitLab server itself, but your setup may vary. If the CA is only
used for GitLab consider putting this in the `Match User git` section
(described below).
The SSH certificates being issued by that CA **must** have a "key ID"
corresponding to that user's username on GitLab, for example (some output
omitted for brevity):
```shell
$ ssh-add -L | grep cert | ssh-keygen -L -f -
(stdin):1:
Type: ssh-rsa-cert-v01@openssh.com user certificate
Public key: RSA-CERT SHA256:[...]
Signing CA: RSA SHA256:[...]
Key ID: "aearnfjord"
Serial: 8289829611021396489
Valid: from 2018-07-18T09:49:00 to 2018-07-19T09:50:34
Principals:
sshUsers
[...]
[...]
```
Technically that's not strictly true, for example, it could be
`prod-aearnfjord` if it's a SSH certificate you'd usually sign in to
servers as the `prod-aearnfjord` user, but then you must specify your
own `AuthorizedPrincipalsCommand` to do that mapping instead of using
our provided default.
The important part is that the `AuthorizedPrincipalsCommand` must be
able to map from the "key ID" to a GitLab username because the
default command we ship assumes there's a 1=1 mapping between the two.
The whole point of this is to allow us to extract a GitLab
username from the key itself, instead of relying on something like the
default public key to username mapping.
Then, in your `sshd_config` set up `AuthorizedPrincipalsCommand` for
the `git` user. Hopefully you can use the default one shipped with
GitLab:
```plaintext
Match User git
AuthorizedPrincipalsCommandUser root
AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check %i sshUsers
```
This command emits output that looks something like:
```shell
command="/opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell username-{KEY_ID}",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty {PRINCIPAL}
```
Where `{KEY_ID}` is the `%i` argument passed to the script
(for example, `aeanfjord`), and `{PRINCIPAL}` is the principal passed to it
(for example, `sshUsers`).
You need to customize the `sshUsers` part of that. It should be
some principal that's guaranteed to be part of the key for all users
who can sign in to GitLab, or you must provide a list of principals,
one of which is present for the user, for example:
```plaintext
[...]
AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check %i sshUsers windowsUsers
```
## Principals and security
You can supply as many principals as you want, these are turned
into multiple lines of `authorized_keys` output, as described in the
`AuthorizedPrincipalsFile` documentation in `sshd_config(5)`.
Usually when using the `AuthorizedKeysCommand` with OpenSSH the
principal is some "group" that's allowed to sign in to that
server. However with GitLab it's only used to appease OpenSSH's
requirement for it, we effectively only care about the "key ID" being
correct. Once that's extracted GitLab enforces its own ACLs for
that user (for example, what projects the user can access).
It's therefore fine to be overly generous in what you accept. For example, if the user has no access
to GitLab, an error is produced with a message about an invalid user.
message about this being an invalid user.
## Interaction with the `authorized_keys` file
If SSH certificates are set up as described previously, they can be used with the `authorized_keys` file so that the `authorized_keys` file serves as a fallback.
When the `AuthorizedPrincipalsCommand` is unable to authenticate a user, OpenSSH reverts to checking the `~/.ssh/authorized_keys` file or using the `AuthorizedKeysCommand`.
Therefore, you might still need to use [Fast lookup of authorized SSH keys in the database](fast_ssh_key_lookup.md) with SSH certificates.
For most users, SSH certificates handle authentication by using the `AuthorizedPrincipalsCommand`, with the `~/.ssh/authorized_keys` file primarily serving as a fallback for
specific cases such as deploy keys. However, depending on your setup, you might find that using the `AuthorizedPrincipalsCommand` exclusively for typical users is sufficient.
In such cases, the `authorized_keys` file is only necessary for automated deployment key access or other specific scenarios.
Consider the balance between the number of keys for typical users (especially if they are frequently renewed) and deploy keys to help you determine whether maintaining the
`authorized_keys` fallback is necessary for your environment.
## Other security caveats
Users can still bypass SSH certificate authentication by manually
uploading an SSH public key to their profile, relying on the
`~/.ssh/authorized_keys` fallback to authenticate it.
There's an [open issue](https://gitlab.com/gitlab-org/gitlab/-/issues/23260)
to add a setting that prevents users from uploading SSH keys that are not deploy keys.
You can build a check to enforce this restriction yourself.
For example, provide a custom `AuthorizedKeysCommand` which checks
if the discovered key-ID returned from `gitlab-shell-authorized-keys-check`
is a deploy key or not (all non-deploy keys should be refused).
## Disabling the global warning about users lacking SSH keys
By default GitLab shows a "You won't be able to pull or push
project code via SSH" warning to users who have not uploaded an SSH
key to their profile.
This is counterproductive when using SSH certificates because users
aren't expected to upload their own keys.
To disable this warning globally, go to "Application settings ->
Account and limit settings" and disable the "Show user add SSH key
message" setting.
This setting was added specifically for use with SSH certificates, but
can be turned off without using them if you'd like to hide the warning
for some other reason.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: User lookup via OpenSSH's AuthorizedPrincipalsCommand
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The default SSH authentication for GitLab requires users to upload their SSH
public keys before they can use the SSH transport.
In centralized (for example, corporate) environments this can be a hassle
operationally, particularly if the SSH keys are temporary keys issued to the
user, including ones that expire 24 hours after issuing.
In such setups some external automated process is needed to constantly
upload the new keys to GitLab.
{{< alert type="warning" >}}
OpenSSH version 6.9+ is required because `AuthorizedKeysCommand` must be
able to accept a fingerprint. Check the version of OpenSSH on your server.
{{< /alert >}}
## Why use OpenSSH certificates?
When you use OpenSSH certificates, information about which GitLab user owns the key is
encoded in the key itself. OpenSSH guarantees that users can't fake this because they need
access to the private CA signing key.
When correctly set up, this does away with the requirement of
uploading user SSH keys to GitLab entirely.
## Setting up SSH certificate lookup via GitLab Shell
How to fully set up SSH certificates is outside the scope of this
document. See
[OpenSSH's`PROTOCOL.certkeys`](https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD)
for how it works, for example
[RedHat's documentation about it](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/sec-using_openssh_certificate_authentication).
We assume that you already have SSH certificates set up, and have
added the `TrustedUserCAKeys` of your CA to your `sshd_config`, for example:
```plaintext
TrustedUserCAKeys /etc/security/mycompany_user_ca.pub
```
Usually `TrustedUserCAKeys` would not be scoped under a `Match User git`
in such a setup because it would also be used for system logins to
the GitLab server itself, but your setup may vary. If the CA is only
used for GitLab consider putting this in the `Match User git` section
(described below).
The SSH certificates being issued by that CA **must** have a "key ID"
corresponding to that user's username on GitLab, for example (some output
omitted for brevity):
```shell
$ ssh-add -L | grep cert | ssh-keygen -L -f -
(stdin):1:
Type: ssh-rsa-cert-v01@openssh.com user certificate
Public key: RSA-CERT SHA256:[...]
Signing CA: RSA SHA256:[...]
Key ID: "aearnfjord"
Serial: 8289829611021396489
Valid: from 2018-07-18T09:49:00 to 2018-07-19T09:50:34
Principals:
sshUsers
[...]
[...]
```
Technically that's not strictly true, for example, it could be
`prod-aearnfjord` if it's a SSH certificate you'd usually sign in to
servers as the `prod-aearnfjord` user, but then you must specify your
own `AuthorizedPrincipalsCommand` to do that mapping instead of using
our provided default.
The important part is that the `AuthorizedPrincipalsCommand` must be
able to map from the "key ID" to a GitLab username because the
default command we ship assumes there's a 1=1 mapping between the two.
The whole point of this is to allow us to extract a GitLab
username from the key itself, instead of relying on something like the
default public key to username mapping.
Then, in your `sshd_config` set up `AuthorizedPrincipalsCommand` for
the `git` user. Hopefully you can use the default one shipped with
GitLab:
```plaintext
Match User git
AuthorizedPrincipalsCommandUser root
AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check %i sshUsers
```
This command emits output that looks something like:
```shell
command="/opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell username-{KEY_ID}",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty {PRINCIPAL}
```
Where `{KEY_ID}` is the `%i` argument passed to the script
(for example, `aeanfjord`), and `{PRINCIPAL}` is the principal passed to it
(for example, `sshUsers`).
You need to customize the `sshUsers` part of that. It should be
some principal that's guaranteed to be part of the key for all users
who can sign in to GitLab, or you must provide a list of principals,
one of which is present for the user, for example:
```plaintext
[...]
AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check %i sshUsers windowsUsers
```
## Principals and security
You can supply as many principals as you want, these are turned
into multiple lines of `authorized_keys` output, as described in the
`AuthorizedPrincipalsFile` documentation in `sshd_config(5)`.
Usually when using the `AuthorizedKeysCommand` with OpenSSH the
principal is some "group" that's allowed to sign in to that
server. However with GitLab it's only used to appease OpenSSH's
requirement for it, we effectively only care about the "key ID" being
correct. Once that's extracted GitLab enforces its own ACLs for
that user (for example, what projects the user can access).
It's therefore fine to be overly generous in what you accept. For example, if the user has no access
to GitLab, an error is produced with a message about an invalid user.
message about this being an invalid user.
## Interaction with the `authorized_keys` file
If SSH certificates are set up as described previously, they can be used with the `authorized_keys` file so that the `authorized_keys` file serves as a fallback.
When the `AuthorizedPrincipalsCommand` is unable to authenticate a user, OpenSSH reverts to checking the `~/.ssh/authorized_keys` file or using the `AuthorizedKeysCommand`.
Therefore, you might still need to use [Fast lookup of authorized SSH keys in the database](fast_ssh_key_lookup.md) with SSH certificates.
For most users, SSH certificates handle authentication by using the `AuthorizedPrincipalsCommand`, with the `~/.ssh/authorized_keys` file primarily serving as a fallback for
specific cases such as deploy keys. However, depending on your setup, you might find that using the `AuthorizedPrincipalsCommand` exclusively for typical users is sufficient.
In such cases, the `authorized_keys` file is only necessary for automated deployment key access or other specific scenarios.
Consider the balance between the number of keys for typical users (especially if they are frequently renewed) and deploy keys to help you determine whether maintaining the
`authorized_keys` fallback is necessary for your environment.
## Other security caveats
Users can still bypass SSH certificate authentication by manually
uploading an SSH public key to their profile, relying on the
`~/.ssh/authorized_keys` fallback to authenticate it.
There's an [open issue](https://gitlab.com/gitlab-org/gitlab/-/issues/23260)
to add a setting that prevents users from uploading SSH keys that are not deploy keys.
You can build a check to enforce this restriction yourself.
For example, provide a custom `AuthorizedKeysCommand` which checks
if the discovered key-ID returned from `gitlab-shell-authorized-keys-check`
is a deploy key or not (all non-deploy keys should be refused).
## Disabling the global warning about users lacking SSH keys
By default GitLab shows a "You won't be able to pull or push
project code via SSH" warning to users who have not uploaded an SSH
key to their profile.
This is counterproductive when using SSH certificates because users
aren't expected to upload their own keys.
To disable this warning globally, go to "Application settings ->
Account and limit settings" and disable the "Show user add SSH key
message" setting.
This setting was added specifically for use with SSH certificates, but
can be turned off without using them if you'd like to hide the warning
for some other reason.
|
https://docs.gitlab.com/administration/operations
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Maintain GitLab
|
Backup and restore, move repos, maintenance tasks.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Keep your GitLab instance up and running.
- [Housekeeping](../housekeeping.md)
- [Activate GitLab EE with license](../license_file.md)
- [Fast SSH key lookup](fast_ssh_key_lookup.md)
- [File system benchmarking](filesystem_benchmarking.md)
- [`gitlab-sshd`](gitlab_sshd.md)
- [Rails console](rails_console.md)
- [Use SSH certificates](ssh_certificates.md)
- [Enable encrypted configuration](../encrypted_configuration.md)
- [Rake tasks](../../administration/raketasks/_index.md)
- [Backup and restore](../backup_restore/_index.md)
- [Dormant project deletion](../dormant_project_deletion.md)
- [Move repositories](moving_repositories.md)
- [Read-only state](../read_only_gitlab.md)
- [Restart GitLab](../restart_gitlab.md)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Backup and restore, move repos, maintenance tasks.
title: Maintain GitLab
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Keep your GitLab instance up and running.
- [Housekeeping](../housekeeping.md)
- [Activate GitLab EE with license](../license_file.md)
- [Fast SSH key lookup](fast_ssh_key_lookup.md)
- [File system benchmarking](filesystem_benchmarking.md)
- [`gitlab-sshd`](gitlab_sshd.md)
- [Rails console](rails_console.md)
- [Use SSH certificates](ssh_certificates.md)
- [Enable encrypted configuration](../encrypted_configuration.md)
- [Rake tasks](../../administration/raketasks/_index.md)
- [Backup and restore](../backup_restore/_index.md)
- [Dormant project deletion](../dormant_project_deletion.md)
- [Move repositories](moving_repositories.md)
- [Read-only state](../read_only_gitlab.md)
- [Restart GitLab](../restart_gitlab.md)
|
https://docs.gitlab.com/administration/filesystem_benchmarking
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/filesystem_benchmarking.md
|
2025-08-13
|
doc/administration/operations
|
[
"doc",
"administration",
"operations"
] |
filesystem_benchmarking.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
File system performance benchmarking
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
File system performance has a big impact on overall GitLab performance,
especially for actions that read or write to Git repositories. This information
helps benchmark file system performance against known good and bad real-world
systems.
When talking about file system performance the biggest concern is
with Network File Systems (NFS). However, even some local disks can have slow
I/O. The information on this page can be used for either scenario.
## Executing benchmarks
### Benchmarking with `fio`
You should use
[Fio](https://fio.readthedocs.io/en/latest/fio_doc.html) to test I/O
performance. This test should be run both on the NFS server and on the
application nodes that talk to the NFS server.
To install:
- On Ubuntu: `apt install fio`.
- On `yum`-managed environments: `yum install fio`.
Then run the following:
```shell
fio --randrepeat=1 --ioengine=libaio --direct=1 --gtod_reduce=1 --name=test --bs=4k --iodepth=64 --readwrite=randrw --rwmixread=75 --size=4G --filename=/path/to/git-data/testfile
```
This creates a 4 GB file in `/path/to/git-data/testfile`. It performs
4 KB reads and writes using a 75%/25% split in the file, with 64
operations running at a time. Be sure to delete the file after the test
completes.
The output varies depending on what version of `fio` installed. The following
is an example output from `fio` v2.2.10 on a networked solid-state drive (SSD):
```plaintext
test: (g=0): rw=randrw, bs=4K-4K/4K-4K/4K-4K, ioengine=libaio, iodepth=64
fio-2.2.10
Starting 1 process
test: Laying out IO file(s) (1 file(s) / 1024MB)
Jobs: 1 (f=1): [m(1)] [100.0% done] [131.4MB/44868KB/0KB /s] [33.7K/11.3K/0 iops] [eta 00m:00s]
test: (groupid=0, jobs=1): err= 0: pid=10287: Sat Feb 2 17:40:10 2019
read : io=784996KB, bw=133662KB/s, iops=33415, runt= 5873msec
write: io=263580KB, bw=44880KB/s, iops=11219, runt= 5873msec
cpu : usr=6.56%, sys=23.11%, ctx=266267, majf=0, minf=8
IO depths : 1=0.1%, 2=0.1%, 4=0.1%, 8=0.1%, 16=0.1%, 32=0.1%, >=64=100.0%
submit : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
complete : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.1%, >=64=0.0%
issued : total=r=196249/w=65895/d=0, short=r=0/w=0/d=0, drop=r=0/w=0/d=0
latency : target=0, window=0, percentile=100.00%, depth=64
Run status group 0 (all jobs):
READ: io=784996KB, aggrb=133661KB/s, minb=133661KB/s, maxb=133661KB/s, mint=5873msec, maxt=5873msec
WRITE: io=263580KB, aggrb=44879KB/s, minb=44879KB/s, maxb=44879KB/s, mint=5873msec, maxt=5873msec
```
Notice the `iops` values in this output. In this example, the SSD
performed 33,415 read operations per second and 11,219 write operations
per second. A spinning disk might yield 2,000 and 700 read and write
operations per second.
### Simple benchmarking
{{< alert type="note" >}}
This test is naive but can be used if `fio` is not
available on the system. It's possible to receive good results on this
test but still have poor performance due to read speed and various other
factors.
{{< /alert >}}
The following one-line commands provide a quick benchmark for file system write and read
performance. This writes 1,000 small files to the directory in which it is
executed, and then reads the same 1,000 files.
1. Change into the root of the appropriate
[repository storage path](../repository_storage_paths.md).
1. Create a temporary directory for the test so it can be removed later:
```shell
mkdir test; cd test
```
1. Run the command:
```shell
time for i in {0..1000}; do echo 'test' > "test${i}.txt"; done
```
1. To benchmark read performance, run the command:
```shell
time for i in {0..1000}; do cat "test${i}.txt" > /dev/null; done
```
1. Remove the test files:
```shell
cd ../; rm -rf test
```
The output of the `time for ...` commands resemble the following. The
important metric is the `real` time.
```shell
$ time for i in {0..1000}; do echo 'test' > "test${i}.txt"; done
real 0m0.116s
user 0m0.025s
sys 0m0.091s
$ time for i in {0..1000}; do cat "test${i}.txt" > /dev/null; done
real 0m3.118s
user 0m1.267s
sys 0m1.663s
```
From experience with multiple customers, this task should take under 10
seconds to indicate good file system performance.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: File system performance benchmarking
breadcrumbs:
- doc
- administration
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
File system performance has a big impact on overall GitLab performance,
especially for actions that read or write to Git repositories. This information
helps benchmark file system performance against known good and bad real-world
systems.
When talking about file system performance the biggest concern is
with Network File Systems (NFS). However, even some local disks can have slow
I/O. The information on this page can be used for either scenario.
## Executing benchmarks
### Benchmarking with `fio`
You should use
[Fio](https://fio.readthedocs.io/en/latest/fio_doc.html) to test I/O
performance. This test should be run both on the NFS server and on the
application nodes that talk to the NFS server.
To install:
- On Ubuntu: `apt install fio`.
- On `yum`-managed environments: `yum install fio`.
Then run the following:
```shell
fio --randrepeat=1 --ioengine=libaio --direct=1 --gtod_reduce=1 --name=test --bs=4k --iodepth=64 --readwrite=randrw --rwmixread=75 --size=4G --filename=/path/to/git-data/testfile
```
This creates a 4 GB file in `/path/to/git-data/testfile`. It performs
4 KB reads and writes using a 75%/25% split in the file, with 64
operations running at a time. Be sure to delete the file after the test
completes.
The output varies depending on what version of `fio` installed. The following
is an example output from `fio` v2.2.10 on a networked solid-state drive (SSD):
```plaintext
test: (g=0): rw=randrw, bs=4K-4K/4K-4K/4K-4K, ioengine=libaio, iodepth=64
fio-2.2.10
Starting 1 process
test: Laying out IO file(s) (1 file(s) / 1024MB)
Jobs: 1 (f=1): [m(1)] [100.0% done] [131.4MB/44868KB/0KB /s] [33.7K/11.3K/0 iops] [eta 00m:00s]
test: (groupid=0, jobs=1): err= 0: pid=10287: Sat Feb 2 17:40:10 2019
read : io=784996KB, bw=133662KB/s, iops=33415, runt= 5873msec
write: io=263580KB, bw=44880KB/s, iops=11219, runt= 5873msec
cpu : usr=6.56%, sys=23.11%, ctx=266267, majf=0, minf=8
IO depths : 1=0.1%, 2=0.1%, 4=0.1%, 8=0.1%, 16=0.1%, 32=0.1%, >=64=100.0%
submit : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
complete : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.1%, >=64=0.0%
issued : total=r=196249/w=65895/d=0, short=r=0/w=0/d=0, drop=r=0/w=0/d=0
latency : target=0, window=0, percentile=100.00%, depth=64
Run status group 0 (all jobs):
READ: io=784996KB, aggrb=133661KB/s, minb=133661KB/s, maxb=133661KB/s, mint=5873msec, maxt=5873msec
WRITE: io=263580KB, aggrb=44879KB/s, minb=44879KB/s, maxb=44879KB/s, mint=5873msec, maxt=5873msec
```
Notice the `iops` values in this output. In this example, the SSD
performed 33,415 read operations per second and 11,219 write operations
per second. A spinning disk might yield 2,000 and 700 read and write
operations per second.
### Simple benchmarking
{{< alert type="note" >}}
This test is naive but can be used if `fio` is not
available on the system. It's possible to receive good results on this
test but still have poor performance due to read speed and various other
factors.
{{< /alert >}}
The following one-line commands provide a quick benchmark for file system write and read
performance. This writes 1,000 small files to the directory in which it is
executed, and then reads the same 1,000 files.
1. Change into the root of the appropriate
[repository storage path](../repository_storage_paths.md).
1. Create a temporary directory for the test so it can be removed later:
```shell
mkdir test; cd test
```
1. Run the command:
```shell
time for i in {0..1000}; do echo 'test' > "test${i}.txt"; done
```
1. To benchmark read performance, run the command:
```shell
time for i in {0..1000}; do cat "test${i}.txt" > /dev/null; done
```
1. Remove the test files:
```shell
cd ../; rm -rf test
```
The output of the `time for ...` commands resemble the following. The
important metric is the `real` time.
```shell
$ time for i in {0..1000}; do echo 'test' > "test${i}.txt"; done
real 0m0.116s
user 0m0.025s
sys 0m0.091s
$ time for i in {0..1000}; do cat "test${i}.txt" > /dev/null; done
real 0m3.118s
user 0m1.267s
sys 0m1.663s
```
From experience with multiple customers, this task should take under 10
seconds to indicate good file system performance.
|
https://docs.gitlab.com/administration/omnibus_packages
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/omnibus_packages.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
omnibus_packages.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Packages and images from the Linux package
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Below you can find some basic information on why GitLab provides packages and
a Docker image that come with bundled dependencies.
These methods are great for physical and virtual machine installations, and simple Docker installations.
## Goals
We have a few core goals with these packages:
1. Extremely easy to install, upgrade, maintain.
1. Support for a wide variety of operating systems
1. Wide support of cloud service providers
## Linux package architecture
GitLab in its core is a Ruby on Rails project. However, GitLab as a whole
application is more complex and has multiple components. If these components are
not present or are incorrectly configured, GitLab does not work or it works
unpredictably.
The GitLab Architecture Overview in the GitLab development documentation shows some of these components and how they
interact. Each of these components needs to be configured and kept up to date.
Most of the components also have external dependencies. For example, the Rails
application depends on a number of [Ruby gems](https://gitlab.com/gitlab-org/gitlab-foss/blob/master/Gemfile.lock). Some of these dependencies also
have their own external dependencies which need to be present on the Operating
System in order for them to function correctly.
Furthermore, GitLab has a monthly release cycle requiring frequent maintenance
to stay up to date.
All the things listed previously present a challenge for the user maintaining the GitLab
installation.
## External Software Dependencies
For applications such as GitLab, external dependencies usually bring the following
challenges:
- Keeping versions in sync between direct and indirect dependencies
- Availability of a version on a specific Operating System
- Version changes can introduce or remove previously used configuration
- Security implications when library is marked as vulnerable but does not have
a new version released yet
Keep in mind that if a dependency exists on your Operating System, it does not
necessarily exist on other supported OSs.
## Benefits
A few benefits of a package with bundled dependencies:
1. Minimal effort required to install GitLab.
1. Minimum configuration required to get GitLab up and running.
1. Minimum effort required to upgrade between GitLab versions.
1. Multiple platforms supported.
1. Maintenance on older platforms is greatly simplified.
1. Less effort to support potential issues.
## Drawbacks
Some drawbacks of a package with bundled dependencies:
1. Duplication with possibly existing software.
1. Less flexibility in configuration.
## Why would you install a package from the Linux package when you can use a system package?
The answer can be simplified to: less maintenance required. Instead of handling
multiple packages that can break existing functionality if the versions are
not compatible, only handle one.
Multiple packages require correct configuration in multiple locations.
Keeping configuration in sync can be error prone.
If you have the skill set to maintain all current dependencies and enough time
to handle any future dependencies that might get introduced, the previous
reasons might not be good enough for you to not use a package from the Linux package.
There are two things to keep in mind before going down this route:
1. Getting support for any problems
you encounter might be more difficult due to the number of possibilities that exist
when using a library version that is not tested by majority of users.
1. Packages from the Linux package also allow shutting off of any services that you do not need,
if you need to run a component independently. For example, you can use a
[non-bundled PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#using-a-non-packaged-postgresql-database-management-server)
with a Linux package installation.
Keep in mind that a non-standard solution like the Linux package
might be a better fit when the application has a number of moving parts.
## Docker image with multiple services
[GitLab Docker image](../../install/docker/_index.md) is based on the Linux package.
Considering that container spawned from this image contains multiple processes,
these types of containers are also referred to as 'fat containers'.
There are reasons for and against an image like this, but they are similar to
what was noted previously:
1. Very simple to get started.
1. Upgrading to the latest version is extremely simple.
1. Running separate services in multiple containers and keeping them running
can be more complex and might not be required for a given install.
This method is useful for organizations just getting started with containers and schedulers, and may not be ready for a more complex installation. This method is a great introduction, and works well for smaller organizations.
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Packages and images from the Linux package
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Below you can find some basic information on why GitLab provides packages and
a Docker image that come with bundled dependencies.
These methods are great for physical and virtual machine installations, and simple Docker installations.
## Goals
We have a few core goals with these packages:
1. Extremely easy to install, upgrade, maintain.
1. Support for a wide variety of operating systems
1. Wide support of cloud service providers
## Linux package architecture
GitLab in its core is a Ruby on Rails project. However, GitLab as a whole
application is more complex and has multiple components. If these components are
not present or are incorrectly configured, GitLab does not work or it works
unpredictably.
The GitLab Architecture Overview in the GitLab development documentation shows some of these components and how they
interact. Each of these components needs to be configured and kept up to date.
Most of the components also have external dependencies. For example, the Rails
application depends on a number of [Ruby gems](https://gitlab.com/gitlab-org/gitlab-foss/blob/master/Gemfile.lock). Some of these dependencies also
have their own external dependencies which need to be present on the Operating
System in order for them to function correctly.
Furthermore, GitLab has a monthly release cycle requiring frequent maintenance
to stay up to date.
All the things listed previously present a challenge for the user maintaining the GitLab
installation.
## External Software Dependencies
For applications such as GitLab, external dependencies usually bring the following
challenges:
- Keeping versions in sync between direct and indirect dependencies
- Availability of a version on a specific Operating System
- Version changes can introduce or remove previously used configuration
- Security implications when library is marked as vulnerable but does not have
a new version released yet
Keep in mind that if a dependency exists on your Operating System, it does not
necessarily exist on other supported OSs.
## Benefits
A few benefits of a package with bundled dependencies:
1. Minimal effort required to install GitLab.
1. Minimum configuration required to get GitLab up and running.
1. Minimum effort required to upgrade between GitLab versions.
1. Multiple platforms supported.
1. Maintenance on older platforms is greatly simplified.
1. Less effort to support potential issues.
## Drawbacks
Some drawbacks of a package with bundled dependencies:
1. Duplication with possibly existing software.
1. Less flexibility in configuration.
## Why would you install a package from the Linux package when you can use a system package?
The answer can be simplified to: less maintenance required. Instead of handling
multiple packages that can break existing functionality if the versions are
not compatible, only handle one.
Multiple packages require correct configuration in multiple locations.
Keeping configuration in sync can be error prone.
If you have the skill set to maintain all current dependencies and enough time
to handle any future dependencies that might get introduced, the previous
reasons might not be good enough for you to not use a package from the Linux package.
There are two things to keep in mind before going down this route:
1. Getting support for any problems
you encounter might be more difficult due to the number of possibilities that exist
when using a library version that is not tested by majority of users.
1. Packages from the Linux package also allow shutting off of any services that you do not need,
if you need to run a component independently. For example, you can use a
[non-bundled PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#using-a-non-packaged-postgresql-database-management-server)
with a Linux package installation.
Keep in mind that a non-standard solution like the Linux package
might be a better fit when the application has a number of moving parts.
## Docker image with multiple services
[GitLab Docker image](../../install/docker/_index.md) is based on the Linux package.
Considering that container spawned from this image contains multiple processes,
these types of containers are also referred to as 'fat containers'.
There are reasons for and against an image like this, but they are similar to
what was noted previously:
1. Very simple to get started.
1. Upgrading to the latest version is extremely simple.
1. Running separate services in multiple containers and keeping them running
can be more complex and might not be required for a given install.
This method is useful for organizations just getting started with containers and schedulers, and may not be ready for a more complex installation. This method is a great introduction, and works well for smaller organizations.
|
https://docs.gitlab.com/administration/defaults
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/defaults.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
defaults.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Package defaults
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Unless configuration is specified in the `/etc/gitlab/gitlab.rb` file,
the package assumes the defaults as noted below.
## Ports
See the table below for the list of ports that the Linux package assigns by default:
| Component | On by default | Communicates via | Alternative | Connection port |
|:--------------------:|:-------------:|:----------------:|:-----------:|:------------------------------------------:|
| GitLab Rails | Yes | Port | X | 80 or 443 |
| GitLab Shell | Yes | Port | X | 22 |
| PostgreSQL | Yes | Socket | Port (5432) | X |
| Redis | Yes | Socket | Port (6379) | X |
| Puma | Yes | Socket | Port (8080) | X |
| GitLab Workhorse | Yes | Socket | Port (8181) | X |
| NGINX status | Yes | Port | X | 8060 |
| Prometheus | Yes | Port | X | 9090 |
| Node exporter | Yes | Port | X | 9100 |
| Redis exporter | Yes | Port | X | 9121 |
| PostgreSQL exporter | Yes | Port | X | 9187 |
| PgBouncer exporter | No | Port | X | 9188 |
| GitLab Exporter | Yes | Port | X | 9168 |
| Sidekiq exporter | Yes | Port | X | 8082 |
| Sidekiq health check | Yes | Port | X | 8092[^Sidekiq-health] |
| Web exporter | No | Port | X | 8083 |
| Geo PostgreSQL | No | Socket | Port (5431) | X |
| Redis Sentinel | No | Port | X | 26379 |
| Incoming email | No | Port | X | 143 |
| Elastic search | No | Port | X | 9200 |
| GitLab Pages | No | Port | X | 80 or 443 |
| GitLab Registry | No* | Port | X | 80, 443 or 5050 |
| GitLab Registry | No | Port | X | 5000 |
| LDAP | No | Port | X | Depends on the component configuration |
| Kerberos | No | Port | X | 8443 or 8088 |
| OmniAuth | Yes | Port | X | Depends on the component configuration |
| SMTP | No | Port | X | 465 |
| Remote syslog | No | Port | X | 514 |
| Mattermost | No | Port | X | 8065 |
| Mattermost | No | Port | X | 80 or 443 |
| PgBouncer | No | Port | X | 6432 |
| Consul | No | Port | X | 8300, 8301(TCP and UDP), 8500, 8600[^Consul-notes] |
| Patroni | No | Port | X | 8008 |
| GitLab KAS | Yes | Port | X | 8150 |
| Gitaly | Yes | Socket | Port (8075) | 8075 or 9999 (TLS) |
| Gitaly exporter | Yes | Port | X | 9236 |
| Praefect | No | Port | X | 2305 or 3305 (TLS) |
| GitLab Workhorse exporter | Yes | Port | X | 9229 |
| Registry exporter | No | Port | X | 5001 |
Legend:
- `Component` - Name of the component.
- `On by default` - Is the component running by default.
- `Communicates via` - How the component talks with the other components.
- `Alternative` - If it is possible to configure the component to use different type of communication. The type is listed with default port used in that case.
- `Connection port` - Port on which the component communicates.
GitLab also expects a file system to be ready for the storage of Git repositories
and various other files.
If you are using NFS (Network File System), files are carried
over a network which requires, based on implementation, ports `111` and
`2049` to be open.
{{< alert type="note" >}}
In some cases, the GitLab Registry is automatically enabled by default. See [our documentation](../packages/container_registry.md) for more details.
{{< /alert >}}
[^Consul-notes]: If using additional Consul functionality, more ports may need to be opened. See the [official documentation](https://developer.hashicorp.com/consul/docs/install/ports#ports-table) for the list.
[^Sidekiq-health]: If Sidekiq health check settings are not set, they default to the Sidekiq metrics exporter settings. This default is deprecated and is set to be removed in [GitLab 15.0](https://gitlab.com/gitlab-org/gitlab/-/issues/347509).
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Package defaults
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Unless configuration is specified in the `/etc/gitlab/gitlab.rb` file,
the package assumes the defaults as noted below.
## Ports
See the table below for the list of ports that the Linux package assigns by default:
| Component | On by default | Communicates via | Alternative | Connection port |
|:--------------------:|:-------------:|:----------------:|:-----------:|:------------------------------------------:|
| GitLab Rails | Yes | Port | X | 80 or 443 |
| GitLab Shell | Yes | Port | X | 22 |
| PostgreSQL | Yes | Socket | Port (5432) | X |
| Redis | Yes | Socket | Port (6379) | X |
| Puma | Yes | Socket | Port (8080) | X |
| GitLab Workhorse | Yes | Socket | Port (8181) | X |
| NGINX status | Yes | Port | X | 8060 |
| Prometheus | Yes | Port | X | 9090 |
| Node exporter | Yes | Port | X | 9100 |
| Redis exporter | Yes | Port | X | 9121 |
| PostgreSQL exporter | Yes | Port | X | 9187 |
| PgBouncer exporter | No | Port | X | 9188 |
| GitLab Exporter | Yes | Port | X | 9168 |
| Sidekiq exporter | Yes | Port | X | 8082 |
| Sidekiq health check | Yes | Port | X | 8092[^Sidekiq-health] |
| Web exporter | No | Port | X | 8083 |
| Geo PostgreSQL | No | Socket | Port (5431) | X |
| Redis Sentinel | No | Port | X | 26379 |
| Incoming email | No | Port | X | 143 |
| Elastic search | No | Port | X | 9200 |
| GitLab Pages | No | Port | X | 80 or 443 |
| GitLab Registry | No* | Port | X | 80, 443 or 5050 |
| GitLab Registry | No | Port | X | 5000 |
| LDAP | No | Port | X | Depends on the component configuration |
| Kerberos | No | Port | X | 8443 or 8088 |
| OmniAuth | Yes | Port | X | Depends on the component configuration |
| SMTP | No | Port | X | 465 |
| Remote syslog | No | Port | X | 514 |
| Mattermost | No | Port | X | 8065 |
| Mattermost | No | Port | X | 80 or 443 |
| PgBouncer | No | Port | X | 6432 |
| Consul | No | Port | X | 8300, 8301(TCP and UDP), 8500, 8600[^Consul-notes] |
| Patroni | No | Port | X | 8008 |
| GitLab KAS | Yes | Port | X | 8150 |
| Gitaly | Yes | Socket | Port (8075) | 8075 or 9999 (TLS) |
| Gitaly exporter | Yes | Port | X | 9236 |
| Praefect | No | Port | X | 2305 or 3305 (TLS) |
| GitLab Workhorse exporter | Yes | Port | X | 9229 |
| Registry exporter | No | Port | X | 5001 |
Legend:
- `Component` - Name of the component.
- `On by default` - Is the component running by default.
- `Communicates via` - How the component talks with the other components.
- `Alternative` - If it is possible to configure the component to use different type of communication. The type is listed with default port used in that case.
- `Connection port` - Port on which the component communicates.
GitLab also expects a file system to be ready for the storage of Git repositories
and various other files.
If you are using NFS (Network File System), files are carried
over a network which requires, based on implementation, ports `111` and
`2049` to be open.
{{< alert type="note" >}}
In some cases, the GitLab Registry is automatically enabled by default. See [our documentation](../packages/container_registry.md) for more details.
{{< /alert >}}
[^Consul-notes]: If using additional Consul functionality, more ports may need to be opened. See the [official documentation](https://developer.hashicorp.com/consul/docs/install/ports#ports-table) for the list.
[^Sidekiq-health]: If Sidekiq health check settings are not set, they default to the Sidekiq metrics exporter settings. This default is deprecated and is set to be removed in [GitLab 15.0](https://gitlab.com/gitlab-org/gitlab/-/issues/347509).
|
https://docs.gitlab.com/administration/postgresql_versions
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/postgresql_versions.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
postgresql_versions.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
PostgreSQL versions shipped with the Linux package
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
This table lists only GitLab versions where a significant change happened in the
package regarding PostgreSQL versions, not all.
{{< /alert >}}
Usually, PostgreSQL versions change with major or minor GitLab releases. However, patch versions
of the Linux package sometimes update the patch level of PostgreSQL. We've established a
yearly cadence for PostgreSQL upgrades
and trigger automatic database upgrades in the release before the new version is required.
For example:
- Linux package 12.7.6 shipped with PostgreSQL 9.6.14 and 10.9.
- Linux package 12.7.7 shipped with PostgreSQL 9.6.17 and 10.12.
Find out [which versions of PostgreSQL (and other components) ship](https://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html)
with each Linux package release.
The lowest supported PostgreSQL versions are listed in the
[installation requirements](../../install/requirements.md#postgresql).
Read more about update policies and warnings in the PostgreSQL
[upgrade docs](https://docs.gitlab.com/omnibus/settings/database.html#upgrade-packaged-postgresql-server).
| First GitLab version | PostgreSQL versions | Default version for fresh installs | Default version for upgrades | Notes |
| -------------- | ------------------- | ---------------------------------- | ---------------------------- | ----- |
| 18.0.0 | 16.8 | 16.8 | 16.8 | Package upgrades are aborted if PostgreSQL is not upgraded to 16 already. |
| 17.11.0 | 14.17, 16.8 | 16.8 | 16.8 | Package upgrades automatically perform an upgrade to PostgreSQL 16 for nodes that are not part of a Geo or HA cluster, unless [opted out](https://docs.gitlab.com/omnibus/settings/database/#opt-out-of-automatic-postgresql-upgrades). |
| 17.10.0 | 14.17, 16.8 | 16.8 | 16.8 | Fresh installs now default to PostgreSQL 16. |
| 17.9.2, 17.8.5, 17.7.7 | 14.17, 16.8 | 14.17 | 16.8 | |
| 17.8.0 | 14.15, 16.6 | 14.15 | 16.6 | |
| 17.5.0 | 14.11, 16.4 | 14.11 | 16.4 | Single node upgrades from PostgreSQL 14 to PostgreSQL 16 are now supported. Starting with GitLab 17.5.0, PostgreSQL 16 is fully supported for both new installations and upgrades in Geo deployments (the restriction from 17.4.0 no longer applies). |
| 17.4.0 | 14.11, 16.4 | 14.11 | 14.11 | PostgreSQL 16 is available for new installations if not using [Geo](../geo/_index.md#requirements-for-running-geo) or [Patroni](../postgresql/_index.md#postgresql-replication-and-failover-for-linux-package-installations). |
| 17.0.0 | 14.11 | 14.11 | 14.11 | Package upgrades are aborted if PostgreSQL is not upgraded to 14 already. |
| 16.10.1, 16.9.3, 16.8.5 | 13.14, 14.11 | 14.11 | 14.11 | |
| 16.6.7, 16.7.5, 16.8.2 | 13.13, 14.10 | 14.10 | 14.10 | |
| 16.7.0 | 13.12, 14.9 | 14.9 | 14.9 | |
| 16.4.3, 16.5.3, 16.6.1 | 13.12, 14.9 | 13.12 | 13.12 | For upgrades, you can manually upgrade to 14.9 following the [upgrade documentation](../../update/versions/gitlab_16_changes.md#linux-package-installations-2). |
| 16.2.0 | 13.11, 14.8 | 13.11 | 13.11 | For upgrades, you can manually upgrade to 14.8 following the [upgrade documentation](../../update/versions/gitlab_16_changes.md#linux-package-installations-2). |
| 16.0.2 | 13.11 | 13.11 | 13.11 | |
| 16.0.0 | 13.8 | 13.8 | 13.8 | |
| 15.11.7 | 13.11 | 13.11 | 12.12 | |
| 15.10.8 | 13.11 | 13.11 | 12.12 | |
| 15.6 | 12.12, 13.8 | 13.8 | 12.12 | For upgrades, you can manually upgrade to 13.8 following the [upgrade documentation](../../update/versions/gitlab_15_changes.md#linux-package-installations-2). |
| 15.0 | 12.10, 13.6 | 13.6 | 12.10 | For upgrades, you can manually upgrade to 13.6 following the [upgrade documentation](../../update/versions/gitlab_15_changes.md#linux-package-installations-2). |
| 14.1 | 12.7, 13.3 | 12.7 | 12.7 | PostgreSQL 13 available for fresh installations if not using [Geo](../geo/_index.md#requirements-for-running-geo) or [Patroni](../postgresql/_index.md#postgresql-replication-and-failover-for-linux-package-installations). |
| 14.0 | 12.7 | 12.7 | 12.7 | HA installations with repmgr are no longer supported and are prevented from upgrading to Linux package 14.0 |
| 13.8 | 11.9, 12.4 | 12.4 | 12.4 | Package upgrades automatically performed PostgreSQL upgrade for nodes that are not part of a Geo or HA cluster. |
| 13.7 | 11.9, 12.4 | 12.4 | 11.9 | For upgrades users can manually upgrade to 12.4 following the [upgrade documentation](https://docs.gitlab.com/omnibus/settings/database.html#upgrade-packaged-postgresql-server). |
| 13.4 | 11.9, 12.4 | 11.9 | 11.9 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 13.3 | 11.7, 12.3 | 11.7 | 11.7 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 13.0 | 11.7 | 11.7 | 11.7 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 12.10 | 9.6.17, 10.12, and 11.7 | 11.7 | 11.7 | Package upgrades automatically performed PostgreSQL upgrade for nodes that are not part of a Geo or repmgr cluster. |
| 12.8 | 9.6.17, 10.12, and 11.7 | 10.12 | 10.12 | Users can manually upgrade to 11.7 following the upgrade documentation. |
| 12.0 | 9.6.11 and 10.7 | 10.7 | 10.7 | Package upgrades automatically performed PostgreSQL upgrade. |
| 11.11 | 9.6.11 and 10.7 | 9.6.11 | 9.6.11 | Users can manually upgrade to 10.7 following the upgrade documentation. |
| 10.0 | 9.6.3 | 9.6.3 | 9.6.3 | Package upgrades aborted if users still on 9.2. |
| 9.0 | 9.2.18 and 9.6.1 | 9.6.1 | 9.6.1 | Package upgrades automatically performed PostgreSQL upgrade. |
| 8.14 | 9.2.18 and 9.6.1 | 9.2.18 | 9.2.18 | Users can manually upgrade to 9.6 following the upgrade documentation. |
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: PostgreSQL versions shipped with the Linux package
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
This table lists only GitLab versions where a significant change happened in the
package regarding PostgreSQL versions, not all.
{{< /alert >}}
Usually, PostgreSQL versions change with major or minor GitLab releases. However, patch versions
of the Linux package sometimes update the patch level of PostgreSQL. We've established a
yearly cadence for PostgreSQL upgrades
and trigger automatic database upgrades in the release before the new version is required.
For example:
- Linux package 12.7.6 shipped with PostgreSQL 9.6.14 and 10.9.
- Linux package 12.7.7 shipped with PostgreSQL 9.6.17 and 10.12.
Find out [which versions of PostgreSQL (and other components) ship](https://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html)
with each Linux package release.
The lowest supported PostgreSQL versions are listed in the
[installation requirements](../../install/requirements.md#postgresql).
Read more about update policies and warnings in the PostgreSQL
[upgrade docs](https://docs.gitlab.com/omnibus/settings/database.html#upgrade-packaged-postgresql-server).
| First GitLab version | PostgreSQL versions | Default version for fresh installs | Default version for upgrades | Notes |
| -------------- | ------------------- | ---------------------------------- | ---------------------------- | ----- |
| 18.0.0 | 16.8 | 16.8 | 16.8 | Package upgrades are aborted if PostgreSQL is not upgraded to 16 already. |
| 17.11.0 | 14.17, 16.8 | 16.8 | 16.8 | Package upgrades automatically perform an upgrade to PostgreSQL 16 for nodes that are not part of a Geo or HA cluster, unless [opted out](https://docs.gitlab.com/omnibus/settings/database/#opt-out-of-automatic-postgresql-upgrades). |
| 17.10.0 | 14.17, 16.8 | 16.8 | 16.8 | Fresh installs now default to PostgreSQL 16. |
| 17.9.2, 17.8.5, 17.7.7 | 14.17, 16.8 | 14.17 | 16.8 | |
| 17.8.0 | 14.15, 16.6 | 14.15 | 16.6 | |
| 17.5.0 | 14.11, 16.4 | 14.11 | 16.4 | Single node upgrades from PostgreSQL 14 to PostgreSQL 16 are now supported. Starting with GitLab 17.5.0, PostgreSQL 16 is fully supported for both new installations and upgrades in Geo deployments (the restriction from 17.4.0 no longer applies). |
| 17.4.0 | 14.11, 16.4 | 14.11 | 14.11 | PostgreSQL 16 is available for new installations if not using [Geo](../geo/_index.md#requirements-for-running-geo) or [Patroni](../postgresql/_index.md#postgresql-replication-and-failover-for-linux-package-installations). |
| 17.0.0 | 14.11 | 14.11 | 14.11 | Package upgrades are aborted if PostgreSQL is not upgraded to 14 already. |
| 16.10.1, 16.9.3, 16.8.5 | 13.14, 14.11 | 14.11 | 14.11 | |
| 16.6.7, 16.7.5, 16.8.2 | 13.13, 14.10 | 14.10 | 14.10 | |
| 16.7.0 | 13.12, 14.9 | 14.9 | 14.9 | |
| 16.4.3, 16.5.3, 16.6.1 | 13.12, 14.9 | 13.12 | 13.12 | For upgrades, you can manually upgrade to 14.9 following the [upgrade documentation](../../update/versions/gitlab_16_changes.md#linux-package-installations-2). |
| 16.2.0 | 13.11, 14.8 | 13.11 | 13.11 | For upgrades, you can manually upgrade to 14.8 following the [upgrade documentation](../../update/versions/gitlab_16_changes.md#linux-package-installations-2). |
| 16.0.2 | 13.11 | 13.11 | 13.11 | |
| 16.0.0 | 13.8 | 13.8 | 13.8 | |
| 15.11.7 | 13.11 | 13.11 | 12.12 | |
| 15.10.8 | 13.11 | 13.11 | 12.12 | |
| 15.6 | 12.12, 13.8 | 13.8 | 12.12 | For upgrades, you can manually upgrade to 13.8 following the [upgrade documentation](../../update/versions/gitlab_15_changes.md#linux-package-installations-2). |
| 15.0 | 12.10, 13.6 | 13.6 | 12.10 | For upgrades, you can manually upgrade to 13.6 following the [upgrade documentation](../../update/versions/gitlab_15_changes.md#linux-package-installations-2). |
| 14.1 | 12.7, 13.3 | 12.7 | 12.7 | PostgreSQL 13 available for fresh installations if not using [Geo](../geo/_index.md#requirements-for-running-geo) or [Patroni](../postgresql/_index.md#postgresql-replication-and-failover-for-linux-package-installations). |
| 14.0 | 12.7 | 12.7 | 12.7 | HA installations with repmgr are no longer supported and are prevented from upgrading to Linux package 14.0 |
| 13.8 | 11.9, 12.4 | 12.4 | 12.4 | Package upgrades automatically performed PostgreSQL upgrade for nodes that are not part of a Geo or HA cluster. |
| 13.7 | 11.9, 12.4 | 12.4 | 11.9 | For upgrades users can manually upgrade to 12.4 following the [upgrade documentation](https://docs.gitlab.com/omnibus/settings/database.html#upgrade-packaged-postgresql-server). |
| 13.4 | 11.9, 12.4 | 11.9 | 11.9 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 13.3 | 11.7, 12.3 | 11.7 | 11.7 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 13.0 | 11.7 | 11.7 | 11.7 | Package upgrades aborted if users not running PostgreSQL 11 already |
| 12.10 | 9.6.17, 10.12, and 11.7 | 11.7 | 11.7 | Package upgrades automatically performed PostgreSQL upgrade for nodes that are not part of a Geo or repmgr cluster. |
| 12.8 | 9.6.17, 10.12, and 11.7 | 10.12 | 10.12 | Users can manually upgrade to 11.7 following the upgrade documentation. |
| 12.0 | 9.6.11 and 10.7 | 10.7 | 10.7 | Package upgrades automatically performed PostgreSQL upgrade. |
| 11.11 | 9.6.11 and 10.7 | 9.6.11 | 9.6.11 | Users can manually upgrade to 10.7 following the upgrade documentation. |
| 10.0 | 9.6.3 | 9.6.3 | 9.6.3 | Package upgrades aborted if users still on 9.2. |
| 9.0 | 9.2.18 and 9.6.1 | 9.6.1 | 9.6.1 | Package upgrades automatically performed PostgreSQL upgrade. |
| 8.14 | 9.2.18 and 9.6.1 | 9.2.18 | 9.2.18 | Users can manually upgrade to 9.6 following the upgrade documentation. |
|
https://docs.gitlab.com/administration/supported_os
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/supported_os.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
supported_os.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
This document was moved to [another location](../../install/package/_index.md).
<!-- This redirect file can be deleted after <2025-09-02>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
---
redirect_to: ../../install/package/_index.md
remove_date: '2025-09-02'
breadcrumbs:
- doc
- administration
- package_information
---
<!-- markdownlint-disable -->
This document was moved to [another location](../../install/package/_index.md).
<!-- This redirect file can be deleted after <2025-09-02>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
https://docs.gitlab.com/administration/signed_packages
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/signed_packages.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
signed_packages.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Package Signatures
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
<!-- vale gitlab_base.SubstitutionWarning = NO -->
Linux packages produced by GitLab are created using [Omnibus](https://github.com/chef/omnibus), for which GitLab
has added DEB signing using `debsigs` in [our own fork](https://gitlab.com/gitlab-org/omnibus).
<!-- vale gitlab_base.SubstitutionWarning = YES -->
Combined with the existing functionality of RPM signing, this addition allows GitLab to provide signed packages for all
supported distributions using DEB or RPM.
These packages are produced by the GitLab CI process, as found in the
[`omnibus-gitlab` project](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/.gitlab-ci.yml),
prior to their delivery to <https://packages.gitlab.com> to provide assurance that the packages are not altered prior
to delivery to our community.
## GnuPG Public Keys
All packages are signed with [GnuPG](https://www.gnupg.org/), in a method appropriate for their format. The key used to
sign these packages can be found on [MIT PGP Public Key Server](https://pgp.mit.edu) at
[`0x3cfcf9baf27eab47`](https://pgp.mit.edu/pks/lookup?op=vindex&search=0x3CFCF9BAF27EAB47).
## Verifying Signatures
Information on how to verify GitLab package signatures can be found in [Package Signatures](https://docs.gitlab.com/omnibus/update/package_signatures.html).
## GPG Signature Management
Information on how GitLab manages GPG keys for package signing can be found in [the runbooks](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/packaging/manage-package-signing-keys.md).
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Package Signatures
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
<!-- vale gitlab_base.SubstitutionWarning = NO -->
Linux packages produced by GitLab are created using [Omnibus](https://github.com/chef/omnibus), for which GitLab
has added DEB signing using `debsigs` in [our own fork](https://gitlab.com/gitlab-org/omnibus).
<!-- vale gitlab_base.SubstitutionWarning = YES -->
Combined with the existing functionality of RPM signing, this addition allows GitLab to provide signed packages for all
supported distributions using DEB or RPM.
These packages are produced by the GitLab CI process, as found in the
[`omnibus-gitlab` project](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/.gitlab-ci.yml),
prior to their delivery to <https://packages.gitlab.com> to provide assurance that the packages are not altered prior
to delivery to our community.
## GnuPG Public Keys
All packages are signed with [GnuPG](https://www.gnupg.org/), in a method appropriate for their format. The key used to
sign these packages can be found on [MIT PGP Public Key Server](https://pgp.mit.edu) at
[`0x3cfcf9baf27eab47`](https://pgp.mit.edu/pks/lookup?op=vindex&search=0x3CFCF9BAF27EAB47).
## Verifying Signatures
Information on how to verify GitLab package signatures can be found in [Package Signatures](https://docs.gitlab.com/omnibus/update/package_signatures.html).
## GPG Signature Management
Information on how GitLab manages GPG keys for package signing can be found in [the runbooks](https://gitlab.com/gitlab-com/runbooks/-/blob/master/docs/packaging/manage-package-signing-keys.md).
|
https://docs.gitlab.com/administration/package_information
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Package information
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux package is bundled with all dependencies required for GitLab
to function correctly. More details can be found
at [bundling dependencies document](omnibus_packages.md).
## Package Version
The released package versions are in the format `MAJOR.MINOR.PATCH-EDITION.OMNIBUS_RELEASE`
| Component | Meaning | Example |
|:--------------------|:------------------------------------------------------------------------------------------------------------------------------------------|:---------|
| `MAJOR.MINOR.PATCH` | The GitLab version this corresponds to. | `13.3.0` |
| `EDITION` | The edition of GitLab this corresponds to. | `ee` |
| `OMNIBUS_RELEASE` | The Linux package release. Usually, this is `0`. We increment this if we need to build a new package without changing the GitLab version. | `0` |
## Licenses
See [licensing](licensing.md)
## Defaults
The Linux package requires various configuration to get the components
in working order. If the configuration is not provided, the package uses
the default values assumed in the package.
These defaults are noted in the package [defaults document](defaults.md).
## Checking the versions of bundled software
After the Linux package is installed, you can find the version of
GitLab and all bundled libraries in `/opt/gitlab/version-manifest.txt`.
If you don't have the package installed, you can always check the Linux package
[source repository](https://gitlab.com/gitlab-org/omnibus-gitlab/tree/master), specifically the
[configuration directory](https://gitlab.com/gitlab-org/omnibus-gitlab/tree/master/config).
For example, if you examine the `8-6-stable` branch, you can conclude that
8.6 packages were running [Ruby 2.1.8](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/8-6-stable/config/projects/gitlab.rb#L48).
Or, that 8.5 packages were bundled with [NGINX 1.9.0](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/8-5-stable/config/software/nginx.rb#L20).
## Signatures of GitLab, Inc. provided packages
Documentation on package signatures can be found at [Signed Packages](signed_packages.md)
## Checking for newer configuration options on upgrade
The `/etc/gitlab/gitlab.rb` configuration file is created when the Linux package is initially installed.
To avoid accidental overwrites of user configuration, the `/etc/gitlab/gitlab.rb` configuration file is not updated
with new configuration when the Linux package installation is upgraded.
New configuration options are noted in the
[`gitlab.rb.template` file](https://gitlab.com/gitlab-org/omnibus-gitlab/raw/master/files/gitlab-config-template/gitlab.rb.template).
The Linux package also provides a convenience command which
compares the existing user configuration with the latest version of the
template contained in the package.
To view a diff between your configuration file and the latest version, run:
```shell
sudo gitlab-ctl diff-config
```
{{< alert type="warning" >}}
If you are pasting the output of this command into your
`/etc/gitlab/gitlab.rb` configuration file, omit any leading `+` and `-`
characters on each line.
{{< /alert >}}
## Init system detection
The Linux package attempts to query the underlying system to
check which init system it uses.
This manifests itself as a `WARNING` during the `sudo gitlab-ctl reconfigure`
run.
Depending on the init system, this `WARNING` can be one of:
```plaintext
/sbin/init: unrecognized option '--version'
```
when the underlying init system is not upstart.
```plaintext
-.mount loaded active mounted /
```
when the underlying init system is systemd.
These warnings can be safely ignored. They are not suppressed because this
allows everyone to debug possible detection issues faster.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Package information
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux package is bundled with all dependencies required for GitLab
to function correctly. More details can be found
at [bundling dependencies document](omnibus_packages.md).
## Package Version
The released package versions are in the format `MAJOR.MINOR.PATCH-EDITION.OMNIBUS_RELEASE`
| Component | Meaning | Example |
|:--------------------|:------------------------------------------------------------------------------------------------------------------------------------------|:---------|
| `MAJOR.MINOR.PATCH` | The GitLab version this corresponds to. | `13.3.0` |
| `EDITION` | The edition of GitLab this corresponds to. | `ee` |
| `OMNIBUS_RELEASE` | The Linux package release. Usually, this is `0`. We increment this if we need to build a new package without changing the GitLab version. | `0` |
## Licenses
See [licensing](licensing.md)
## Defaults
The Linux package requires various configuration to get the components
in working order. If the configuration is not provided, the package uses
the default values assumed in the package.
These defaults are noted in the package [defaults document](defaults.md).
## Checking the versions of bundled software
After the Linux package is installed, you can find the version of
GitLab and all bundled libraries in `/opt/gitlab/version-manifest.txt`.
If you don't have the package installed, you can always check the Linux package
[source repository](https://gitlab.com/gitlab-org/omnibus-gitlab/tree/master), specifically the
[configuration directory](https://gitlab.com/gitlab-org/omnibus-gitlab/tree/master/config).
For example, if you examine the `8-6-stable` branch, you can conclude that
8.6 packages were running [Ruby 2.1.8](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/8-6-stable/config/projects/gitlab.rb#L48).
Or, that 8.5 packages were bundled with [NGINX 1.9.0](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/8-5-stable/config/software/nginx.rb#L20).
## Signatures of GitLab, Inc. provided packages
Documentation on package signatures can be found at [Signed Packages](signed_packages.md)
## Checking for newer configuration options on upgrade
The `/etc/gitlab/gitlab.rb` configuration file is created when the Linux package is initially installed.
To avoid accidental overwrites of user configuration, the `/etc/gitlab/gitlab.rb` configuration file is not updated
with new configuration when the Linux package installation is upgraded.
New configuration options are noted in the
[`gitlab.rb.template` file](https://gitlab.com/gitlab-org/omnibus-gitlab/raw/master/files/gitlab-config-template/gitlab.rb.template).
The Linux package also provides a convenience command which
compares the existing user configuration with the latest version of the
template contained in the package.
To view a diff between your configuration file and the latest version, run:
```shell
sudo gitlab-ctl diff-config
```
{{< alert type="warning" >}}
If you are pasting the output of this command into your
`/etc/gitlab/gitlab.rb` configuration file, omit any leading `+` and `-`
characters on each line.
{{< /alert >}}
## Init system detection
The Linux package attempts to query the underlying system to
check which init system it uses.
This manifests itself as a `WARNING` during the `sudo gitlab-ctl reconfigure`
run.
Depending on the init system, this `WARNING` can be one of:
```plaintext
/sbin/init: unrecognized option '--version'
```
when the underlying init system is not upstart.
```plaintext
-.mount loaded active mounted /
```
when the underlying init system is systemd.
These warnings can be safely ignored. They are not suppressed because this
allows everyone to debug possible detection issues faster.
|
https://docs.gitlab.com/administration/deprecation_policy
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/deprecation_policy.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
deprecation_policy.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Linux package deprecation policy
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux packages come with number of different libraries and services which offers users plethora of configuration options.
As libraries and services get updated, their configuration options change
and become obsolete. To increase maintainability and preserve a working
setup, various configuration requires removal.
## Configuration deprecation
### Policy
The Linux package retains configuration for at least **one major**
version. We can't guarantee that deprecated configuration
is available in the next major release. See [example](#example) for more details.
### Notice
If the configuration becomes obsolete, we announce the deprecation:
- via release blog post on `https://about.gitlab.com/blog/`. The blog post item
contains the deprecation notice together with the target removal date.
- via installation/reconfigure output (if applicable).
- via official documentation on `https://docs.gitlab.com/`. The documentation update contains the corrected syntax (if applicable) or a date of configuration removal.
### Procedure
This section lists steps necessary for deprecating and removing configuration.
We can differentiate two different types of configuration:
- Sensitive: Configuration that can cause major service outage (like data integrity,
installation integrity, or preventing users from reaching the installation)
- Regular: Configuration that can make a feature unavailable but still makes the
installation usable (like a change in default project/group settings, or
miscommunication with other components)
We must also differentiate deprecation and removal procedure.
#### Deprecating configuration
Deprecation procedure is similar for both `sensitive` and `regular` configuration. The only difference is in the removal target date.
Common steps:
1. Create an issue at the [`omnibus-gitlab` issue tracker](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues) with
details on deprecation type and other necessary information. Apply the label `deprecation`.
1. Decide on the removal target for the deprecated configuration
1. Formulate deprecation notice for each item as noted in [Notice section](#notice)
Removal target:
For regular configuration, removal target should always be the date of the **next major** release. If the date is not known, you can reference the next major version.
For sensitive configuration things are a bit more complicated.
We should aim to not remove sensitive configuration in the next major release if the next major release is 2 minor releases away (This number is chosen to match our security backport release policy).
See the table below for some examples:
| Configuration type | Deprecation announced | Final minor release | Remove |
| -------- | -------- | -------- | -------- |
| Sensitive | 10.1.0 | 10.9.0 | 11.0.0 |
| Sensitive | 10.7.0 | 10.9.0 | 12.0.0 |
| Regular | 10.1.0 | 10.9.0 | 11.0.0 |
| Regular | 10.8.0 | 10.9.0 | 11.0.0 |
#### Removing configuration
When deprecation is announced and removal target set, the milestone for the issue
should be changed to match the removal target version.
The final comment in the issue must have:
- A text snippet for the release blog post section.
- A link to a documentation merge request (or documentation snippet) that introduces the change.
- Either:
- A link to a draft merge request that removes the configuration.
- Details on what must be done.
## Example
User configuration available in `/etc/gitlab/gitlab.rb` was introduced in GitLab version 10.0, `gitlab_rails['configuration'] = true`. In GitLab version 10.4.0, a new change was introduced that requires rename of this configuration option. New configuration option is `gitlab_rails['better_configuration'] = true`. Development team translates the old configuration into a new one
and triggers a deprecation procedure.
This means that these two configuration
options are valid through GitLab version 10. In other words,
if you still have `gitlab_rails['configuration'] = true` set in GitLab 10.8.0
the feature continues working the same way as if you had `gitlab_rails['better_configuration'] = true` set.
However, setting the old version of the configuration prints out a deprecation
notice at the end of installation/upgrade/reconfigure run.
In GitLab 11, `gitlab_rails['configuration'] = true` no longer works and you must manually change the configuration in `/etc/gitlab/gitlab.rb` to the new valid configuration.
**Note** If this configuration option is sensitive and can put integrity of the installation or
data in danger,the installation or upgrade is aborted.
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Linux package deprecation policy
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux packages come with number of different libraries and services which offers users plethora of configuration options.
As libraries and services get updated, their configuration options change
and become obsolete. To increase maintainability and preserve a working
setup, various configuration requires removal.
## Configuration deprecation
### Policy
The Linux package retains configuration for at least **one major**
version. We can't guarantee that deprecated configuration
is available in the next major release. See [example](#example) for more details.
### Notice
If the configuration becomes obsolete, we announce the deprecation:
- via release blog post on `https://about.gitlab.com/blog/`. The blog post item
contains the deprecation notice together with the target removal date.
- via installation/reconfigure output (if applicable).
- via official documentation on `https://docs.gitlab.com/`. The documentation update contains the corrected syntax (if applicable) or a date of configuration removal.
### Procedure
This section lists steps necessary for deprecating and removing configuration.
We can differentiate two different types of configuration:
- Sensitive: Configuration that can cause major service outage (like data integrity,
installation integrity, or preventing users from reaching the installation)
- Regular: Configuration that can make a feature unavailable but still makes the
installation usable (like a change in default project/group settings, or
miscommunication with other components)
We must also differentiate deprecation and removal procedure.
#### Deprecating configuration
Deprecation procedure is similar for both `sensitive` and `regular` configuration. The only difference is in the removal target date.
Common steps:
1. Create an issue at the [`omnibus-gitlab` issue tracker](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues) with
details on deprecation type and other necessary information. Apply the label `deprecation`.
1. Decide on the removal target for the deprecated configuration
1. Formulate deprecation notice for each item as noted in [Notice section](#notice)
Removal target:
For regular configuration, removal target should always be the date of the **next major** release. If the date is not known, you can reference the next major version.
For sensitive configuration things are a bit more complicated.
We should aim to not remove sensitive configuration in the next major release if the next major release is 2 minor releases away (This number is chosen to match our security backport release policy).
See the table below for some examples:
| Configuration type | Deprecation announced | Final minor release | Remove |
| -------- | -------- | -------- | -------- |
| Sensitive | 10.1.0 | 10.9.0 | 11.0.0 |
| Sensitive | 10.7.0 | 10.9.0 | 12.0.0 |
| Regular | 10.1.0 | 10.9.0 | 11.0.0 |
| Regular | 10.8.0 | 10.9.0 | 11.0.0 |
#### Removing configuration
When deprecation is announced and removal target set, the milestone for the issue
should be changed to match the removal target version.
The final comment in the issue must have:
- A text snippet for the release blog post section.
- A link to a documentation merge request (or documentation snippet) that introduces the change.
- Either:
- A link to a draft merge request that removes the configuration.
- Details on what must be done.
## Example
User configuration available in `/etc/gitlab/gitlab.rb` was introduced in GitLab version 10.0, `gitlab_rails['configuration'] = true`. In GitLab version 10.4.0, a new change was introduced that requires rename of this configuration option. New configuration option is `gitlab_rails['better_configuration'] = true`. Development team translates the old configuration into a new one
and triggers a deprecation procedure.
This means that these two configuration
options are valid through GitLab version 10. In other words,
if you still have `gitlab_rails['configuration'] = true` set in GitLab 10.8.0
the feature continues working the same way as if you had `gitlab_rails['better_configuration'] = true` set.
However, setting the old version of the configuration prints out a deprecation
notice at the end of installation/upgrade/reconfigure run.
In GitLab 11, `gitlab_rails['configuration'] = true` no longer works and you must manually change the configuration in `/etc/gitlab/gitlab.rb` to the new valid configuration.
**Note** If this configuration option is sensitive and can put integrity of the installation or
data in danger,the installation or upgrade is aborted.
|
https://docs.gitlab.com/administration/licensing
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/licensing.md
|
2025-08-13
|
doc/administration/package_information
|
[
"doc",
"administration",
"package_information"
] |
licensing.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Package Licensing
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## License
While GitLab itself is MIT, the Linux package sources are licensed under the Apache-2.0.
## License file location
Starting with version 8.11, the Linux package contains license
information of all software that is bundled in the package.
After installing the package, licenses for each individual bundled library
can be found in `/opt/gitlab/LICENSES` directory.
There is also one `LICENSE` file which contains all licenses compiled together.
This compiled license can be found in `/opt/gitlab/LICENSE` file.
Starting with version 9.2, the Linux package ships with a
`dependency_licenses.json` file containing version and license information of
all bundled software, including software libraries, Ruby gems that the rails
application uses, and JavaScript libraries that is required for the frontend
components. Because it's in JSON format, GitLab can parse this file and use it for automated checks or validations. The file may be found at
`/opt/gitlab/dependency_licenses.json`.
Starting with version 11.3, we have also made the license information available
online, at: <https://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html>
## Checking licenses
The Linux package is made up of many pieces of software, comprising code
that is covered by many different licenses. Those licenses are provided and
compiled as stated previously.
Starting with version 8.13, GitLab has placed an additional step into
Linux package installation. The `license_check` step calls
`lib/gitlab/tasks/license_check.rake`, which checks the compiled `LICENSE` file
against the current list of approved and questionable licenses as denoted in the
arrays at the top of the script. This script outputs one of `Good`,
`Unknown` or `Check` for each piece of software that is a part of the
Linux package.
- `Good`: denotes a license that is approved for all usage types, in GitLab and
the Linux package.
- `Unknown`: denotes a license that is not recognized in the list of 'good' or 'bad',
which should be immediately reviewed for implications of use.
- `Check`: denotes a license that has the potential be incompatible with GitLab itself,
and thus should be checked for how it is used as a part of the Linux package
to ensure compliance.
This list is sourced from the GitLab development documentation on licensing.
However, due to the nature of the Linux package, the licenses may not apply
in the same way. Such as with `git` and `rsync`. See the [GNU License FAQ](https://www.gnu.org/licenses/gpl-faq.en.html#MereAggregation)
## License acknowledgments
### libjpeg-turbo - BSD 3-clause license
This software is based in part on the work of the Independent JPEG Group.
## Trademark Usage
Within the GitLab documentation, reference to third-party technologies and/or trademarks of third-party entities may be made. The inclusion of reference to third-party technology and/or entities is solely for the purposes of examples of how GitLab software may interact with, or be used in conjunction with, such third-party technology.
All trademarks, materials, documentation, and other intellectual property remain the property of any/all such third party.
### Trademark Requirements
Use of GitLab Trademarks must be in compliance with the standards set forth in our guidelines (as updated from time to time).
CHEF® and all Chef marks are owned by Progress Software Corporation and must be used in accordance with the [Progress Software Trademark Usage Policy](https://www.progress.com/legal/trademarks).
When using a GitLab or third-party trademark in documentation, include the (R) symbol in the first instance, for example, "Chef(R) is used for configuring…". You may omit the symbol in subsequent instances.
If a trademark owner requires a particular notice or trademark requirement, such notice or requirement should be stated above.
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Package Licensing
breadcrumbs:
- doc
- administration
- package_information
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
## License
While GitLab itself is MIT, the Linux package sources are licensed under the Apache-2.0.
## License file location
Starting with version 8.11, the Linux package contains license
information of all software that is bundled in the package.
After installing the package, licenses for each individual bundled library
can be found in `/opt/gitlab/LICENSES` directory.
There is also one `LICENSE` file which contains all licenses compiled together.
This compiled license can be found in `/opt/gitlab/LICENSE` file.
Starting with version 9.2, the Linux package ships with a
`dependency_licenses.json` file containing version and license information of
all bundled software, including software libraries, Ruby gems that the rails
application uses, and JavaScript libraries that is required for the frontend
components. Because it's in JSON format, GitLab can parse this file and use it for automated checks or validations. The file may be found at
`/opt/gitlab/dependency_licenses.json`.
Starting with version 11.3, we have also made the license information available
online, at: <https://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html>
## Checking licenses
The Linux package is made up of many pieces of software, comprising code
that is covered by many different licenses. Those licenses are provided and
compiled as stated previously.
Starting with version 8.13, GitLab has placed an additional step into
Linux package installation. The `license_check` step calls
`lib/gitlab/tasks/license_check.rake`, which checks the compiled `LICENSE` file
against the current list of approved and questionable licenses as denoted in the
arrays at the top of the script. This script outputs one of `Good`,
`Unknown` or `Check` for each piece of software that is a part of the
Linux package.
- `Good`: denotes a license that is approved for all usage types, in GitLab and
the Linux package.
- `Unknown`: denotes a license that is not recognized in the list of 'good' or 'bad',
which should be immediately reviewed for implications of use.
- `Check`: denotes a license that has the potential be incompatible with GitLab itself,
and thus should be checked for how it is used as a part of the Linux package
to ensure compliance.
This list is sourced from the GitLab development documentation on licensing.
However, due to the nature of the Linux package, the licenses may not apply
in the same way. Such as with `git` and `rsync`. See the [GNU License FAQ](https://www.gnu.org/licenses/gpl-faq.en.html#MereAggregation)
## License acknowledgments
### libjpeg-turbo - BSD 3-clause license
This software is based in part on the work of the Independent JPEG Group.
## Trademark Usage
Within the GitLab documentation, reference to third-party technologies and/or trademarks of third-party entities may be made. The inclusion of reference to third-party technology and/or entities is solely for the purposes of examples of how GitLab software may interact with, or be used in conjunction with, such third-party technology.
All trademarks, materials, documentation, and other intellectual property remain the property of any/all such third party.
### Trademark Requirements
Use of GitLab Trademarks must be in compliance with the standards set forth in our guidelines (as updated from time to time).
CHEF® and all Chef marks are owned by Progress Software Corporation and must be used in accordance with the [Progress Software Trademark Usage Policy](https://www.progress.com/legal/trademarks).
When using a GitLab or third-party trademark in documentation, include the (R) symbol in the first instance, for example, "Chef(R) is used for configuring…". You may omit the symbol in subsequent instances.
If a trademark owner requires a particular notice or trademark requirement, such notice or requirement should be stated above.
|
https://docs.gitlab.com/administration/pages
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/pages
|
[
"doc",
"administration",
"pages"
] |
_index.md
|
Plan
|
Knowledge
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Pages administration
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab Pages provides static site hosting for GitLab projects and groups.
Server administrators must configure Pages before users can access this feature.
With GitLab Pages, administrators:
- Host static websites securely with custom domains and SSL/TLS certificates.
- Enable authentication to control access to Pages sites through GitLab permissions.
- Scale deployments using object storage or network storage in multi-node environments.
- Monitor and manage traffic with rate limiting and custom headers.
- Support IPv4 and IPv6 addresses for all Pages sites.
The GitLab Pages daemon runs as a separate process and can be configured either on the same server
as GitLab or on its own dedicated infrastructure.
For user documentation, see [GitLab Pages](../../user/project/pages/_index.md).
{{< alert type="note" >}}
This guide is for Linux package installations. If you have a self-compiled GitLab installation, see
[GitLab Pages administration for self-compiled installations](source.md).
{{< /alert >}}
## The GitLab Pages daemon
GitLab Pages makes use of the [GitLab Pages daemon](https://gitlab.com/gitlab-org/gitlab-pages), a basic HTTP server
written in Go that can listen on an external IP address and provide support for
custom domains and custom certificates. It supports dynamic certificates through
Server Name Indication (SNI) and exposes pages using HTTP2 by default.
You are encouraged to read its [README](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/README.md) to fully understand how
it works.
In the case of [custom domains](#custom-domains) (but not
[wildcard domains](#wildcard-domains)), the Pages daemon needs to listen on
ports `80` and/or `443`. For that reason, there is some flexibility in the way
which you can set it up:
- Run the Pages daemon in the same server as GitLab, listening on a **secondary IP**.
- Run the Pages daemon in a [separate server](#running-gitlab-pages-on-a-separate-server). In that case, the
[Pages path](#change-storage-path) must also be present in the server that
the Pages daemon is installed, so you must share it through the network.
- Run the Pages daemon in the same server as GitLab, listening on the same IP
but on different ports. In that case, you must proxy the traffic with
a load balancer. If you choose that route, you should use TCP load
balancing for HTTPS. If you use TLS-termination (HTTPS-load balancing), the
pages can't be served with user-provided certificates. For
HTTP it's OK to use HTTP or TCP load balancing.
In this document, we proceed assuming the first option. If you are not
supporting custom domains a secondary IP is not needed.
## Prerequisites
This section describes the prerequisites for configuring GitLab Pages.
### Wildcard domains
Before configuring Pages for wildcard domains, you must:
1. Have a domain for Pages that is not a subdomain of your GitLab instance domain.
| GitLab domain | Pages domain | Does it work? |
| -------------------- | ------------------- | ------------- |
| `example.com` | `example.io` | {{< icon name="check-circle" >}} Yes |
| `example.com` | `pages.example.com` | {{< icon name="dotted-circle" >}} No |
| `gitlab.example.com` | `pages.example.com` | {{< icon name="check-circle" >}} Yes |
1. Configure a **wildcard DNS record**.
1. Optional. Have a **wildcard certificate** for that domain if you decide to
serve Pages under HTTPS.
1. Optional but recommended. Enable [instance runners](../../ci/runners/_index.md)
so that your users don't have to bring their own.
1. For custom domains, have a **secondary IP**.
### Single-domain sites
Before configuring Pages for single-domain sites, you must:
1. Have a domain for Pages that is not a subdomain of your GitLab instance domain.
| GitLab domain | Pages domain | Supported |
| -------------------- | ------------------- | ------------- |
| `example.com` | `example.io` | {{< icon name="check-circle" >}} Yes |
| `example.com` | `pages.example.com` | {{< icon name="dotted-circle" >}} No |
| `gitlab.example.com` | `pages.example.com` | {{< icon name="check-circle" >}} Yes |
1. Configure a **DNS record**.
1. Optional. If you decide to serve Pages under HTTPS, have a **TLS certificate** for that domain.
1. Optional but recommended. Enable [instance runners](../../ci/runners/_index.md)
so that your users don't have to bring their own.
1. For custom domains, have a **secondary IP**.
{{< alert type="note" >}}
If your GitLab instance and the Pages daemon are deployed in a private network or behind a firewall, your GitLab Pages websites are only accessible to devices/users that have access to the private network.
{{< /alert >}}
### Add the domain to the Public Suffix List
The [Public Suffix List](https://publicsuffix.org) is used by browsers to
decide how to treat subdomains. If your GitLab instance allows members of the
public to create GitLab Pages sites, it also allows those users to create
subdomains on the pages domain (`example.io`). Adding the domain to the Public
Suffix List prevents browsers from accepting
[supercookies](https://en.wikipedia.org/wiki/HTTP_cookie#Supercookie),
among other things.
To submit your GitLab Pages subdomain, follow [Submit amendments to the Public Suffix List](https://publicsuffix.org/submit/).
For example, if your domain is `example.io`, you should
request that `example.io` is added to the Public Suffix List. GitLab.com
added `gitlab.io` [in 2016](https://gitlab.com/gitlab-com/gl-infra/reliability/-/issues/230).
### DNS configuration
GitLab Pages expect to run on their own virtual host. In your DNS server/provider
add a [wildcard DNS `A` record](https://en.wikipedia.org/wiki/Wildcard_DNS_record) pointing to the
host that GitLab runs. For example, an entry would look like this:
```plaintext
*.example.io. 1800 IN A 192.0.2.1
*.example.io. 1800 IN AAAA 2001:db8::1
```
Where `example.io` is the domain GitLab Pages is served from,
`192.0.2.1` is the IPv4 address of your GitLab instance, and `2001:db8::1` is the
IPv6 address. If you don't have IPv6, you can omit the `AAAA` record.
#### DNS configuration for single-domain sites
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
To configure GitLab Pages DNS for single-domain sites without wildcard DNS:
1. Enable the GitLab Pages flag for this feature by adding
`gitlab_pages['namespace_in_path'] = true` to `/etc/gitlab/gitlab.rb`.
1. In your DNS provider, add entries for `example.io`.
Replace `example.io` with your domain name, and `192.0.0.0` with
the IPv4 version of your IP address. The entries look like this:
```plaintext
example.io 1800 IN A 192.0.0.0
```
1. Optional. If your GitLab instance has an IPv6 address, add entries for it.
Replace `example.io` with your domain name, and `2001:db8::1` with
the IPv6 version of your IP address. The entries look like this:
```plaintext
example.io 1800 IN AAAA 2001:db8::1
```
This example contains the following:
- `example.io`: The domain GitLab Pages is served from.
#### DNS configuration for custom domains
If support for custom domains is needed, all subdomains of the Pages root domain should point to the
secondary IP (which is dedicated for the Pages daemon). Without this configuration, users can't use
`CNAME` records to point their custom domains to their GitLab Pages.
For example, an entry could look like this:
```plaintext
example.com 1800 IN A 192.0.2.1
*.example.io. 1800 IN A 192.0.2.2
```
This example contains the following:
- `example.com`: The GitLab domain.
- `example.io`: The domain GitLab Pages is served from.
- `192.0.2.1`: The primary IP of your GitLab instance.
- `192.0.2.2`: The secondary IP, which is dedicated to GitLab Pages. It must be different than the primary IP.
{{< alert type="note" >}}
You should not use the GitLab domain to serve user pages. For more information see the [security section](#security).
{{< /alert >}}
## Configuration
Depending on your needs, you can set up GitLab Pages in 4 different ways.
The following examples are listed from the easiest setup to the most
advanced one.
### Wildcard domains
The following configuration is the minimum setup to use GitLab Pages.
It is the foundation for all other setups described here.
In this configuration:
- NGINX proxies all requests to the GitLab Pages daemon.
- The GitLab Pages daemon doesn't listen directly to the public internet.
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
To configure GitLab Pages to use wildcard domains:
1. Set the external URL for GitLab Pages in `/etc/gitlab/gitlab.rb`:
```ruby
external_url "http://example.com" # external_url here is only for reference
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `http://<namespace>.example.io/<project_slug>`.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [How to Enable GitLab Pages for GitLab CE and EE](https://youtu.be/dD8c7WNcc6s).
<!-- Video published on 2017-02-22 -->
### Single-domain sites
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
The following configuration is the minimum setup to use GitLab Pages.
It is the foundation for all other setups described here.
In this configuration:
- NGINX proxies all requests to the GitLab Pages daemon.
- The GitLab Pages daemon doesn't listen directly to the public internet.
Prerequisites:
- You have configured DNS for
[single-domain sites](#dns-configuration-for-single-domain-sites).
To configure GitLab Pages to use single-domain sites:
1. In `/etc/gitlab/gitlab.rb`, set the external URL for GitLab Pages, and enable the feature:
```ruby
external_url "http://example.com" # Swap out this URL for your own
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
# Set this flag to enable this feature
gitlab_pages['namespace_in_path'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `http://example.io/<namespace>/<project_slug>`.
{{< alert type="warning" >}}
GitLab Pages supports only one URL scheme at a time:
wildcard domains or single-domain sites.
If you enable `namespace_in_path`, existing GitLab Pages websites
are accessible only on single-domain.
{{< /alert >}}
### Wildcard domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- TLS certificate. Can be either Wildcard, or any other type meeting the [requirements](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#manual-addition-of-ssltls-certificates).
NGINX proxies all requests to the daemon. Pages daemon doesn't listen to the
public internet.
1. Place the wildcard TLS certificate for `*.example.io` and the key inside `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['redirect_http_to_https'] = true
```
1. If you haven't named your certificate and key `example.io.crt` and `example.io.key`,
you must also add the full paths as shown below:
```ruby
pages_nginx['ssl_certificate'] = "/etc/gitlab/ssl/pages-nginx.crt"
pages_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/pages-nginx.key"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
The resulting URL scheme is `https://<namespace>.example.io/<project_slug>`.
{{< alert type="warning" >}}
Multiple wildcards for one instance is not supported. Only one wildcard per instance can be assigned.
{{< /alert >}}
{{< alert type="warning" >}}
GitLab Pages does not update the OAuth application if changes are made to the redirect URI.
Before you reconfigure, remove the `gitlab_pages` section from `/etc/gitlab/gitlab-secrets.json`,
then run `gitlab-ctl reconfigure`. For more information, read
[GitLab Pages does not regenerate OAuth](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3947).
{{< /alert >}}
### Single-domain sites with TLS support
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
Prerequisites:
- You have configured DNS for
[single-domain sites](#dns-configuration-for-single-domain-sites).
- You have a TLS certificate that covers your domain (like `example.io`).
In this configuration, NGINX proxies all requests to the daemon. The GitLab Pages
daemon doesn't listen to the public internet:
1. Add your TLS certificate and key as mentioned in the prerequisites into `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb`, set the external URL for GitLab Pages, and enable the feature:
```ruby
external_url "https://example.com" # Swap out this URL for your own
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['redirect_http_to_https'] = true
# Set this flag to enable this feature
gitlab_pages['namespace_in_path'] = true
```
1. If your TLS certificate and key don't match the name of your domain, like
`example.io.crt` and `example.io.key`,
add the full paths for the certificate and key files to `/etc/gitlab/gitlab.rb`:
```ruby
pages_nginx['ssl_certificate'] = "/etc/gitlab/ssl/pages-nginx.crt"
pages_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/pages-nginx.key"
```
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
{{< alert type="warning" >}}
GitLab Pages does not update the OAuth application, and
the default `auth_redirect_uri` is updated to `https://example.io/projects/auth`.
Before you reconfigure, remove the `gitlab_pages` section from `/etc/gitlab/gitlab-secrets.json`,
then run `gitlab-ctl reconfigure`. For more information, see
[GitLab Pages does not regenerate OAuth](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3947).
{{< /alert >}}
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `https://example.io/<namespace>/<project_slug>`.
{{< alert type="warning" >}}
GitLab Pages supports only one URL scheme at a time:
wildcard domains or single-domain sites.
If you enable `namespace_in_path`, existing GitLab Pages websites
are accessible only as single-domain sites.
{{< /alert >}}
### Wildcard domains with TLS-terminating Load Balancer
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- [TLS-terminating load balancer](../../install/aws/_index.md#load-balancer)
This setup is primarily intended to be used when [installing a GitLab POC on Amazon Web Services](../../install/aws/_index.md). This includes a TLS-terminating [classic load balancer](../../install/aws/_index.md#load-balancer) that listens for HTTPS connections, manages TLS certificates, and forwards HTTP traffic to the instance.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['enable'] = true
pages_nginx['listen_port'] = 80
pages_nginx['listen_https'] = false
pages_nginx['redirect_http_to_https'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `https://<namespace>.example.io/<project_slug>`.
### Global settings
Below is a table of all configuration settings known to Pages in a Linux package installation,
and what they do. These options can be adjusted in `/etc/gitlab/gitlab.rb`,
and take effect after you [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
Most of these settings don't have to be configured manually unless you need more granular
control over how the Pages daemon runs and serves content in your environment.
| Setting | Default | Description |
| --------------------------------------- | ----------------------------------------------------- | ----------- |
| `pages_external_url` | N/A | The URL where GitLab Pages is accessible, including protocol (HTTP / HTTPS). If `https://` is used, additional configuration is required. See [Wildcard domains with TLS support](#wildcard-domains-with-tls-support) and [Custom domains with TLS support](#custom-domains-with-tls-support) for details. |
| **`gitlab_pages[]`** | N/A | |
| `access_control` | N/A | Whether to enable [access control](_index.md#access-control). |
| `api_secret_key` | Auto-generated | Full path to file with secret key used to authenticate with the GitLab API. |
| `artifacts_server` | N/A | Enable viewing [artifacts](../cicd/job_artifacts.md) in GitLab Pages. |
| `artifacts_server_timeout` | N/A | Timeout (in seconds) for a proxied request to the artifacts server. |
| `artifacts_server_url` | GitLab `external URL` + `/api/v4` | API URL to proxy artifact requests to, for example `https://gitlab.com/api/v4`. When running a [separate Pages server](#running-gitlab-pages-on-a-separate-server), this URL must point to the main GitLab server's API. |
| `auth_redirect_uri` | Project's subdomain of `pages_external_url` + `/auth` | Callback URL for authenticating with GitLab. URL should be subdomain of `pages_external_url` + `/auth`, for example `https://projects.example.io/auth`. When `namespace_in_path` is enabled, defaults to `pages_external_url` + `/projects/auth`, for example `https://example.io/projects/auth`. |
| `auth_secret` | Auto-pulled from GitLab | Secret key for signing authentication requests. Leave blank to pull automatically from GitLab during OAuth registration. |
| `client_cert` | N/A | Client certificate used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `client_key` | N/A | Client key used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `client_ca_certs` | N/A | Root CA certificates used to sign client certificate used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `dir` | N/A | Working directory for configuration and secrets files. |
| `enable` | N/A | Enable or disable GitLab Pages on the current system. |
| `external_http` | N/A | Configure Pages to bind to one or more secondary IP addresses, serving HTTP requests. Multiple addresses can be given as an array, along with exact ports, for example `['1.2.3.4', '1.2.3.5:8063']`. Sets value for `listen_http`. If running GitLab Pages behind a reverse proxy with TLS termination, specify `listen_proxy` instead of `external_http`. |
| `external_https` | N/A | Configure Pages to bind to one or more secondary IP addresses, serving HTTPS requests. Multiple addresses can be given as an array, along with exact ports, for example `['1.2.3.4', '1.2.3.5:8063']`. Sets value for `listen_https`. |
| `custom_domain_mode` | N/A | Configure Pages to enable custom domain: `http` or `https`. When running a [separate Pages server](#running-gitlab-pages-on-a-separate-server), configure this setting on the GitLab server as well. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/285089) in GitLab 18.1. |
| `server_shutdown_timeout` | `30s` | GitLab Pages server shutdown timeout in seconds. |
| `gitlab_client_http_timeout` | `10s` | GitLab API HTTP client connection timeout in seconds. |
| `gitlab_client_jwt_expiry` | `30s` | JWT Token expiry time in seconds. |
| `gitlab_cache_expiry` | `600s` | The maximum time a domain's configuration is stored in the cache. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_cache_refresh` | `60s` | The interval at which a domain's configuration is set to be due to refresh. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_cache_cleanup` | `60s` | The interval at which expired items are removed from the cache. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_timeout` | `30s` | The maximum time to wait for a response from the GitLab API per request. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_interval` | `1s` | The interval to wait before retrying to resolve a domain's configuration via the GitLab API. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_retries` | `3` | The maximum number of times to retry to resolve a domain's configuration via the API. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `domain_config_source` | N/A | This parameter was removed in 14.0, on earlier versions it can be used to enable and test API domain configuration source |
| `gitlab_id` | Auto-filled | The OAuth application public ID. Leave blank to automatically fill when Pages authenticates with GitLab. |
| `gitlab_secret` | Auto-filled | The OAuth application secret. Leave blank to automatically fill when Pages authenticates with GitLab. |
| `auth_scope` | `api` | The OAuth application scope to use for authentication. Must match GitLab Pages OAuth application settings. Leave blank to use `api` scope by default. |
| `auth_timeout` | `5s` | GitLab application client timeout for authentication in seconds. A value of `0` means no timeout. |
| `auth_cookie_session_timeout` | `10m` | Authentication cookie session timeout in seconds. A value of `0` means the cookie is deleted after the browser session ends. |
| `gitlab_server` | GitLab `external_url` | Server to use for authentication when access control is enabled. |
| `headers` | N/A | Specify any additional http headers that should be sent to the client with each response. Multiple headers can be given as an array, header and value as one string, for example `['my-header: myvalue', 'my-other-header: my-other-value']` |
| `enable_disk` | N/A | Allows the GitLab Pages daemon to serve content from disk. Shall be disabled if shared disk storage isn't available. |
| `insecure_ciphers` | N/A | Use default list of cipher suites, may contain insecure ones like 3DES and RC4. |
| `internal_gitlab_server` | GitLab `external_url` | Internal GitLab server address used exclusively for API requests. Useful if you want to send that traffic over an internal load balancer. |
| `listen_proxy` | N/A | The addresses to listen on for reverse-proxy requests. Pages binds to these addresses' network sockets and receives incoming requests from them. Sets the value of `proxy_pass` in `$nginx-dir/conf/gitlab-pages.conf`. |
| `log_directory` | N/A | Absolute path to a log directory. |
| `log_format` | N/A | The log output format: `text` or `json`. |
| `log_verbose` | N/A | Verbose logging, true/false. |
| `namespace_in_path` | `false` | Enable or disable namespace in the URL path to support [single-domain sites DNS setup](#dns-configuration-for-single-domain-sites). |
| `propagate_correlation_id` | `false` | Set to true to re-use existing Correlation ID from the incoming request header `X-Request-ID` if present. If a reverse proxy sets this header, the value is propagated in the request chain. |
| `max_connections` | N/A | Limit on the number of concurrent connections to the HTTP, HTTPS or proxy listeners. |
| `max_uri_length` | `2048` | The maximum length of URIs accepted by GitLab Pages. Set to 0 for unlimited length. |
| `metrics_address` | N/A | The address to listen on for metrics requests. |
| `redirect_http` | N/A | Redirect pages from HTTP to HTTPS, true/false. |
| `redirects_max_config_size` | `65536` | The maximum size of the `_redirects` file, in bytes. |
| `redirects_max_path_segments` | `25` | The maximum number of path segments allowed in `_redirects` rules URLs. |
| `redirects_max_rule_count` | `1000` | The maximum number of rules allowed in `_redirects`. |
| `sentry_dsn` | N/A | The address for sending Sentry crash reporting to. |
| `sentry_enabled` | N/A | Enable reporting and logging with Sentry, true/false. |
| `sentry_environment` | N/A | The environment for Sentry crash reporting. |
| `status_uri` | N/A | The URL path for a status page, for example, `/@status`. Configure to enable health check endpoint on GitLab Pages. |
| `tls_max_version` | N/A | Specifies the maximum TLS version ("tls1.2" or "tls1.3"). |
| `tls_min_version` | N/A | Specifies the minimum TLS version ("tls1.2" or "tls1.3"). |
| `use_http2` | N/A | Enable HTTP2 support. |
| **`gitlab_pages['env'][]`** | N/A | |
| `http_proxy` | N/A | Configure GitLab Pages to use an HTTP Proxy to mediate traffic between Pages and GitLab. Sets an environment variable `http_proxy` when starting Pages daemon. |
| **`gitlab_rails[]`** | N/A | |
| `pages_domain_verification_cron_worker` | N/A | Schedule for verifying custom GitLab Pages domains. |
| `pages_domain_ssl_renewal_cron_worker` | N/A | Schedule for obtaining and renewing SSL certificates through Let's Encrypt for GitLab Pages domains. |
| `pages_domain_removal_cron_worker` | N/A | Schedule for removing unverified custom GitLab Pages domains. |
| `pages_path` | `GITLAB-RAILS/shared/pages` | The directory on disk where pages are stored. |
| **`pages_nginx[]`** | N/A | |
| `enable` | N/A | Include a virtual host `server{}` block for Pages inside NGINX. Needed for NGINX to proxy traffic back to the Pages daemon. Set to `false` if the Pages daemon should directly receive all requests, for example, when using [custom domains](_index.md#custom-domains). |
| `FF_CONFIGURABLE_ROOT_DIR` | N/A | Feature flag to [customize the default folder](../../user/project/pages/introduction.md#customize-the-default-folder) (enabled by default). |
| `FF_ENABLE_PLACEHOLDERS` | N/A | Feature flag for rewrites (enabled by default). See [Rewrites](../../user/project/pages/redirects.md#rewrites) for more information. |
| `rate_limit_source_ip` | N/A | Rate limit per source IP in number of requests per second. Set to `0` to disable this feature. |
| `rate_limit_source_ip_burst` | N/A | Rate limit per source IP maximum burst allowed per second. |
| `rate_limit_domain` | N/A | Rate limit per domain in number of requests per second. Set to `0` to disable this feature. |
| `rate_limit_domain_burst` | N/A | Rate limit per domain maximum burst allowed per second. |
| `rate_limit_tls_source_ip` | N/A | Rate limit per source IP in number of TLS connections per second. Set to `0` to disable this feature. |
| `rate_limit_tls_source_ip_burst` | N/A | Rate limit per source IP maximum TLS connections burst allowed per second. |
| `rate_limit_tls_domain` | N/A | Rate limit per domain in number of TLS connections per second. Set to `0` to disable this feature. |
| `rate_limit_tls_domain_burst` | N/A | Rate limit per domain maximum TLS connections burst allowed per second. |
| `rate_limit_subnets_allow_list` | N/A | Allow list with the IP ranges (subnets) that should bypass all rate limits. For example, `['1.2.3.4/24', '2001:db8::1/32']`. [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/14653) in GitLab 17.3. |
| `server_read_timeout` | `5s` | Maximum duration to read the request headers and body. For no timeout, set to `0` or a negative value. |
| `server_read_header_timeout` | `1s` | Maximum duration to read the request headers. For no timeout, set to `0` or a negative value. |
| `server_write_timeout` | `0` | Maximum duration to write all files in the response. Larger files require more time. For no timeout, set to `0` or a negative value. |
| `server_keep_alive` | `15s` | The `Keep-Alive` period for network connections accepted by this listener. If `0`, `Keep-Alive` is enabled if supported by the protocol and operating system. If negative, `Keep-Alive` is disabled. |
## Advanced configuration
In addition to the wildcard domains, you can also have the option to configure
GitLab Pages to work with custom domains. Again, there are two options here:
support custom domains with and without TLS certificates. The easiest setup is
that without TLS certificates. In either case, you need a **secondary IP**. If
you have IPv6 and IPv4 addresses, you can use them both.
### Custom domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Secondary IP
In that case, the Pages daemon is running, NGINX still proxies requests to
the daemon but the daemon can receive requests from the outside
world. Custom domains are supported, but no TLS.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "http://example.com" # external_url here is only for reference
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
nginx['listen_addresses'] = ['192.0.2.1'] # The primary IP of the GitLab instance
pages_nginx['enable'] = false
gitlab_pages['external_http'] = ['192.0.2.2:80', '[2001:db8::2]:80'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['custom_domain_mode'] = 'http' # Enable custom domain
```
If you don't have IPv6, you can omit the IPv6 address.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL schemes are `http://<namespace>.example.io/<project_slug>` and `http://custom-domain.com`.
### Custom domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- TLS certificate. Can be either Wildcard, or any other type meeting the [requirements](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#manual-addition-of-ssltls-certificates).
- Secondary IP
In that case, the Pages daemon is running, NGINX still proxies requests to
the daemon but the daemon is also able to receive requests from the outside
world. Custom domains and TLS are supported.
1. Place the wildcard TLS certificate for `*.example.io` and the key inside `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
nginx['listen_addresses'] = ['192.0.2.1'] # The primary IP of the GitLab instance
pages_nginx['enable'] = false
gitlab_pages['external_http'] = ['192.0.2.2:80', '[2001:db8::2]:80'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['external_https'] = ['192.0.2.2:443', '[2001:db8::2]:443'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['custom_domain_mode'] = 'https' # Enable custom domain
# Redirect pages from HTTP to HTTPS
gitlab_pages['redirect_http'] = true
```
If you don't have IPv6, you can omit the IPv6 address.
1. If you haven't named your certificate `example.io.crt` and your key `example.io.key`,
then you need to also add the full paths as shown below:
```ruby
gitlab_pages['cert'] = "/etc/gitlab/ssl/example.io.crt"
gitlab_pages['cert_key'] = "/etc/gitlab/ssl/example.io.key"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
The resulting URL schemes are `https://<namespace>.example.io/<project_slug>` and `https://custom-domain.com`.
### Custom domain verification
To prevent malicious users from hijacking domains that don't belong to them,
GitLab supports [custom domain verification](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#steps).
When adding a custom domain, users are required to prove they own it by
adding a GitLab-controlled verification code to the DNS records for that domain.
{{< alert type="warning" >}}
Disabling domain verification is unsafe and can lead to various vulnerabilities.
If you do disable it, either ensure that the Pages root domain itself does not point to the
secondary IP or add the root domain as custom domain to a project; otherwise, any user can add this
domain as a custom domain to their project.
{{< /alert >}}
If your user base is private or otherwise trusted, you can disable the
verification requirement:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Clear the **Require users to prove ownership of custom domains** checkbox.
This setting is enabled by default.
### Let's Encrypt integration
[GitLab Pages' Let's Encrypt integration](../../user/project/pages/custom_domains_ssl_tls_certification/lets_encrypt_integration.md)
allows users to add Let's Encrypt SSL certificates for GitLab Pages
sites served under a custom domain.
To enable it:
1. Choose an email address on which you want to receive notifications about expiring domains.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter the email address for receiving notifications and accept the Terms of Service for Let's Encrypt.
1. Select **Save changes**.
### Access control
GitLab Pages access control can be configured per-project, and allows access to a Pages
site to be controlled based on a user's membership to that project.
Access control works by registering the Pages daemon as an OAuth application
with GitLab. Whenever a request to access a private Pages site is made by an
unauthenticated user, the Pages daemon redirects the user to GitLab. If
authentication is successful, the user is redirected back to Pages with a token,
which is persisted in a cookie. The cookies are signed with a secret key, so
tampering can be detected.
Each request to view a resource in a private site is authenticated by Pages
using that token. For each request it receives, it makes a request to the GitLab
API to check that the user is authorized to read that site.
Pages access control is disabled by default. To enable it:
1. Enable it in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['access_control'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Users can now configure it in their [projects' settings](../../user/project/pages/pages_access_control.md).
{{< alert type="note" >}}
For this setting to be effective with multi-node setups, it has to be applied to
all the App nodes and Sidekiq nodes.
{{< /alert >}}
#### Using Pages with reduced authentication scope
By default, the Pages daemon uses the `api` scope to authenticate. You can configure this. For
example, this reduces the scope to `read_api` in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['auth_scope'] = 'read_api'
```
The scope to use for authentication must match the GitLab Pages OAuth application settings. Users of
pre-existing applications must modify the GitLab Pages OAuth application. Follow these steps to do
this:
1. Enable [access control](#access-control).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications**.
1. Expand **GitLab Pages**.
1. Clear the `api` scope's checkbox and select the desired scope's checkbox (for example,
`read_api`).
1. Select **Save changes**.
#### Disable public access to all Pages sites
Prerequisites:
- You must have administrator access to the instance.
- You must enable [Access Control](#access-control) first for the setting to show in the **Admin** area.
You can enforce [Access Control](#access-control) for all GitLab Pages websites hosted
on your GitLab instance. By doing so, only authenticated users have access to them.
This setting overrides Access Control set by users in individual projects.
This can be helpful to restrict information published with Pages websites to the users
of your instance only.
To do that:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Select the **Disable public access to Pages sites** checkbox.
1. Select **Save changes**.
#### Disable unique domains by default
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/555559) in GitLab 18.3.
{{< /history >}}
Prerequisites:
- You must have administrator access to the instance.
By default, all newly created GitLab Pages sites use unique domain URLs
(for example, `my-project-1a2b3c.example.com`), which prevents cookie sharing
between different sites under the same namespace.
You can disable this default behavior so that new Pages sites use path-based URLs
(for example, `my-namespace.example.com/my-project`) instead.
However, this approach has the risk of cookie sharing between different sites under the same namespace.
This setting controls the default behavior for new sites only.
Users can still override this setting for individual projects.
To disable unique domains by default:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Clear the **Enable unique domains by default** checkbox.
1. Select **Save changes**.
This setting only affects new Pages sites.
Existing sites maintain their current unique domain configuration.
### Running behind a proxy
Like the rest of GitLab, Pages can be used in those environments where external
internet connectivity is gated by a proxy. To use a proxy for GitLab Pages:
1. Configure in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env']['http_proxy'] = 'http://example:8080'
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Using a custom Certificate Authority (CA)
When using certificates issued by a custom CA, [Access Control](../../user/project/pages/pages_access_control.md) and
the [online view of HTML job artifacts](../../ci/jobs/job_artifacts.md#download-job-artifacts)
fails to work if the custom CA is not recognized.
This usually results in this error:
`Post /oauth/token: x509: certificate signed by unknown authority`.
For Linux package installations, this is fixed by [installing a custom CA](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates).
For self-compiled installations, this can be fixed by installing the custom Certificate
Authority (CA) in the system certificate store.
### Support mutual TLS when calling the GitLab API
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/548) in GitLab 17.1.
{{< /history >}}
Prerequisites:
- Your instance must use the Linux package installation method.
If GitLab is [configured to require mutual TLS](https://docs.gitlab.com/omnibus/settings/ssl/#enable-2-way-ssl-client-authentication),
you must add client certificates to your GitLab Pages configuration.
Certificates have these requirements:
- The certificate must specify the hostname or IP address as a Subject Alternative Name.
- The full certificate chain is required, including the end-user certificate, intermediate certificates,
and the root certificate, in that order.
The certificate's Common Name field is ignored.
To configure the certificates in your GitLab Pages server:
1. On the GitLab Pages nodes, create the `/etc/gitlab/ssl` directory and copy your key and full certificate chain there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['client_cert'] = ['/etc/gitlab/ssl/cert.pem']
gitlab_pages['client_key'] = ['/etc/gitlab/ssl/key.pem']
```
1. If you used a custom Certificate Authority (CA), you must copy the root CA certificate to `/etc/gitlab/ssl`
and edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['client_ca_certs'] = ['/etc/gitlab/ssl/ca.pem']
```
File paths for multiple custom Certificate Authority (CA)s are separated by commas.
1. If you have a multi-node GitLab Pages installation, repeat these steps in all the nodes.
1. Save a copy of the full certificate chain files in the `/etc/gitlab/trusted-certs` directory on all your GitLab Nodes.
### ZIP serving and cache configuration
{{< alert type="warning" >}}
These instructions deal with some advanced settings of your GitLab instance. The recommended default values are set inside GitLab Pages. You should
change these settings only if absolutely necessary. Use extreme caution.
{{< /alert >}}
GitLab Pages can serve content from ZIP archives through object storage (an
[issue](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/485) exists for supporting disk storage
as well). It uses an in-memory cache to increase the performance when serving content from a ZIP
archive. You can modify the cache behavior by changing the following configuration flags.
| Setting | Description |
| ------- | ----------- |
| `zip_cache_expiration` | The cache expiration interval of ZIP archives. Must be greater than zero to avoid serving stale content. Default is `60s`. |
| `zip_cache_cleanup` | The interval at which archives are cleaned from memory if they have already expired. Default is `30s`. |
| `zip_cache_refresh` | The time interval in which an archive is extended in memory if accessed before `zip_cache_expiration`. This works together with `zip_cache_expiration` to determine if an archive is extended in memory. See the [example below](#zip-cache-refresh-example) for important details. Default is `30s`. |
| `zip_open_timeout` | The maximum time allowed to open a ZIP archive. Increase this time for big archives or slow network connections because doing so may affect the latency of serving Pages. Default is 30 s. |
| `zip_http_client_timeout` | The maximum time for the ZIP HTTP client. Default is `30m`. |
#### ZIP cache refresh example
Archives are refreshed in the cache (extending the time they are held in memory) if they're accessed
before `zip_cache_expiration`, and the time left before expiring is less than or equal to
`zip_cache_refresh`. For example, if `archive.zip` is accessed at time `0s`, it expires in `60s` (the
default for `zip_cache_expiration`). In the example below, if the archive is opened again after `15s`
it is **not** refreshed because the time left for expiry (`45s`) is greater than `zip_cache_refresh`
(default `30s`). However, if the archive is accessed again after `45s` (from the first time it was
opened) it's refreshed. This extends the time the archive remains in memory from
`45s + zip_cache_expiration (60s)`, for a total of `105s`.
After an archive reaches `zip_cache_expiration`, it's marked as expired and removed on the next
`zip_cache_cleanup` interval.

### HTTP Strict Transport Security (HSTS) support
HTTP Strict Transport Security (HSTS) can be enabled through the `gitlab_pages['headers']` configuration option. HSTS informs browsers that the website they are visiting should always provide its content over HTTPS to ensure that attackers cannot force subsequent connections to happen unencrypted. It can also improve loading speed of pages as it prevents browsers from attempting to connect over an unencrypted HTTP channel before being redirected to HTTPS.
```ruby
gitlab_pages['headers'] = ['Strict-Transport-Security: max-age=63072000']
```
### Pages project redirects limits
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-pages/-/merge_requests/778) in GitLab 15.2.
{{< /history >}}
GitLab Pages comes with a set of default limits for the [`_redirects` file](../../user/project/pages/redirects.md)
to minimize the impact on performance. You can configure these limits if you'd like to increase or decrease the limits.
```ruby
gitlab_pages['redirects_max_config_size'] = 131072
gitlab_pages['redirects_max_path_segments'] = 50
gitlab_pages['redirects_max_rule_count'] = 2000
```
## Use environment variables
You can pass an environment variable to the Pages daemon (for example,
to enable or disable a feature flag).
To disable the configurable directory feature:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env'] = {
'FF_CONFIGURABLE_ROOT_DIR' => "false"
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## Activate verbose logging for daemon
Follow the steps below to configure verbose logging of GitLab Pages daemon.
1. By default the daemon only logs with `INFO` level.
If you wish to make it log events with level `DEBUG` you must configure this in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['log_verbose'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Propagating the correlation ID
Setting the `propagate_correlation_id` to true allows installations behind a reverse proxy to generate
and set a correlation ID to requests sent to GitLab Pages. When a reverse proxy sets the header value `X-Request-ID`,
the value propagates in the request chain.
Users [can find the correlation ID in the logs](../logs/tracing_correlation_id.md#identify-the-correlation-id-for-a-request).
To enable the propagation of the correlation ID:
1. Set the parameter to true in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['propagate_correlation_id'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Change storage path
Follow the steps below to change the default path where GitLab Pages' contents
are stored.
1. Pages are stored by default in `/var/opt/gitlab/gitlab-rails/shared/pages`.
If you wish to store them in another location you must set it up in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['pages_path'] = "/mnt/storage/pages"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Configure listener for reverse proxy requests
Follow the steps below to configure the proxy listener of GitLab Pages.
1. By default the listener is configured to listen for requests on `localhost:8090`.
If you wish to disable it you must configure this in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['listen_proxy'] = nil
```
If you wish to make it listen on a different port you must configure this also in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['listen_proxy'] = "localhost:10080"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Set global maximum size of each GitLab Pages site
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the global maximum pages size for a project:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. In **Maximum size of pages**, enter a value. The default is `100`.
1. Select **Save changes**.
## Set maximum size of each GitLab Pages site in a group
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the maximum size of each GitLab Pages site in a group, overriding the inherited setting:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > General**.
1. Expand **Pages**.
1. Enter a value under **Maximum size** in MB.
1. Select **Save changes**.
## Set maximum size of GitLab Pages site in a project
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the maximum size of GitLab Pages site in a project, overriding the inherited setting:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Pages**.
1. In **Maximum size of pages**, enter the size in MB.
1. Select **Save changes**.
## Set maximum number of GitLab Pages custom domains for a project
Prerequisites:
- You must have administrator access to the instance.
To set the maximum number of GitLab Pages custom domains for a project:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter a value for **Maximum number of custom domains per project**. Use `0` for unlimited domains.
1. Select **Save changes**.
## Configure the default expiry for parallel deployments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/456477) in GitLab 17.4.
{{< /history >}}
Prerequisites:
- You must have administrator access to the instance.
To configure the default duration for the instance after which
[parallel deployments](../../user/project/pages/_index.md#parallel-deployments)
are deleted:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter a value for **Default expiration for parallel deployments in seconds**.
Use `0` if parallel deployments should not expire by default.
1. Select **Save changes**.
## Set maximum number of files per GitLab Pages website
The total number of file entries (including directories and symlinks) is limited to `200,000` per GitLab Pages website.
You can update the limit in your GitLab Self-Managed instance using the
[GitLab Rails console](../operations/rails_console.md#starting-a-rails-console-session).
For more information, see [GitLab application limits](../instance_limits.md#number-of-files-per-gitlab-pages-website).
## Running GitLab Pages on a separate server
You can run the GitLab Pages daemon on a separate server to decrease the load on
your main application server. This configuration does not support mutual TLS (mTLS). See the [corresponding feature proposal](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/548) for more information.
To configure GitLab Pages on a separate server:
{{< alert type="warning" >}}
The following procedure includes steps to back up and edit the
`gitlab-secrets.json` file. This file contains secrets that control
database encryption. Proceed with caution.
{{< /alert >}}
1. Optionally, to enable [access control](#access-control), add the following to `/etc/gitlab/gitlab.rb` and [reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation):
```ruby
gitlab_pages['access_control'] = true
```
{{< alert type="warning" >}}
If you plan to use GitLab Pages with access control, you must enable it on the first GitLab server before copying `gitlab-secrets.json`.
Enabling access control generates a new OAuth application, and information about it propagates to `gitlab-secrets.json`. If it's not done
in the correct order, you may face issues with access control.
{{< /alert >}}
1. Create a backup of the secrets file on the **GitLab server**:
```shell
cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.bak
```
1. On the **GitLab server**, to enable Pages, add the following to `/etc/gitlab/gitlab.rb`:
```ruby
pages_external_url "http://<pages_server_URL>"
```
1. Set up object storage by either:
- [Configuring the object storage and migrating GitLab Pages data to it](#object-storage-settings), or
- [Configuring network storage](#enable-pages-network-storage-in-multi-node-environments).
1. [Reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the
changes to take effect. The `gitlab-secrets.json` file is now updated with the
new configuration.
1. Set up a new server. This becomes the **Pages server**.
1. On the **Pages server**, install GitLab by using the Linux package and modify `/etc/gitlab/gitlab.rb`
to include:
```ruby
roles ['pages_role']
pages_external_url "http://<pages_server_URL>"
gitlab_pages['gitlab_server'] = 'http://<gitlab_server_IP_or_URL>'
## If access control was enabled on step 3
gitlab_pages['access_control'] = true
```
1. If you have custom UID/GID settings on the **GitLab server**, add them to the **Pages server** `/etc/gitlab/gitlab.rb` as well,
otherwise running a `gitlab-ctl reconfigure` on the **GitLab server** can change file ownership and cause Pages requests to fail.
1. Create a backup of the secrets file on the **Pages server**:
```shell
cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.bak
```
1. To enable custom domains for individual GitLab Pages sites, set up the **Pages server** using either:
- [Custom domains](#custom-domains)
- [Custom domains with TLS support](#custom-domains-with-tls-support)
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the **GitLab server**
to the **Pages server**.
```shell
# On the GitLab server
cp /etc/gitlab/gitlab-secrets.json /mnt/pages/gitlab-secrets.json
# On the Pages server
mv /var/opt/gitlab/gitlab-rails/shared/pages/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json
```
1. [Reconfigure the **Pages server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. On the **GitLab server**, make the following changes to `/etc/gitlab/gitlab.rb`:
```ruby
pages_external_url "http://<pages_server_URL>"
gitlab_pages['enable'] = false
pages_nginx['enable'] = false
```
1. To enable custom domains for individual GitLab Pages sites, on the **GitLab server**,
make the following changes to `/etc/gitlab/gitlab.rb`:
- Custom domains
```ruby
gitlab_pages['custom_domain_mode'] = 'http' # Enable custom domain mode to http
```
- Custom domains with TLS support
```ruby
gitlab_pages['custom_domain_mode'] = 'https' # Enable custom domain mode to https
```
1. [Reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
It's possible to run GitLab Pages on multiple servers if you wish to distribute
the load. You can do this through standard load balancing practices such as
configuring your DNS server to return multiple IPs for your Pages server, or
configuring a load balancer to work at the IP level. If you wish to
set up GitLab Pages on multiple servers, perform the previous procedure for each
Pages server.
## Domain source configuration
When GitLab Pages daemon serves pages requests it firstly needs to identify which project should be used to
serve the requested URL and how its content is stored.
By default, GitLab Pages uses the internal GitLab API every time a new domain is requested.
Pages fails to start if it can't connect to the API.
The domain information is also cached by the Pages daemon to speed up subsequent requests.
For common issues, see [troubleshooting](troubleshooting.md#failed-to-connect-to-the-internal-gitlab-api).
For more details see this [blog post](https://about.gitlab.com/blog/2020/08/03/how-gitlab-pages-uses-the-gitlab-api-to-serve-content/).
### GitLab API cache configuration
API-based configuration uses a caching mechanism to improve performance and reliability of serving Pages.
The cache behavior can be modified by changing the cache settings, however, the recommended values are set for you and should only be modified if needed.
Incorrect configuration of these values may result in intermittent
or persistent errors, or the Pages Daemon serving old content.
{{< alert type="note" >}}
Expiry, interval and timeout flags use [Go duration formatting](https://pkg.go.dev/time#ParseDuration).
A duration string is a possibly signed sequence of decimal numbers,
each with optional fraction and a unit suffix, such as `300ms`, `1.5h` or `2h45m`.
Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`.
{{< /alert >}}
Examples:
- Increasing `gitlab_cache_expiry` allows items to exist in the cache longer.
This setting might be useful if the communication between GitLab Pages and GitLab Rails
is not stable.
- Increasing `gitlab_cache_refresh` reduces the frequency at which GitLab Pages
requests a domain's configuration from GitLab Rails. This setting might be useful
GitLab Pages generates too many requests to GitLab API and content does not change frequently.
- Decreasing `gitlab_cache_cleanup` removes expired items from the cache more frequently,
reducing the memory usage of your Pages node.
- Decreasing `gitlab_retrieval_timeout` allows you to stop the request to GitLab Rails
more quickly. Increasing it allows more time to receive a response from the API,
useful in slow networking environments.
- Decreasing `gitlab_retrieval_interval` makes requests to the API more frequently,
only when there is an error response from the API, for example a connection timeout.
- Decreasing `gitlab_retrieval_retries` reduces the number of times a domain's
configuration is tried to be resolved automatically before reporting an error.
## Object storage settings
The following [object storage](../object_storage.md) settings are:
- Nested under `pages:` and then `object_store:` on self-compiled installations.
- Prefixed by `pages_object_store_` on Linux package installations.
| Setting | Description | Default |
|---------|-------------|---------|
| `enabled` | Whether object storage is enabled. | `false` |
| `remote_directory` | The name of the bucket where Pages site content is stored. | |
| `connection` | Various connection options described below. | |
{{< alert type="note" >}}
If you want to stop using and disconnect the NFS server, you need to
[explicitly disable local storage](#disable-pages-local-storage).
{{< /alert >}}
### S3-compatible connection settings
You should use the [consolidated object storage settings](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
See [the available connection settings for different providers](../object_storage.md#configure-the-connection-settings).
### Migrate Pages deployments to object storage
Existing Pages deployment objects (zip archives) can be stored in either:
- Local storage
- [Object storage](../object_storage.md)
Migrate your existing Pages deployments from local storage to object storage:
```shell
sudo gitlab-rake gitlab:pages:deployments:migrate_to_object_storage
```
You can track progress and verify that all Pages deployments migrated successfully using the
[PostgreSQL console](https://docs.gitlab.com/omnibus/settings/database.html#connecting-to-the-bundled-postgresql-database):
- `sudo gitlab-rails dbconsole --database main` for Linux package installations.
- `sudo -u git -H psql -d gitlabhq_production` for self-compiled installations.
Verify `objectstg` below (where `store=2`) has count of all Pages deployments:
```shell
gitlabhq_production=# SELECT count(*) AS total, sum(case when file_store = '1' then 1 else 0 end) AS filesystem, sum(case when file_store = '2' then 1 else 0 end) AS objectstg FROM pages_deployments;
total | filesystem | objectstg
------+------------+-----------
10 | 0 | 10
```
After verifying everything is working correctly,
[disable Pages local storage](#disable-pages-local-storage).
### Rolling Pages deployments back to local storage
After the migration to object storage is performed, you can choose to move your Pages deployments back to local storage:
```shell
sudo gitlab-rake gitlab:pages:deployments:migrate_to_local
```
### Disable Pages local storage
If you use [object storage](#object-storage-settings), you can disable local storage to avoid unnecessary disk usage/writes:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['pages_local_store_enabled'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Enable Pages network storage in multi-node environments
Object storage is the preferred configuration for most environments. However,
if your requirements call for network storage and you want to configure Pages
to run on a [separate server](#running-gitlab-pages-on-a-separate-server), you should:
1. Ensure the shared storage volume you intend to use is already mounted and
available on both the primary server and your intended Pages server.
1. Update the `/etc/gitlab/gitlab.rb` of each node to include:
```ruby
gitlab_pages['enable_disk'] = true
gitlab_rails['pages_path'] = "/var/opt/gitlab/gitlab-rails/shared/pages" # Path to your network storage
```
1. Switch over Pages to your separate server.
After you successfully configure Pages on your separate server, only that server
needs access to the shared storage volume. Consider keeping the shared storage volume
mounted on your primary server, in case you must migrate back to a single-node environment.
## ZIP storage
The underlying storage format of GitLab Pages is a single ZIP archive per project.
These ZIP archives can be stored either locally on disk storage or on [object storage](#object-storage-settings) if it is configured.
The ZIP archives are stored every time pages site is updated.
## Backup
GitLab Pages are part of the [regular backup](../backup_restore/_index.md), so there is no separate backup to configure.
## Security
You should strongly consider running GitLab Pages under a different hostname
than GitLab to prevent XSS attacks.
### Rate limits
{{< history >}}
- [Changed](https://gitlab.com/groups/gitlab-org/-/epics/14653) in GitLab 17.3: You can exclude subnets from Pages rate limits.
{{< /history >}}
You can enforce rate limits to help minimize the risk of a Denial of Service (DoS) attack. GitLab Pages
uses a [token bucket algorithm](https://en.wikipedia.org/wiki/Token_bucket) to enforce rate limiting. By default,
requests or TLS connections that exceed the specified limits are reported and rejected.
GitLab Pages supports the following types of rate limiting:
- Per `source_ip`. It limits how many requests or TLS connections are allowed from the single client IP address.
- Per `domain`. It limits how many requests or TLS connections are allowed per domain hosted on GitLab Pages. It can be a custom domain like `example.com`, or group domain like `group.gitlab.io`.
HTTP request-based rate limits are enforced using the following:
- `rate_limit_source_ip`: Sets the maximum threshold in number of requests per client IP per second. Set to 0 to disable this feature.
- `rate_limit_source_ip_burst`: Sets the maximum threshold of number of requests allowed in an initial outburst of requests per client IP.
For example, when you load a web page that loads multiple resources at the same time.
- `rate_limit_domain`: Sets the maximum threshold in number of requests per hosted pages domain per second. Set to 0 to disable this feature.
- `rate_limit_domain_burst`: Sets the maximum threshold of number of requests allowed in an initial outburst of requests per hosted pages domain.
TLS connection-based rate limits are enforced using the following:
- `rate_limit_tls_source_ip`: Sets the maximum threshold in number of TLS connections per client IP per second. Set to 0 to disable this feature.
- `rate_limit_tls_source_ip_burst`: Sets the maximum threshold of number of TLS connections allowed in an initial outburst of TLS connections per client IP.
For example, when you load a web page from different web browsers at the same time.
- `rate_limit_tls_domain`: Sets the maximum threshold in number of TLS connections per hosted pages domain per second. Set to 0 to disable this feature.
- `rate_limit_tls_domain_burst`: Sets the maximum threshold of number of TLS connections allowed in an initial outburst of TLS connections per hosted pages domain.
To allow certain IP ranges (subnets) to bypass all rate limits:
- `rate_limit_subnets_allow_list`: Sets the allow list with the IP ranges (subnets) that should bypass all rate limits.
For example, `['1.2.3.4/24', '2001:db8::1/32']`.
[Charts example](https://docs.gitlab.com/charts/charts/gitlab/gitlab-pages/#configure-rate-limits-subnets-allow-list) is available.
An IPv6 address receives a large prefix in the 128-bit address space. The prefix is typically at least size /64. Because of the large number of possible addresses, if the client's IP address is IPv6, the limit is applied to the IPv6 prefix with a length of 64, rather than the entire IPv6 address.
#### Enable HTTP requests rate limits by source-IP
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_source_ip'] = 20.0
gitlab_pages['rate_limit_source_ip_burst'] = 600
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable HTTP requests rate limits by domain
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_domain'] = 1000
gitlab_pages['rate_limit_domain_burst'] = 5000
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable TLS connections rate limits by source-IP
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_tls_source_ip'] = 20.0
gitlab_pages['rate_limit_tls_source_ip_burst'] = 600
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable TLS connections rate limits by domain
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_tls_domain'] = 1000
gitlab_pages['rate_limit_tls_domain_burst'] = 5000
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Related topics
- [Troubleshooting GitLab Pages administration](troubleshooting.md)
|
---
stage: Plan
group: Knowledge
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab Pages administration
breadcrumbs:
- doc
- administration
- pages
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab Pages provides static site hosting for GitLab projects and groups.
Server administrators must configure Pages before users can access this feature.
With GitLab Pages, administrators:
- Host static websites securely with custom domains and SSL/TLS certificates.
- Enable authentication to control access to Pages sites through GitLab permissions.
- Scale deployments using object storage or network storage in multi-node environments.
- Monitor and manage traffic with rate limiting and custom headers.
- Support IPv4 and IPv6 addresses for all Pages sites.
The GitLab Pages daemon runs as a separate process and can be configured either on the same server
as GitLab or on its own dedicated infrastructure.
For user documentation, see [GitLab Pages](../../user/project/pages/_index.md).
{{< alert type="note" >}}
This guide is for Linux package installations. If you have a self-compiled GitLab installation, see
[GitLab Pages administration for self-compiled installations](source.md).
{{< /alert >}}
## The GitLab Pages daemon
GitLab Pages makes use of the [GitLab Pages daemon](https://gitlab.com/gitlab-org/gitlab-pages), a basic HTTP server
written in Go that can listen on an external IP address and provide support for
custom domains and custom certificates. It supports dynamic certificates through
Server Name Indication (SNI) and exposes pages using HTTP2 by default.
You are encouraged to read its [README](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/README.md) to fully understand how
it works.
In the case of [custom domains](#custom-domains) (but not
[wildcard domains](#wildcard-domains)), the Pages daemon needs to listen on
ports `80` and/or `443`. For that reason, there is some flexibility in the way
which you can set it up:
- Run the Pages daemon in the same server as GitLab, listening on a **secondary IP**.
- Run the Pages daemon in a [separate server](#running-gitlab-pages-on-a-separate-server). In that case, the
[Pages path](#change-storage-path) must also be present in the server that
the Pages daemon is installed, so you must share it through the network.
- Run the Pages daemon in the same server as GitLab, listening on the same IP
but on different ports. In that case, you must proxy the traffic with
a load balancer. If you choose that route, you should use TCP load
balancing for HTTPS. If you use TLS-termination (HTTPS-load balancing), the
pages can't be served with user-provided certificates. For
HTTP it's OK to use HTTP or TCP load balancing.
In this document, we proceed assuming the first option. If you are not
supporting custom domains a secondary IP is not needed.
## Prerequisites
This section describes the prerequisites for configuring GitLab Pages.
### Wildcard domains
Before configuring Pages for wildcard domains, you must:
1. Have a domain for Pages that is not a subdomain of your GitLab instance domain.
| GitLab domain | Pages domain | Does it work? |
| -------------------- | ------------------- | ------------- |
| `example.com` | `example.io` | {{< icon name="check-circle" >}} Yes |
| `example.com` | `pages.example.com` | {{< icon name="dotted-circle" >}} No |
| `gitlab.example.com` | `pages.example.com` | {{< icon name="check-circle" >}} Yes |
1. Configure a **wildcard DNS record**.
1. Optional. Have a **wildcard certificate** for that domain if you decide to
serve Pages under HTTPS.
1. Optional but recommended. Enable [instance runners](../../ci/runners/_index.md)
so that your users don't have to bring their own.
1. For custom domains, have a **secondary IP**.
### Single-domain sites
Before configuring Pages for single-domain sites, you must:
1. Have a domain for Pages that is not a subdomain of your GitLab instance domain.
| GitLab domain | Pages domain | Supported |
| -------------------- | ------------------- | ------------- |
| `example.com` | `example.io` | {{< icon name="check-circle" >}} Yes |
| `example.com` | `pages.example.com` | {{< icon name="dotted-circle" >}} No |
| `gitlab.example.com` | `pages.example.com` | {{< icon name="check-circle" >}} Yes |
1. Configure a **DNS record**.
1. Optional. If you decide to serve Pages under HTTPS, have a **TLS certificate** for that domain.
1. Optional but recommended. Enable [instance runners](../../ci/runners/_index.md)
so that your users don't have to bring their own.
1. For custom domains, have a **secondary IP**.
{{< alert type="note" >}}
If your GitLab instance and the Pages daemon are deployed in a private network or behind a firewall, your GitLab Pages websites are only accessible to devices/users that have access to the private network.
{{< /alert >}}
### Add the domain to the Public Suffix List
The [Public Suffix List](https://publicsuffix.org) is used by browsers to
decide how to treat subdomains. If your GitLab instance allows members of the
public to create GitLab Pages sites, it also allows those users to create
subdomains on the pages domain (`example.io`). Adding the domain to the Public
Suffix List prevents browsers from accepting
[supercookies](https://en.wikipedia.org/wiki/HTTP_cookie#Supercookie),
among other things.
To submit your GitLab Pages subdomain, follow [Submit amendments to the Public Suffix List](https://publicsuffix.org/submit/).
For example, if your domain is `example.io`, you should
request that `example.io` is added to the Public Suffix List. GitLab.com
added `gitlab.io` [in 2016](https://gitlab.com/gitlab-com/gl-infra/reliability/-/issues/230).
### DNS configuration
GitLab Pages expect to run on their own virtual host. In your DNS server/provider
add a [wildcard DNS `A` record](https://en.wikipedia.org/wiki/Wildcard_DNS_record) pointing to the
host that GitLab runs. For example, an entry would look like this:
```plaintext
*.example.io. 1800 IN A 192.0.2.1
*.example.io. 1800 IN AAAA 2001:db8::1
```
Where `example.io` is the domain GitLab Pages is served from,
`192.0.2.1` is the IPv4 address of your GitLab instance, and `2001:db8::1` is the
IPv6 address. If you don't have IPv6, you can omit the `AAAA` record.
#### DNS configuration for single-domain sites
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
To configure GitLab Pages DNS for single-domain sites without wildcard DNS:
1. Enable the GitLab Pages flag for this feature by adding
`gitlab_pages['namespace_in_path'] = true` to `/etc/gitlab/gitlab.rb`.
1. In your DNS provider, add entries for `example.io`.
Replace `example.io` with your domain name, and `192.0.0.0` with
the IPv4 version of your IP address. The entries look like this:
```plaintext
example.io 1800 IN A 192.0.0.0
```
1. Optional. If your GitLab instance has an IPv6 address, add entries for it.
Replace `example.io` with your domain name, and `2001:db8::1` with
the IPv6 version of your IP address. The entries look like this:
```plaintext
example.io 1800 IN AAAA 2001:db8::1
```
This example contains the following:
- `example.io`: The domain GitLab Pages is served from.
#### DNS configuration for custom domains
If support for custom domains is needed, all subdomains of the Pages root domain should point to the
secondary IP (which is dedicated for the Pages daemon). Without this configuration, users can't use
`CNAME` records to point their custom domains to their GitLab Pages.
For example, an entry could look like this:
```plaintext
example.com 1800 IN A 192.0.2.1
*.example.io. 1800 IN A 192.0.2.2
```
This example contains the following:
- `example.com`: The GitLab domain.
- `example.io`: The domain GitLab Pages is served from.
- `192.0.2.1`: The primary IP of your GitLab instance.
- `192.0.2.2`: The secondary IP, which is dedicated to GitLab Pages. It must be different than the primary IP.
{{< alert type="note" >}}
You should not use the GitLab domain to serve user pages. For more information see the [security section](#security).
{{< /alert >}}
## Configuration
Depending on your needs, you can set up GitLab Pages in 4 different ways.
The following examples are listed from the easiest setup to the most
advanced one.
### Wildcard domains
The following configuration is the minimum setup to use GitLab Pages.
It is the foundation for all other setups described here.
In this configuration:
- NGINX proxies all requests to the GitLab Pages daemon.
- The GitLab Pages daemon doesn't listen directly to the public internet.
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
To configure GitLab Pages to use wildcard domains:
1. Set the external URL for GitLab Pages in `/etc/gitlab/gitlab.rb`:
```ruby
external_url "http://example.com" # external_url here is only for reference
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `http://<namespace>.example.io/<project_slug>`.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [How to Enable GitLab Pages for GitLab CE and EE](https://youtu.be/dD8c7WNcc6s).
<!-- Video published on 2017-02-22 -->
### Single-domain sites
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
The following configuration is the minimum setup to use GitLab Pages.
It is the foundation for all other setups described here.
In this configuration:
- NGINX proxies all requests to the GitLab Pages daemon.
- The GitLab Pages daemon doesn't listen directly to the public internet.
Prerequisites:
- You have configured DNS for
[single-domain sites](#dns-configuration-for-single-domain-sites).
To configure GitLab Pages to use single-domain sites:
1. In `/etc/gitlab/gitlab.rb`, set the external URL for GitLab Pages, and enable the feature:
```ruby
external_url "http://example.com" # Swap out this URL for your own
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
# Set this flag to enable this feature
gitlab_pages['namespace_in_path'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `http://example.io/<namespace>/<project_slug>`.
{{< alert type="warning" >}}
GitLab Pages supports only one URL scheme at a time:
wildcard domains or single-domain sites.
If you enable `namespace_in_path`, existing GitLab Pages websites
are accessible only on single-domain.
{{< /alert >}}
### Wildcard domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- TLS certificate. Can be either Wildcard, or any other type meeting the [requirements](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#manual-addition-of-ssltls-certificates).
NGINX proxies all requests to the daemon. Pages daemon doesn't listen to the
public internet.
1. Place the wildcard TLS certificate for `*.example.io` and the key inside `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['redirect_http_to_https'] = true
```
1. If you haven't named your certificate and key `example.io.crt` and `example.io.key`,
you must also add the full paths as shown below:
```ruby
pages_nginx['ssl_certificate'] = "/etc/gitlab/ssl/pages-nginx.crt"
pages_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/pages-nginx.key"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
The resulting URL scheme is `https://<namespace>.example.io/<project_slug>`.
{{< alert type="warning" >}}
Multiple wildcards for one instance is not supported. Only one wildcard per instance can be assigned.
{{< /alert >}}
{{< alert type="warning" >}}
GitLab Pages does not update the OAuth application if changes are made to the redirect URI.
Before you reconfigure, remove the `gitlab_pages` section from `/etc/gitlab/gitlab-secrets.json`,
then run `gitlab-ctl reconfigure`. For more information, read
[GitLab Pages does not regenerate OAuth](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3947).
{{< /alert >}}
### Single-domain sites with TLS support
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/17584) as an [experiment](../../policy/development_stages_support.md) in GitLab 16.7.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148621) to [beta](../../policy/development_stages_support.md) in GitLab 16.11.
- [Changed](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1111) implementation from NGINX to the GitLab Pages codebase in GitLab 17.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/483365) in GitLab 17.4.
{{< /history >}}
Prerequisites:
- You have configured DNS for
[single-domain sites](#dns-configuration-for-single-domain-sites).
- You have a TLS certificate that covers your domain (like `example.io`).
In this configuration, NGINX proxies all requests to the daemon. The GitLab Pages
daemon doesn't listen to the public internet:
1. Add your TLS certificate and key as mentioned in the prerequisites into `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb`, set the external URL for GitLab Pages, and enable the feature:
```ruby
external_url "https://example.com" # Swap out this URL for your own
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['redirect_http_to_https'] = true
# Set this flag to enable this feature
gitlab_pages['namespace_in_path'] = true
```
1. If your TLS certificate and key don't match the name of your domain, like
`example.io.crt` and `example.io.key`,
add the full paths for the certificate and key files to `/etc/gitlab/gitlab.rb`:
```ruby
pages_nginx['ssl_certificate'] = "/etc/gitlab/ssl/pages-nginx.crt"
pages_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/pages-nginx.key"
```
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
{{< alert type="warning" >}}
GitLab Pages does not update the OAuth application, and
the default `auth_redirect_uri` is updated to `https://example.io/projects/auth`.
Before you reconfigure, remove the `gitlab_pages` section from `/etc/gitlab/gitlab-secrets.json`,
then run `gitlab-ctl reconfigure`. For more information, see
[GitLab Pages does not regenerate OAuth](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/3947).
{{< /alert >}}
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `https://example.io/<namespace>/<project_slug>`.
{{< alert type="warning" >}}
GitLab Pages supports only one URL scheme at a time:
wildcard domains or single-domain sites.
If you enable `namespace_in_path`, existing GitLab Pages websites
are accessible only as single-domain sites.
{{< /alert >}}
### Wildcard domains with TLS-terminating Load Balancer
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- [TLS-terminating load balancer](../../install/aws/_index.md#load-balancer)
This setup is primarily intended to be used when [installing a GitLab POC on Amazon Web Services](../../install/aws/_index.md). This includes a TLS-terminating [classic load balancer](../../install/aws/_index.md#load-balancer) that listens for HTTPS connections, manages TLS certificates, and forwards HTTP traffic to the instance.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
pages_nginx['enable'] = true
pages_nginx['listen_port'] = 80
pages_nginx['listen_https'] = false
pages_nginx['redirect_http_to_https'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL scheme is `https://<namespace>.example.io/<project_slug>`.
### Global settings
Below is a table of all configuration settings known to Pages in a Linux package installation,
and what they do. These options can be adjusted in `/etc/gitlab/gitlab.rb`,
and take effect after you [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
Most of these settings don't have to be configured manually unless you need more granular
control over how the Pages daemon runs and serves content in your environment.
| Setting | Default | Description |
| --------------------------------------- | ----------------------------------------------------- | ----------- |
| `pages_external_url` | N/A | The URL where GitLab Pages is accessible, including protocol (HTTP / HTTPS). If `https://` is used, additional configuration is required. See [Wildcard domains with TLS support](#wildcard-domains-with-tls-support) and [Custom domains with TLS support](#custom-domains-with-tls-support) for details. |
| **`gitlab_pages[]`** | N/A | |
| `access_control` | N/A | Whether to enable [access control](_index.md#access-control). |
| `api_secret_key` | Auto-generated | Full path to file with secret key used to authenticate with the GitLab API. |
| `artifacts_server` | N/A | Enable viewing [artifacts](../cicd/job_artifacts.md) in GitLab Pages. |
| `artifacts_server_timeout` | N/A | Timeout (in seconds) for a proxied request to the artifacts server. |
| `artifacts_server_url` | GitLab `external URL` + `/api/v4` | API URL to proxy artifact requests to, for example `https://gitlab.com/api/v4`. When running a [separate Pages server](#running-gitlab-pages-on-a-separate-server), this URL must point to the main GitLab server's API. |
| `auth_redirect_uri` | Project's subdomain of `pages_external_url` + `/auth` | Callback URL for authenticating with GitLab. URL should be subdomain of `pages_external_url` + `/auth`, for example `https://projects.example.io/auth`. When `namespace_in_path` is enabled, defaults to `pages_external_url` + `/projects/auth`, for example `https://example.io/projects/auth`. |
| `auth_secret` | Auto-pulled from GitLab | Secret key for signing authentication requests. Leave blank to pull automatically from GitLab during OAuth registration. |
| `client_cert` | N/A | Client certificate used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `client_key` | N/A | Client key used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `client_ca_certs` | N/A | Root CA certificates used to sign client certificate used for mutual TLS with the GitLab API. See [Support mutual TLS when calling the GitLab API](#support-mutual-tls-when-calling-the-gitlab-api) for details. |
| `dir` | N/A | Working directory for configuration and secrets files. |
| `enable` | N/A | Enable or disable GitLab Pages on the current system. |
| `external_http` | N/A | Configure Pages to bind to one or more secondary IP addresses, serving HTTP requests. Multiple addresses can be given as an array, along with exact ports, for example `['1.2.3.4', '1.2.3.5:8063']`. Sets value for `listen_http`. If running GitLab Pages behind a reverse proxy with TLS termination, specify `listen_proxy` instead of `external_http`. |
| `external_https` | N/A | Configure Pages to bind to one or more secondary IP addresses, serving HTTPS requests. Multiple addresses can be given as an array, along with exact ports, for example `['1.2.3.4', '1.2.3.5:8063']`. Sets value for `listen_https`. |
| `custom_domain_mode` | N/A | Configure Pages to enable custom domain: `http` or `https`. When running a [separate Pages server](#running-gitlab-pages-on-a-separate-server), configure this setting on the GitLab server as well. [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/285089) in GitLab 18.1. |
| `server_shutdown_timeout` | `30s` | GitLab Pages server shutdown timeout in seconds. |
| `gitlab_client_http_timeout` | `10s` | GitLab API HTTP client connection timeout in seconds. |
| `gitlab_client_jwt_expiry` | `30s` | JWT Token expiry time in seconds. |
| `gitlab_cache_expiry` | `600s` | The maximum time a domain's configuration is stored in the cache. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_cache_refresh` | `60s` | The interval at which a domain's configuration is set to be due to refresh. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_cache_cleanup` | `60s` | The interval at which expired items are removed from the cache. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_timeout` | `30s` | The maximum time to wait for a response from the GitLab API per request. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_interval` | `1s` | The interval to wait before retrying to resolve a domain's configuration via the GitLab API. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `gitlab_retrieval_retries` | `3` | The maximum number of times to retry to resolve a domain's configuration via the API. For details, see [GitLab API cache configuration](#gitlab-api-cache-configuration). |
| `domain_config_source` | N/A | This parameter was removed in 14.0, on earlier versions it can be used to enable and test API domain configuration source |
| `gitlab_id` | Auto-filled | The OAuth application public ID. Leave blank to automatically fill when Pages authenticates with GitLab. |
| `gitlab_secret` | Auto-filled | The OAuth application secret. Leave blank to automatically fill when Pages authenticates with GitLab. |
| `auth_scope` | `api` | The OAuth application scope to use for authentication. Must match GitLab Pages OAuth application settings. Leave blank to use `api` scope by default. |
| `auth_timeout` | `5s` | GitLab application client timeout for authentication in seconds. A value of `0` means no timeout. |
| `auth_cookie_session_timeout` | `10m` | Authentication cookie session timeout in seconds. A value of `0` means the cookie is deleted after the browser session ends. |
| `gitlab_server` | GitLab `external_url` | Server to use for authentication when access control is enabled. |
| `headers` | N/A | Specify any additional http headers that should be sent to the client with each response. Multiple headers can be given as an array, header and value as one string, for example `['my-header: myvalue', 'my-other-header: my-other-value']` |
| `enable_disk` | N/A | Allows the GitLab Pages daemon to serve content from disk. Shall be disabled if shared disk storage isn't available. |
| `insecure_ciphers` | N/A | Use default list of cipher suites, may contain insecure ones like 3DES and RC4. |
| `internal_gitlab_server` | GitLab `external_url` | Internal GitLab server address used exclusively for API requests. Useful if you want to send that traffic over an internal load balancer. |
| `listen_proxy` | N/A | The addresses to listen on for reverse-proxy requests. Pages binds to these addresses' network sockets and receives incoming requests from them. Sets the value of `proxy_pass` in `$nginx-dir/conf/gitlab-pages.conf`. |
| `log_directory` | N/A | Absolute path to a log directory. |
| `log_format` | N/A | The log output format: `text` or `json`. |
| `log_verbose` | N/A | Verbose logging, true/false. |
| `namespace_in_path` | `false` | Enable or disable namespace in the URL path to support [single-domain sites DNS setup](#dns-configuration-for-single-domain-sites). |
| `propagate_correlation_id` | `false` | Set to true to re-use existing Correlation ID from the incoming request header `X-Request-ID` if present. If a reverse proxy sets this header, the value is propagated in the request chain. |
| `max_connections` | N/A | Limit on the number of concurrent connections to the HTTP, HTTPS or proxy listeners. |
| `max_uri_length` | `2048` | The maximum length of URIs accepted by GitLab Pages. Set to 0 for unlimited length. |
| `metrics_address` | N/A | The address to listen on for metrics requests. |
| `redirect_http` | N/A | Redirect pages from HTTP to HTTPS, true/false. |
| `redirects_max_config_size` | `65536` | The maximum size of the `_redirects` file, in bytes. |
| `redirects_max_path_segments` | `25` | The maximum number of path segments allowed in `_redirects` rules URLs. |
| `redirects_max_rule_count` | `1000` | The maximum number of rules allowed in `_redirects`. |
| `sentry_dsn` | N/A | The address for sending Sentry crash reporting to. |
| `sentry_enabled` | N/A | Enable reporting and logging with Sentry, true/false. |
| `sentry_environment` | N/A | The environment for Sentry crash reporting. |
| `status_uri` | N/A | The URL path for a status page, for example, `/@status`. Configure to enable health check endpoint on GitLab Pages. |
| `tls_max_version` | N/A | Specifies the maximum TLS version ("tls1.2" or "tls1.3"). |
| `tls_min_version` | N/A | Specifies the minimum TLS version ("tls1.2" or "tls1.3"). |
| `use_http2` | N/A | Enable HTTP2 support. |
| **`gitlab_pages['env'][]`** | N/A | |
| `http_proxy` | N/A | Configure GitLab Pages to use an HTTP Proxy to mediate traffic between Pages and GitLab. Sets an environment variable `http_proxy` when starting Pages daemon. |
| **`gitlab_rails[]`** | N/A | |
| `pages_domain_verification_cron_worker` | N/A | Schedule for verifying custom GitLab Pages domains. |
| `pages_domain_ssl_renewal_cron_worker` | N/A | Schedule for obtaining and renewing SSL certificates through Let's Encrypt for GitLab Pages domains. |
| `pages_domain_removal_cron_worker` | N/A | Schedule for removing unverified custom GitLab Pages domains. |
| `pages_path` | `GITLAB-RAILS/shared/pages` | The directory on disk where pages are stored. |
| **`pages_nginx[]`** | N/A | |
| `enable` | N/A | Include a virtual host `server{}` block for Pages inside NGINX. Needed for NGINX to proxy traffic back to the Pages daemon. Set to `false` if the Pages daemon should directly receive all requests, for example, when using [custom domains](_index.md#custom-domains). |
| `FF_CONFIGURABLE_ROOT_DIR` | N/A | Feature flag to [customize the default folder](../../user/project/pages/introduction.md#customize-the-default-folder) (enabled by default). |
| `FF_ENABLE_PLACEHOLDERS` | N/A | Feature flag for rewrites (enabled by default). See [Rewrites](../../user/project/pages/redirects.md#rewrites) for more information. |
| `rate_limit_source_ip` | N/A | Rate limit per source IP in number of requests per second. Set to `0` to disable this feature. |
| `rate_limit_source_ip_burst` | N/A | Rate limit per source IP maximum burst allowed per second. |
| `rate_limit_domain` | N/A | Rate limit per domain in number of requests per second. Set to `0` to disable this feature. |
| `rate_limit_domain_burst` | N/A | Rate limit per domain maximum burst allowed per second. |
| `rate_limit_tls_source_ip` | N/A | Rate limit per source IP in number of TLS connections per second. Set to `0` to disable this feature. |
| `rate_limit_tls_source_ip_burst` | N/A | Rate limit per source IP maximum TLS connections burst allowed per second. |
| `rate_limit_tls_domain` | N/A | Rate limit per domain in number of TLS connections per second. Set to `0` to disable this feature. |
| `rate_limit_tls_domain_burst` | N/A | Rate limit per domain maximum TLS connections burst allowed per second. |
| `rate_limit_subnets_allow_list` | N/A | Allow list with the IP ranges (subnets) that should bypass all rate limits. For example, `['1.2.3.4/24', '2001:db8::1/32']`. [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/14653) in GitLab 17.3. |
| `server_read_timeout` | `5s` | Maximum duration to read the request headers and body. For no timeout, set to `0` or a negative value. |
| `server_read_header_timeout` | `1s` | Maximum duration to read the request headers. For no timeout, set to `0` or a negative value. |
| `server_write_timeout` | `0` | Maximum duration to write all files in the response. Larger files require more time. For no timeout, set to `0` or a negative value. |
| `server_keep_alive` | `15s` | The `Keep-Alive` period for network connections accepted by this listener. If `0`, `Keep-Alive` is enabled if supported by the protocol and operating system. If negative, `Keep-Alive` is disabled. |
## Advanced configuration
In addition to the wildcard domains, you can also have the option to configure
GitLab Pages to work with custom domains. Again, there are two options here:
support custom domains with and without TLS certificates. The easiest setup is
that without TLS certificates. In either case, you need a **secondary IP**. If
you have IPv6 and IPv4 addresses, you can use them both.
### Custom domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Secondary IP
In that case, the Pages daemon is running, NGINX still proxies requests to
the daemon but the daemon can receive requests from the outside
world. Custom domains are supported, but no TLS.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "http://example.com" # external_url here is only for reference
pages_external_url 'http://example.io' # Important: not a subdomain of external_url, so cannot be http://pages.example.com
nginx['listen_addresses'] = ['192.0.2.1'] # The primary IP of the GitLab instance
pages_nginx['enable'] = false
gitlab_pages['external_http'] = ['192.0.2.2:80', '[2001:db8::2]:80'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['custom_domain_mode'] = 'http' # Enable custom domain
```
If you don't have IPv6, you can omit the IPv6 address.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
The resulting URL schemes are `http://<namespace>.example.io/<project_slug>` and `http://custom-domain.com`.
### Custom domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- TLS certificate. Can be either Wildcard, or any other type meeting the [requirements](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#manual-addition-of-ssltls-certificates).
- Secondary IP
In that case, the Pages daemon is running, NGINX still proxies requests to
the daemon but the daemon is also able to receive requests from the outside
world. Custom domains and TLS are supported.
1. Place the wildcard TLS certificate for `*.example.io` and the key inside `/etc/gitlab/ssl`.
1. In `/etc/gitlab/gitlab.rb` specify the following configuration:
```ruby
external_url "https://example.com" # external_url here is only for reference
pages_external_url 'https://example.io' # Important: not a subdomain of external_url, so cannot be https://pages.example.com
nginx['listen_addresses'] = ['192.0.2.1'] # The primary IP of the GitLab instance
pages_nginx['enable'] = false
gitlab_pages['external_http'] = ['192.0.2.2:80', '[2001:db8::2]:80'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['external_https'] = ['192.0.2.2:443', '[2001:db8::2]:443'] # The secondary IPs for the GitLab Pages daemon
gitlab_pages['custom_domain_mode'] = 'https' # Enable custom domain
# Redirect pages from HTTP to HTTPS
gitlab_pages['redirect_http'] = true
```
If you don't have IPv6, you can omit the IPv6 address.
1. If you haven't named your certificate `example.io.crt` and your key `example.io.key`,
then you need to also add the full paths as shown below:
```ruby
gitlab_pages['cert'] = "/etc/gitlab/ssl/example.io.crt"
gitlab_pages['cert_key'] = "/etc/gitlab/ssl/example.io.key"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. If you're using [Pages Access Control](#access-control), update the redirect URI in the GitLab Pages
[System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application)
to use the HTTPS protocol.
The resulting URL schemes are `https://<namespace>.example.io/<project_slug>` and `https://custom-domain.com`.
### Custom domain verification
To prevent malicious users from hijacking domains that don't belong to them,
GitLab supports [custom domain verification](../../user/project/pages/custom_domains_ssl_tls_certification/_index.md#steps).
When adding a custom domain, users are required to prove they own it by
adding a GitLab-controlled verification code to the DNS records for that domain.
{{< alert type="warning" >}}
Disabling domain verification is unsafe and can lead to various vulnerabilities.
If you do disable it, either ensure that the Pages root domain itself does not point to the
secondary IP or add the root domain as custom domain to a project; otherwise, any user can add this
domain as a custom domain to their project.
{{< /alert >}}
If your user base is private or otherwise trusted, you can disable the
verification requirement:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Clear the **Require users to prove ownership of custom domains** checkbox.
This setting is enabled by default.
### Let's Encrypt integration
[GitLab Pages' Let's Encrypt integration](../../user/project/pages/custom_domains_ssl_tls_certification/lets_encrypt_integration.md)
allows users to add Let's Encrypt SSL certificates for GitLab Pages
sites served under a custom domain.
To enable it:
1. Choose an email address on which you want to receive notifications about expiring domains.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter the email address for receiving notifications and accept the Terms of Service for Let's Encrypt.
1. Select **Save changes**.
### Access control
GitLab Pages access control can be configured per-project, and allows access to a Pages
site to be controlled based on a user's membership to that project.
Access control works by registering the Pages daemon as an OAuth application
with GitLab. Whenever a request to access a private Pages site is made by an
unauthenticated user, the Pages daemon redirects the user to GitLab. If
authentication is successful, the user is redirected back to Pages with a token,
which is persisted in a cookie. The cookies are signed with a secret key, so
tampering can be detected.
Each request to view a resource in a private site is authenticated by Pages
using that token. For each request it receives, it makes a request to the GitLab
API to check that the user is authorized to read that site.
Pages access control is disabled by default. To enable it:
1. Enable it in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['access_control'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Users can now configure it in their [projects' settings](../../user/project/pages/pages_access_control.md).
{{< alert type="note" >}}
For this setting to be effective with multi-node setups, it has to be applied to
all the App nodes and Sidekiq nodes.
{{< /alert >}}
#### Using Pages with reduced authentication scope
By default, the Pages daemon uses the `api` scope to authenticate. You can configure this. For
example, this reduces the scope to `read_api` in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['auth_scope'] = 'read_api'
```
The scope to use for authentication must match the GitLab Pages OAuth application settings. Users of
pre-existing applications must modify the GitLab Pages OAuth application. Follow these steps to do
this:
1. Enable [access control](#access-control).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications**.
1. Expand **GitLab Pages**.
1. Clear the `api` scope's checkbox and select the desired scope's checkbox (for example,
`read_api`).
1. Select **Save changes**.
#### Disable public access to all Pages sites
Prerequisites:
- You must have administrator access to the instance.
- You must enable [Access Control](#access-control) first for the setting to show in the **Admin** area.
You can enforce [Access Control](#access-control) for all GitLab Pages websites hosted
on your GitLab instance. By doing so, only authenticated users have access to them.
This setting overrides Access Control set by users in individual projects.
This can be helpful to restrict information published with Pages websites to the users
of your instance only.
To do that:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Select the **Disable public access to Pages sites** checkbox.
1. Select **Save changes**.
#### Disable unique domains by default
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/555559) in GitLab 18.3.
{{< /history >}}
Prerequisites:
- You must have administrator access to the instance.
By default, all newly created GitLab Pages sites use unique domain URLs
(for example, `my-project-1a2b3c.example.com`), which prevents cookie sharing
between different sites under the same namespace.
You can disable this default behavior so that new Pages sites use path-based URLs
(for example, `my-namespace.example.com/my-project`) instead.
However, this approach has the risk of cookie sharing between different sites under the same namespace.
This setting controls the default behavior for new sites only.
Users can still override this setting for individual projects.
To disable unique domains by default:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Clear the **Enable unique domains by default** checkbox.
1. Select **Save changes**.
This setting only affects new Pages sites.
Existing sites maintain their current unique domain configuration.
### Running behind a proxy
Like the rest of GitLab, Pages can be used in those environments where external
internet connectivity is gated by a proxy. To use a proxy for GitLab Pages:
1. Configure in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env']['http_proxy'] = 'http://example:8080'
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Using a custom Certificate Authority (CA)
When using certificates issued by a custom CA, [Access Control](../../user/project/pages/pages_access_control.md) and
the [online view of HTML job artifacts](../../ci/jobs/job_artifacts.md#download-job-artifacts)
fails to work if the custom CA is not recognized.
This usually results in this error:
`Post /oauth/token: x509: certificate signed by unknown authority`.
For Linux package installations, this is fixed by [installing a custom CA](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates).
For self-compiled installations, this can be fixed by installing the custom Certificate
Authority (CA) in the system certificate store.
### Support mutual TLS when calling the GitLab API
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/548) in GitLab 17.1.
{{< /history >}}
Prerequisites:
- Your instance must use the Linux package installation method.
If GitLab is [configured to require mutual TLS](https://docs.gitlab.com/omnibus/settings/ssl/#enable-2-way-ssl-client-authentication),
you must add client certificates to your GitLab Pages configuration.
Certificates have these requirements:
- The certificate must specify the hostname or IP address as a Subject Alternative Name.
- The full certificate chain is required, including the end-user certificate, intermediate certificates,
and the root certificate, in that order.
The certificate's Common Name field is ignored.
To configure the certificates in your GitLab Pages server:
1. On the GitLab Pages nodes, create the `/etc/gitlab/ssl` directory and copy your key and full certificate chain there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['client_cert'] = ['/etc/gitlab/ssl/cert.pem']
gitlab_pages['client_key'] = ['/etc/gitlab/ssl/key.pem']
```
1. If you used a custom Certificate Authority (CA), you must copy the root CA certificate to `/etc/gitlab/ssl`
and edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['client_ca_certs'] = ['/etc/gitlab/ssl/ca.pem']
```
File paths for multiple custom Certificate Authority (CA)s are separated by commas.
1. If you have a multi-node GitLab Pages installation, repeat these steps in all the nodes.
1. Save a copy of the full certificate chain files in the `/etc/gitlab/trusted-certs` directory on all your GitLab Nodes.
### ZIP serving and cache configuration
{{< alert type="warning" >}}
These instructions deal with some advanced settings of your GitLab instance. The recommended default values are set inside GitLab Pages. You should
change these settings only if absolutely necessary. Use extreme caution.
{{< /alert >}}
GitLab Pages can serve content from ZIP archives through object storage (an
[issue](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/485) exists for supporting disk storage
as well). It uses an in-memory cache to increase the performance when serving content from a ZIP
archive. You can modify the cache behavior by changing the following configuration flags.
| Setting | Description |
| ------- | ----------- |
| `zip_cache_expiration` | The cache expiration interval of ZIP archives. Must be greater than zero to avoid serving stale content. Default is `60s`. |
| `zip_cache_cleanup` | The interval at which archives are cleaned from memory if they have already expired. Default is `30s`. |
| `zip_cache_refresh` | The time interval in which an archive is extended in memory if accessed before `zip_cache_expiration`. This works together with `zip_cache_expiration` to determine if an archive is extended in memory. See the [example below](#zip-cache-refresh-example) for important details. Default is `30s`. |
| `zip_open_timeout` | The maximum time allowed to open a ZIP archive. Increase this time for big archives or slow network connections because doing so may affect the latency of serving Pages. Default is 30 s. |
| `zip_http_client_timeout` | The maximum time for the ZIP HTTP client. Default is `30m`. |
#### ZIP cache refresh example
Archives are refreshed in the cache (extending the time they are held in memory) if they're accessed
before `zip_cache_expiration`, and the time left before expiring is less than or equal to
`zip_cache_refresh`. For example, if `archive.zip` is accessed at time `0s`, it expires in `60s` (the
default for `zip_cache_expiration`). In the example below, if the archive is opened again after `15s`
it is **not** refreshed because the time left for expiry (`45s`) is greater than `zip_cache_refresh`
(default `30s`). However, if the archive is accessed again after `45s` (from the first time it was
opened) it's refreshed. This extends the time the archive remains in memory from
`45s + zip_cache_expiration (60s)`, for a total of `105s`.
After an archive reaches `zip_cache_expiration`, it's marked as expired and removed on the next
`zip_cache_cleanup` interval.

### HTTP Strict Transport Security (HSTS) support
HTTP Strict Transport Security (HSTS) can be enabled through the `gitlab_pages['headers']` configuration option. HSTS informs browsers that the website they are visiting should always provide its content over HTTPS to ensure that attackers cannot force subsequent connections to happen unencrypted. It can also improve loading speed of pages as it prevents browsers from attempting to connect over an unencrypted HTTP channel before being redirected to HTTPS.
```ruby
gitlab_pages['headers'] = ['Strict-Transport-Security: max-age=63072000']
```
### Pages project redirects limits
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-pages/-/merge_requests/778) in GitLab 15.2.
{{< /history >}}
GitLab Pages comes with a set of default limits for the [`_redirects` file](../../user/project/pages/redirects.md)
to minimize the impact on performance. You can configure these limits if you'd like to increase or decrease the limits.
```ruby
gitlab_pages['redirects_max_config_size'] = 131072
gitlab_pages['redirects_max_path_segments'] = 50
gitlab_pages['redirects_max_rule_count'] = 2000
```
## Use environment variables
You can pass an environment variable to the Pages daemon (for example,
to enable or disable a feature flag).
To disable the configurable directory feature:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env'] = {
'FF_CONFIGURABLE_ROOT_DIR' => "false"
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## Activate verbose logging for daemon
Follow the steps below to configure verbose logging of GitLab Pages daemon.
1. By default the daemon only logs with `INFO` level.
If you wish to make it log events with level `DEBUG` you must configure this in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['log_verbose'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Propagating the correlation ID
Setting the `propagate_correlation_id` to true allows installations behind a reverse proxy to generate
and set a correlation ID to requests sent to GitLab Pages. When a reverse proxy sets the header value `X-Request-ID`,
the value propagates in the request chain.
Users [can find the correlation ID in the logs](../logs/tracing_correlation_id.md#identify-the-correlation-id-for-a-request).
To enable the propagation of the correlation ID:
1. Set the parameter to true in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['propagate_correlation_id'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Change storage path
Follow the steps below to change the default path where GitLab Pages' contents
are stored.
1. Pages are stored by default in `/var/opt/gitlab/gitlab-rails/shared/pages`.
If you wish to store them in another location you must set it up in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['pages_path'] = "/mnt/storage/pages"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Configure listener for reverse proxy requests
Follow the steps below to configure the proxy listener of GitLab Pages.
1. By default the listener is configured to listen for requests on `localhost:8090`.
If you wish to disable it you must configure this in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['listen_proxy'] = nil
```
If you wish to make it listen on a different port you must configure this also in
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['listen_proxy'] = "localhost:10080"
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Set global maximum size of each GitLab Pages site
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the global maximum pages size for a project:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. In **Maximum size of pages**, enter a value. The default is `100`.
1. Select **Save changes**.
## Set maximum size of each GitLab Pages site in a group
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the maximum size of each GitLab Pages site in a group, overriding the inherited setting:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > General**.
1. Expand **Pages**.
1. Enter a value under **Maximum size** in MB.
1. Select **Save changes**.
## Set maximum size of GitLab Pages site in a project
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Prerequisites:
- You must have administrator access to the instance.
To set the maximum size of GitLab Pages site in a project, overriding the inherited setting:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Pages**.
1. In **Maximum size of pages**, enter the size in MB.
1. Select **Save changes**.
## Set maximum number of GitLab Pages custom domains for a project
Prerequisites:
- You must have administrator access to the instance.
To set the maximum number of GitLab Pages custom domains for a project:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter a value for **Maximum number of custom domains per project**. Use `0` for unlimited domains.
1. Select **Save changes**.
## Configure the default expiry for parallel deployments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/456477) in GitLab 17.4.
{{< /history >}}
Prerequisites:
- You must have administrator access to the instance.
To configure the default duration for the instance after which
[parallel deployments](../../user/project/pages/_index.md#parallel-deployments)
are deleted:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Enter a value for **Default expiration for parallel deployments in seconds**.
Use `0` if parallel deployments should not expire by default.
1. Select **Save changes**.
## Set maximum number of files per GitLab Pages website
The total number of file entries (including directories and symlinks) is limited to `200,000` per GitLab Pages website.
You can update the limit in your GitLab Self-Managed instance using the
[GitLab Rails console](../operations/rails_console.md#starting-a-rails-console-session).
For more information, see [GitLab application limits](../instance_limits.md#number-of-files-per-gitlab-pages-website).
## Running GitLab Pages on a separate server
You can run the GitLab Pages daemon on a separate server to decrease the load on
your main application server. This configuration does not support mutual TLS (mTLS). See the [corresponding feature proposal](https://gitlab.com/gitlab-org/gitlab-pages/-/issues/548) for more information.
To configure GitLab Pages on a separate server:
{{< alert type="warning" >}}
The following procedure includes steps to back up and edit the
`gitlab-secrets.json` file. This file contains secrets that control
database encryption. Proceed with caution.
{{< /alert >}}
1. Optionally, to enable [access control](#access-control), add the following to `/etc/gitlab/gitlab.rb` and [reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation):
```ruby
gitlab_pages['access_control'] = true
```
{{< alert type="warning" >}}
If you plan to use GitLab Pages with access control, you must enable it on the first GitLab server before copying `gitlab-secrets.json`.
Enabling access control generates a new OAuth application, and information about it propagates to `gitlab-secrets.json`. If it's not done
in the correct order, you may face issues with access control.
{{< /alert >}}
1. Create a backup of the secrets file on the **GitLab server**:
```shell
cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.bak
```
1. On the **GitLab server**, to enable Pages, add the following to `/etc/gitlab/gitlab.rb`:
```ruby
pages_external_url "http://<pages_server_URL>"
```
1. Set up object storage by either:
- [Configuring the object storage and migrating GitLab Pages data to it](#object-storage-settings), or
- [Configuring network storage](#enable-pages-network-storage-in-multi-node-environments).
1. [Reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the
changes to take effect. The `gitlab-secrets.json` file is now updated with the
new configuration.
1. Set up a new server. This becomes the **Pages server**.
1. On the **Pages server**, install GitLab by using the Linux package and modify `/etc/gitlab/gitlab.rb`
to include:
```ruby
roles ['pages_role']
pages_external_url "http://<pages_server_URL>"
gitlab_pages['gitlab_server'] = 'http://<gitlab_server_IP_or_URL>'
## If access control was enabled on step 3
gitlab_pages['access_control'] = true
```
1. If you have custom UID/GID settings on the **GitLab server**, add them to the **Pages server** `/etc/gitlab/gitlab.rb` as well,
otherwise running a `gitlab-ctl reconfigure` on the **GitLab server** can change file ownership and cause Pages requests to fail.
1. Create a backup of the secrets file on the **Pages server**:
```shell
cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.bak
```
1. To enable custom domains for individual GitLab Pages sites, set up the **Pages server** using either:
- [Custom domains](#custom-domains)
- [Custom domains with TLS support](#custom-domains-with-tls-support)
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the **GitLab server**
to the **Pages server**.
```shell
# On the GitLab server
cp /etc/gitlab/gitlab-secrets.json /mnt/pages/gitlab-secrets.json
# On the Pages server
mv /var/opt/gitlab/gitlab-rails/shared/pages/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json
```
1. [Reconfigure the **Pages server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. On the **GitLab server**, make the following changes to `/etc/gitlab/gitlab.rb`:
```ruby
pages_external_url "http://<pages_server_URL>"
gitlab_pages['enable'] = false
pages_nginx['enable'] = false
```
1. To enable custom domains for individual GitLab Pages sites, on the **GitLab server**,
make the following changes to `/etc/gitlab/gitlab.rb`:
- Custom domains
```ruby
gitlab_pages['custom_domain_mode'] = 'http' # Enable custom domain mode to http
```
- Custom domains with TLS support
```ruby
gitlab_pages['custom_domain_mode'] = 'https' # Enable custom domain mode to https
```
1. [Reconfigure the **GitLab server**](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
It's possible to run GitLab Pages on multiple servers if you wish to distribute
the load. You can do this through standard load balancing practices such as
configuring your DNS server to return multiple IPs for your Pages server, or
configuring a load balancer to work at the IP level. If you wish to
set up GitLab Pages on multiple servers, perform the previous procedure for each
Pages server.
## Domain source configuration
When GitLab Pages daemon serves pages requests it firstly needs to identify which project should be used to
serve the requested URL and how its content is stored.
By default, GitLab Pages uses the internal GitLab API every time a new domain is requested.
Pages fails to start if it can't connect to the API.
The domain information is also cached by the Pages daemon to speed up subsequent requests.
For common issues, see [troubleshooting](troubleshooting.md#failed-to-connect-to-the-internal-gitlab-api).
For more details see this [blog post](https://about.gitlab.com/blog/2020/08/03/how-gitlab-pages-uses-the-gitlab-api-to-serve-content/).
### GitLab API cache configuration
API-based configuration uses a caching mechanism to improve performance and reliability of serving Pages.
The cache behavior can be modified by changing the cache settings, however, the recommended values are set for you and should only be modified if needed.
Incorrect configuration of these values may result in intermittent
or persistent errors, or the Pages Daemon serving old content.
{{< alert type="note" >}}
Expiry, interval and timeout flags use [Go duration formatting](https://pkg.go.dev/time#ParseDuration).
A duration string is a possibly signed sequence of decimal numbers,
each with optional fraction and a unit suffix, such as `300ms`, `1.5h` or `2h45m`.
Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`.
{{< /alert >}}
Examples:
- Increasing `gitlab_cache_expiry` allows items to exist in the cache longer.
This setting might be useful if the communication between GitLab Pages and GitLab Rails
is not stable.
- Increasing `gitlab_cache_refresh` reduces the frequency at which GitLab Pages
requests a domain's configuration from GitLab Rails. This setting might be useful
GitLab Pages generates too many requests to GitLab API and content does not change frequently.
- Decreasing `gitlab_cache_cleanup` removes expired items from the cache more frequently,
reducing the memory usage of your Pages node.
- Decreasing `gitlab_retrieval_timeout` allows you to stop the request to GitLab Rails
more quickly. Increasing it allows more time to receive a response from the API,
useful in slow networking environments.
- Decreasing `gitlab_retrieval_interval` makes requests to the API more frequently,
only when there is an error response from the API, for example a connection timeout.
- Decreasing `gitlab_retrieval_retries` reduces the number of times a domain's
configuration is tried to be resolved automatically before reporting an error.
## Object storage settings
The following [object storage](../object_storage.md) settings are:
- Nested under `pages:` and then `object_store:` on self-compiled installations.
- Prefixed by `pages_object_store_` on Linux package installations.
| Setting | Description | Default |
|---------|-------------|---------|
| `enabled` | Whether object storage is enabled. | `false` |
| `remote_directory` | The name of the bucket where Pages site content is stored. | |
| `connection` | Various connection options described below. | |
{{< alert type="note" >}}
If you want to stop using and disconnect the NFS server, you need to
[explicitly disable local storage](#disable-pages-local-storage).
{{< /alert >}}
### S3-compatible connection settings
You should use the [consolidated object storage settings](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
See [the available connection settings for different providers](../object_storage.md#configure-the-connection-settings).
### Migrate Pages deployments to object storage
Existing Pages deployment objects (zip archives) can be stored in either:
- Local storage
- [Object storage](../object_storage.md)
Migrate your existing Pages deployments from local storage to object storage:
```shell
sudo gitlab-rake gitlab:pages:deployments:migrate_to_object_storage
```
You can track progress and verify that all Pages deployments migrated successfully using the
[PostgreSQL console](https://docs.gitlab.com/omnibus/settings/database.html#connecting-to-the-bundled-postgresql-database):
- `sudo gitlab-rails dbconsole --database main` for Linux package installations.
- `sudo -u git -H psql -d gitlabhq_production` for self-compiled installations.
Verify `objectstg` below (where `store=2`) has count of all Pages deployments:
```shell
gitlabhq_production=# SELECT count(*) AS total, sum(case when file_store = '1' then 1 else 0 end) AS filesystem, sum(case when file_store = '2' then 1 else 0 end) AS objectstg FROM pages_deployments;
total | filesystem | objectstg
------+------------+-----------
10 | 0 | 10
```
After verifying everything is working correctly,
[disable Pages local storage](#disable-pages-local-storage).
### Rolling Pages deployments back to local storage
After the migration to object storage is performed, you can choose to move your Pages deployments back to local storage:
```shell
sudo gitlab-rake gitlab:pages:deployments:migrate_to_local
```
### Disable Pages local storage
If you use [object storage](#object-storage-settings), you can disable local storage to avoid unnecessary disk usage/writes:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['pages_local_store_enabled'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Enable Pages network storage in multi-node environments
Object storage is the preferred configuration for most environments. However,
if your requirements call for network storage and you want to configure Pages
to run on a [separate server](#running-gitlab-pages-on-a-separate-server), you should:
1. Ensure the shared storage volume you intend to use is already mounted and
available on both the primary server and your intended Pages server.
1. Update the `/etc/gitlab/gitlab.rb` of each node to include:
```ruby
gitlab_pages['enable_disk'] = true
gitlab_rails['pages_path'] = "/var/opt/gitlab/gitlab-rails/shared/pages" # Path to your network storage
```
1. Switch over Pages to your separate server.
After you successfully configure Pages on your separate server, only that server
needs access to the shared storage volume. Consider keeping the shared storage volume
mounted on your primary server, in case you must migrate back to a single-node environment.
## ZIP storage
The underlying storage format of GitLab Pages is a single ZIP archive per project.
These ZIP archives can be stored either locally on disk storage or on [object storage](#object-storage-settings) if it is configured.
The ZIP archives are stored every time pages site is updated.
## Backup
GitLab Pages are part of the [regular backup](../backup_restore/_index.md), so there is no separate backup to configure.
## Security
You should strongly consider running GitLab Pages under a different hostname
than GitLab to prevent XSS attacks.
### Rate limits
{{< history >}}
- [Changed](https://gitlab.com/groups/gitlab-org/-/epics/14653) in GitLab 17.3: You can exclude subnets from Pages rate limits.
{{< /history >}}
You can enforce rate limits to help minimize the risk of a Denial of Service (DoS) attack. GitLab Pages
uses a [token bucket algorithm](https://en.wikipedia.org/wiki/Token_bucket) to enforce rate limiting. By default,
requests or TLS connections that exceed the specified limits are reported and rejected.
GitLab Pages supports the following types of rate limiting:
- Per `source_ip`. It limits how many requests or TLS connections are allowed from the single client IP address.
- Per `domain`. It limits how many requests or TLS connections are allowed per domain hosted on GitLab Pages. It can be a custom domain like `example.com`, or group domain like `group.gitlab.io`.
HTTP request-based rate limits are enforced using the following:
- `rate_limit_source_ip`: Sets the maximum threshold in number of requests per client IP per second. Set to 0 to disable this feature.
- `rate_limit_source_ip_burst`: Sets the maximum threshold of number of requests allowed in an initial outburst of requests per client IP.
For example, when you load a web page that loads multiple resources at the same time.
- `rate_limit_domain`: Sets the maximum threshold in number of requests per hosted pages domain per second. Set to 0 to disable this feature.
- `rate_limit_domain_burst`: Sets the maximum threshold of number of requests allowed in an initial outburst of requests per hosted pages domain.
TLS connection-based rate limits are enforced using the following:
- `rate_limit_tls_source_ip`: Sets the maximum threshold in number of TLS connections per client IP per second. Set to 0 to disable this feature.
- `rate_limit_tls_source_ip_burst`: Sets the maximum threshold of number of TLS connections allowed in an initial outburst of TLS connections per client IP.
For example, when you load a web page from different web browsers at the same time.
- `rate_limit_tls_domain`: Sets the maximum threshold in number of TLS connections per hosted pages domain per second. Set to 0 to disable this feature.
- `rate_limit_tls_domain_burst`: Sets the maximum threshold of number of TLS connections allowed in an initial outburst of TLS connections per hosted pages domain.
To allow certain IP ranges (subnets) to bypass all rate limits:
- `rate_limit_subnets_allow_list`: Sets the allow list with the IP ranges (subnets) that should bypass all rate limits.
For example, `['1.2.3.4/24', '2001:db8::1/32']`.
[Charts example](https://docs.gitlab.com/charts/charts/gitlab/gitlab-pages/#configure-rate-limits-subnets-allow-list) is available.
An IPv6 address receives a large prefix in the 128-bit address space. The prefix is typically at least size /64. Because of the large number of possible addresses, if the client's IP address is IPv6, the limit is applied to the IPv6 prefix with a length of 64, rather than the entire IPv6 address.
#### Enable HTTP requests rate limits by source-IP
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_source_ip'] = 20.0
gitlab_pages['rate_limit_source_ip_burst'] = 600
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable HTTP requests rate limits by domain
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_domain'] = 1000
gitlab_pages['rate_limit_domain_burst'] = 5000
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable TLS connections rate limits by source-IP
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_tls_source_ip'] = 20.0
gitlab_pages['rate_limit_tls_source_ip_burst'] = 600
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
#### Enable TLS connections rate limits by domain
1. Set rate limits in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['rate_limit_tls_domain'] = 1000
gitlab_pages['rate_limit_tls_domain_burst'] = 5000
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## Related topics
- [Troubleshooting GitLab Pages administration](troubleshooting.md)
|
https://docs.gitlab.com/administration/source
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/source.md
|
2025-08-13
|
doc/administration/pages
|
[
"doc",
"administration",
"pages"
] |
source.md
|
Plan
|
Knowledge
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Pages administration for self-compiled installations
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
Before attempting to enable GitLab Pages, first make sure you have
[installed GitLab](../../install/self_compiled/_index.md) successfully.
{{< /alert >}}
This document explains how to configure GitLab Pages for self-compiled GitLab installations.
For more information about configuring GitLab Pages for Linux Package installations (recommended), see the [Linux package documentation](_index.md).
The advantage of using the Linux package installation is that it contains the latest supported version of GitLab Pages.
## How GitLab Pages works
GitLab Pages makes use of the [GitLab Pages daemon](https://gitlab.com/gitlab-org/gitlab-pages), a lightweight HTTP server that listens on an external IP address and provides support for
custom domains and certificates. It supports dynamic certificates through
`SNI` and exposes pages using HTTP2 by default.
You are encouraged to read its [README](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/README.md)
to fully understand how it works.
In the case of [custom domains](#custom-domains) (but not
[wildcard domains](#wildcard-domains)), the Pages daemon needs to listen on
ports `80` and/or `443`. For that reason, there is some flexibility in the way
which you can set it up:
- Run the Pages daemon in the same server as GitLab, listening on a secondary
IP.
- Run the Pages daemon in a separate server. In that case, the
[Pages path](#change-storage-path) must also be present in the server that
the Pages daemon is installed, so you must share it through the network.
- Run the Pages daemon in the same server as GitLab, listening on the same IP
but on different ports. In that case, you must proxy the traffic with a load
balancer. If you choose that route, you should use TCP load balancing for
HTTPS. If you use TLS-termination (HTTPS-load balancing), the pages aren't
able to be served with user-provided certificates. For HTTP, you can use HTTP
or TCP load balancing.
In this document, we proceed assuming the first option. If you aren't
supporting custom domains, a secondary IP isn't needed.
## Prerequisites
Before proceeding with the Pages configuration, make sure that:
- You have a separate domain to serve GitLab Pages from. In this document we
assume that to be `example.io`.
- You have configured a **wildcard DNS record** for that domain.
- You have installed the `zip` and `unzip` packages in the same server that
GitLab is installed because they are needed to compress and decompress the
Pages artifacts.
- Optional. You have a **wildcard certificate** for the Pages domain if you
decide to serve Pages (`*.example.io`) under HTTPS.
- Optional but recommended. You have configured and enabled the [instance runners](../../ci/runners/_index.md)
so your users don't have to bring their own.
### DNS configuration
GitLab Pages expect to run on their own virtual host. In your DNS server/provider
you need to add a [wildcard DNS `A` record](https://en.wikipedia.org/wiki/Wildcard_DNS_record) pointing to the
host that GitLab runs. For example, an entry would look like this:
```plaintext
*.example.io. 1800 IN A 192.0.2.1
```
Where `example.io` is the domain to serve GitLab Pages from,
and `192.0.2.1` is the IP address of your GitLab instance.
{{< alert type="note" >}}
You should not use the GitLab domain to serve user pages. For more information
see the [security section](#security).
{{< /alert >}}
## Configuration
Depending on your needs, you can set up GitLab Pages in 4 different ways.
The following options are listed from the easiest setup to the most
advanced one. The absolute minimum requirement is to set up the wildcard DNS
because that is needed in all configurations.
### Wildcard domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
URL scheme: `http://<namespace>.example.io/<project_slug>`
This setup is the minimum you can use Pages with. It is the base for all
other setups as described below. NGINX proxies all requests to the daemon.
The Pages daemon doesn't listen to the outside world.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Go to the GitLab installation directory:
```shell
cd /home/git/gitlab
```
1. Edit `gitlab.yml` and under the `pages` setting, set `enabled` to `true` and
the `host` to the FQDN to serve GitLab Pages from:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
access_control: false
port: 8090
https: false
artifacts_server: false
external_http: ["127.0.0.1:8090"]
secret_file: /home/git/gitlab/gitlab-pages-secret
```
1. Add the following configuration file to
`/home/git/gitlab-pages/gitlab-pages.conf`, and be sure to change
`example.io` to the FQDN from which you want to serve GitLab Pages and
`gitlab.example.com` to the URL of your GitLab instance:
```ini
listen-http=:8090
pages-root=/home/git/gitlab/shared/pages
api-secret-key=/home/git/gitlab/gitlab-pages-secret
pages-domain=example.io
internal-gitlab-server=https://gitlab.example.com
```
You may use an `http` address, when running GitLab Pages and GitLab on the
same host. If you use `https` and use a self-signed certificate, be sure to
make your custom CA available to GitLab Pages. For example, you can do this
by setting the `SSL_CERT_DIR` environment variable.
1. Add the secret API key:
```shell
sudo -u git -H openssl rand -base64 32 > /home/git/gitlab/gitlab-pages-secret
```
1. To enable the pages daemon:
- If your system uses systemd as init, run:
```shell
sudo systemctl edit gitlab.target
```
In the editor that opens, add the following and save the file:
```plaintext
[Unit]
Wants=gitlab-pages.service
```
- If your system uses SysV init instead, edit `/etc/default/gitlab` and set
`gitlab_pages_enabled` to `true`:
```ini
gitlab_pages_enabled=true
```
1. Copy the `gitlab-pages` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages /etc/nginx/sites-available/gitlab-pages.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages.conf
```
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
### Wildcard domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Wildcard TLS certificate
URL scheme: `https://<namespace>.example.io/<project_slug>`
NGINX proxies all requests to the daemon. Pages daemon doesn't listen to the
outside world.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. In `gitlab.yml`, set the port to `443` and https to `true`:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 443
https: true
```
1. Edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true` in
order to enable the pages daemon. In `gitlab_pages_options` the
`-pages-domain` must match the `host` value that you set previously.
The `-root-cert` and `-root-key` settings are the wildcard TLS certificates
of the `example.io` domain:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -root-cert /path/to/example.io.crt -root-key /path/to/example.io.key"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages-ssl /etc/nginx/sites-available/gitlab-pages-ssl.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages-ssl.conf
```
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## Advanced configuration
In addition to the wildcard domains, you can also have the option to configure
GitLab Pages to work with custom domains. Again, there are two options here:
support custom domains with and without TLS certificates. The easiest setup is
that without TLS certificates.
### Custom domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Secondary IP
URL scheme: `http://<namespace>.example.io/<project_slug>` and `http://custom-domain.com`
In that case, the pages daemon is running. NGINX still proxies requests to
the daemon, but the daemon is also able to receive requests from the outside
world. Custom domains are supported, but no TLS.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Edit `gitlab.yml` to look like the example below. You need to change the
`host` to the FQDN to serve GitLab Pages from. Set
`external_http` to the secondary IP on which the pages daemon listens
for connections:
```yaml
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 80
https: false
external_http: 192.0.2.2:80
```
1. To enable the daemon, edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true`.
In `gitlab_pages_options`, the value for `-pages-domain` must match the `host` and `-listen-http` must match
the `external_http`:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -listen-http 192.0.2.2:80"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages /etc/nginx/sites-available/gitlab-pages.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages.conf
```
1. Edit all GitLab related configurations in `/etc/nginx/site-available/` and replace
`0.0.0.0` with `192.0.2.1`, where `192.0.2.1` the primary IP where GitLab
listens to.
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
### Custom domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Wildcard TLS certificate
- Secondary IP
URL scheme: `https://<namespace>.example.io/<project_slug>` and `https://custom-domain.com`
In that case, the pages daemon is running. NGINX still proxies requests to
the daemon, but the daemon is also able to receive requests from the outside
world. Custom domains and TLS are supported.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Edit `gitlab.yml` to look like the example below. You need to change the
`host` to the FQDN to serve GitLab Pages from. Set
`external_http` and `external_https` to the secondary IP on which the pages
daemon listens for connections:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 443
https: true
external_http: 192.0.2.2:80
external_https: 192.0.2.2:443
```
1. Edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true` in
order to enable the pages daemon. In `gitlab_pages_options`, you must match the
`-pages-domain` with `host`, `-listen-http` with `external_http`, and `-listen-https` with `external_https` settings.
The `-root-cert` and `-root-key` settings are the wildcard TLS certificates
of the `example.io` domain:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -listen-http 192.0.2.2:80 -listen-https 192.0.2.2:443 -root-cert /path/to/example.io.crt -root-key /path/to/example.io.key"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages-ssl /etc/nginx/sites-available/gitlab-pages-ssl.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages-ssl.conf
```
1. Edit all GitLab related configurations in `/etc/nginx/site-available/` and replace
`0.0.0.0` with `192.0.2.1`, where `192.0.2.1` the primary IP where GitLab
listens to.
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## NGINX caveats
{{< alert type="note" >}}
The following information applies only to self-compiled installations.
{{< /alert >}}
Be extra careful when setting up the domain name in the NGINX configuration. You must
not remove the backslashes.
If your GitLab Pages domain is `example.io`, replace:
```nginx
server_name ~^.*\.YOUR_GITLAB_PAGES\.DOMAIN$;
```
with:
```nginx
server_name ~^.*\.example\.io$;
```
If you are using a subdomain, make sure to escape all dots (`.`) except from
the first one with a backslash (\). For example `pages.example.io` would be:
```nginx
server_name ~^.*\.pages\.example\.io$;
```
## Access control
GitLab Pages access control can be configured per project. Access to a Pages
site can be controlled based on a user's membership to that project.
Access control works by registering the Pages daemon as an OAuth application
with GitLab. Whenever a request to access a private Pages site is made by an
unauthenticated user, the Pages daemon redirects the user to GitLab. If
authentication is successful, the user is redirected back to Pages with a token,
which is persisted in a cookie. The cookies are signed with a secret key, so
tampering can be detected.
Each request to view a resource in a private site is authenticated by Pages
using that token. For each request it receives, it makes a request to the GitLab
API to check that the user is authorized to read that site.
Access Control parameters for Pages are set in a configuration file, which
by convention is named `gitlab-pages-config`. The configuration file is passed to
pages using the `-config flag` or `CONFIG` environment variable.
Pages access control is disabled by default. To enable it:
1. Modify your `config/gitlab.yml` file:
```yaml
pages:
access_control: true
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
1. Create a new [system OAuth application](../../integration/oauth_provider.md#create-a-user-owned-application).
This should be called `GitLab Pages` and have a `Redirect URL` of
`https://projects.example.io/auth`. It does not need to be a "trusted"
application, but it does need the `api` scope.
1. Start the Pages daemon by passing a configuration file with the following arguments:
```shell
auth-client-id=<OAuth Application ID generated by GitLab>
auth-client-secret=<OAuth code generated by GitLab>
auth-redirect-uri='http://projects.example.io/auth'
auth-secret=<40 random hex characters>
auth-server=<URL of the GitLab instance>
```
1. Users can now configure it in their [projects' settings](../../user/project/pages/pages_access_control.md).
## Change storage path
Follow the steps below to change the default path where GitLab Pages' contents
are stored.
1. Pages are stored by default in `/home/git/gitlab/shared/pages`.
If you wish to store them in another location you must set it up in
`gitlab.yml` under the `pages` section:
```yaml
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
path: /mnt/storage/pages
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## Set maximum Pages size
The default for the maximum size of unpacked archives per project is 100 MB.
To change this value:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Update the value for **Maximum size of pages (MB)**.
## Backup
Pages are part of the [regular backup](../backup_restore/_index.md) so there is nothing to configure.
## Security
You should strongly consider running GitLab Pages under a different hostname
than GitLab to prevent XSS attacks.
|
---
stage: Plan
group: Knowledge
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab Pages administration for self-compiled installations
breadcrumbs:
- doc
- administration
- pages
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
Before attempting to enable GitLab Pages, first make sure you have
[installed GitLab](../../install/self_compiled/_index.md) successfully.
{{< /alert >}}
This document explains how to configure GitLab Pages for self-compiled GitLab installations.
For more information about configuring GitLab Pages for Linux Package installations (recommended), see the [Linux package documentation](_index.md).
The advantage of using the Linux package installation is that it contains the latest supported version of GitLab Pages.
## How GitLab Pages works
GitLab Pages makes use of the [GitLab Pages daemon](https://gitlab.com/gitlab-org/gitlab-pages), a lightweight HTTP server that listens on an external IP address and provides support for
custom domains and certificates. It supports dynamic certificates through
`SNI` and exposes pages using HTTP2 by default.
You are encouraged to read its [README](https://gitlab.com/gitlab-org/gitlab-pages/blob/master/README.md)
to fully understand how it works.
In the case of [custom domains](#custom-domains) (but not
[wildcard domains](#wildcard-domains)), the Pages daemon needs to listen on
ports `80` and/or `443`. For that reason, there is some flexibility in the way
which you can set it up:
- Run the Pages daemon in the same server as GitLab, listening on a secondary
IP.
- Run the Pages daemon in a separate server. In that case, the
[Pages path](#change-storage-path) must also be present in the server that
the Pages daemon is installed, so you must share it through the network.
- Run the Pages daemon in the same server as GitLab, listening on the same IP
but on different ports. In that case, you must proxy the traffic with a load
balancer. If you choose that route, you should use TCP load balancing for
HTTPS. If you use TLS-termination (HTTPS-load balancing), the pages aren't
able to be served with user-provided certificates. For HTTP, you can use HTTP
or TCP load balancing.
In this document, we proceed assuming the first option. If you aren't
supporting custom domains, a secondary IP isn't needed.
## Prerequisites
Before proceeding with the Pages configuration, make sure that:
- You have a separate domain to serve GitLab Pages from. In this document we
assume that to be `example.io`.
- You have configured a **wildcard DNS record** for that domain.
- You have installed the `zip` and `unzip` packages in the same server that
GitLab is installed because they are needed to compress and decompress the
Pages artifacts.
- Optional. You have a **wildcard certificate** for the Pages domain if you
decide to serve Pages (`*.example.io`) under HTTPS.
- Optional but recommended. You have configured and enabled the [instance runners](../../ci/runners/_index.md)
so your users don't have to bring their own.
### DNS configuration
GitLab Pages expect to run on their own virtual host. In your DNS server/provider
you need to add a [wildcard DNS `A` record](https://en.wikipedia.org/wiki/Wildcard_DNS_record) pointing to the
host that GitLab runs. For example, an entry would look like this:
```plaintext
*.example.io. 1800 IN A 192.0.2.1
```
Where `example.io` is the domain to serve GitLab Pages from,
and `192.0.2.1` is the IP address of your GitLab instance.
{{< alert type="note" >}}
You should not use the GitLab domain to serve user pages. For more information
see the [security section](#security).
{{< /alert >}}
## Configuration
Depending on your needs, you can set up GitLab Pages in 4 different ways.
The following options are listed from the easiest setup to the most
advanced one. The absolute minimum requirement is to set up the wildcard DNS
because that is needed in all configurations.
### Wildcard domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
URL scheme: `http://<namespace>.example.io/<project_slug>`
This setup is the minimum you can use Pages with. It is the base for all
other setups as described below. NGINX proxies all requests to the daemon.
The Pages daemon doesn't listen to the outside world.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Go to the GitLab installation directory:
```shell
cd /home/git/gitlab
```
1. Edit `gitlab.yml` and under the `pages` setting, set `enabled` to `true` and
the `host` to the FQDN to serve GitLab Pages from:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
access_control: false
port: 8090
https: false
artifacts_server: false
external_http: ["127.0.0.1:8090"]
secret_file: /home/git/gitlab/gitlab-pages-secret
```
1. Add the following configuration file to
`/home/git/gitlab-pages/gitlab-pages.conf`, and be sure to change
`example.io` to the FQDN from which you want to serve GitLab Pages and
`gitlab.example.com` to the URL of your GitLab instance:
```ini
listen-http=:8090
pages-root=/home/git/gitlab/shared/pages
api-secret-key=/home/git/gitlab/gitlab-pages-secret
pages-domain=example.io
internal-gitlab-server=https://gitlab.example.com
```
You may use an `http` address, when running GitLab Pages and GitLab on the
same host. If you use `https` and use a self-signed certificate, be sure to
make your custom CA available to GitLab Pages. For example, you can do this
by setting the `SSL_CERT_DIR` environment variable.
1. Add the secret API key:
```shell
sudo -u git -H openssl rand -base64 32 > /home/git/gitlab/gitlab-pages-secret
```
1. To enable the pages daemon:
- If your system uses systemd as init, run:
```shell
sudo systemctl edit gitlab.target
```
In the editor that opens, add the following and save the file:
```plaintext
[Unit]
Wants=gitlab-pages.service
```
- If your system uses SysV init instead, edit `/etc/default/gitlab` and set
`gitlab_pages_enabled` to `true`:
```ini
gitlab_pages_enabled=true
```
1. Copy the `gitlab-pages` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages /etc/nginx/sites-available/gitlab-pages.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages.conf
```
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
### Wildcard domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Wildcard TLS certificate
URL scheme: `https://<namespace>.example.io/<project_slug>`
NGINX proxies all requests to the daemon. Pages daemon doesn't listen to the
outside world.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. In `gitlab.yml`, set the port to `443` and https to `true`:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 443
https: true
```
1. Edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true` in
order to enable the pages daemon. In `gitlab_pages_options` the
`-pages-domain` must match the `host` value that you set previously.
The `-root-cert` and `-root-key` settings are the wildcard TLS certificates
of the `example.io` domain:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -root-cert /path/to/example.io.crt -root-key /path/to/example.io.key"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages-ssl /etc/nginx/sites-available/gitlab-pages-ssl.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages-ssl.conf
```
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## Advanced configuration
In addition to the wildcard domains, you can also have the option to configure
GitLab Pages to work with custom domains. Again, there are two options here:
support custom domains with and without TLS certificates. The easiest setup is
that without TLS certificates.
### Custom domains
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Secondary IP
URL scheme: `http://<namespace>.example.io/<project_slug>` and `http://custom-domain.com`
In that case, the pages daemon is running. NGINX still proxies requests to
the daemon, but the daemon is also able to receive requests from the outside
world. Custom domains are supported, but no TLS.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Edit `gitlab.yml` to look like the example below. You need to change the
`host` to the FQDN to serve GitLab Pages from. Set
`external_http` to the secondary IP on which the pages daemon listens
for connections:
```yaml
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 80
https: false
external_http: 192.0.2.2:80
```
1. To enable the daemon, edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true`.
In `gitlab_pages_options`, the value for `-pages-domain` must match the `host` and `-listen-http` must match
the `external_http`:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -listen-http 192.0.2.2:80"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages /etc/nginx/sites-available/gitlab-pages.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages.conf
```
1. Edit all GitLab related configurations in `/etc/nginx/site-available/` and replace
`0.0.0.0` with `192.0.2.1`, where `192.0.2.1` the primary IP where GitLab
listens to.
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
### Custom domains with TLS support
Prerequisites:
- [Wildcard DNS setup](#dns-configuration)
- Wildcard TLS certificate
- Secondary IP
URL scheme: `https://<namespace>.example.io/<project_slug>` and `https://custom-domain.com`
In that case, the pages daemon is running. NGINX still proxies requests to
the daemon, but the daemon is also able to receive requests from the outside
world. Custom domains and TLS are supported.
1. Install the Pages daemon:
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
1. Edit `gitlab.yml` to look like the example below. You need to change the
`host` to the FQDN to serve GitLab Pages from. Set
`external_http` and `external_https` to the secondary IP on which the pages
daemon listens for connections:
```yaml
## GitLab Pages
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
# path: shared/pages
host: example.io
port: 443
https: true
external_http: 192.0.2.2:80
external_https: 192.0.2.2:443
```
1. Edit `/etc/default/gitlab` and set `gitlab_pages_enabled` to `true` in
order to enable the pages daemon. In `gitlab_pages_options`, you must match the
`-pages-domain` with `host`, `-listen-http` with `external_http`, and `-listen-https` with `external_https` settings.
The `-root-cert` and `-root-key` settings are the wildcard TLS certificates
of the `example.io` domain:
```ini
gitlab_pages_enabled=true
gitlab_pages_options="-pages-domain example.io -pages-root $app_root/shared/pages -listen-proxy 127.0.0.1:8090 -listen-http 192.0.2.2:80 -listen-https 192.0.2.2:443 -root-cert /path/to/example.io.crt -root-key /path/to/example.io.key"
```
1. Copy the `gitlab-pages-ssl` NGINX configuration file:
```shell
sudo cp lib/support/nginx/gitlab-pages-ssl /etc/nginx/sites-available/gitlab-pages-ssl.conf
sudo ln -sf /etc/nginx/sites-{available,enabled}/gitlab-pages-ssl.conf
```
1. Edit all GitLab related configurations in `/etc/nginx/site-available/` and replace
`0.0.0.0` with `192.0.2.1`, where `192.0.2.1` the primary IP where GitLab
listens to.
1. Restart NGINX.
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## NGINX caveats
{{< alert type="note" >}}
The following information applies only to self-compiled installations.
{{< /alert >}}
Be extra careful when setting up the domain name in the NGINX configuration. You must
not remove the backslashes.
If your GitLab Pages domain is `example.io`, replace:
```nginx
server_name ~^.*\.YOUR_GITLAB_PAGES\.DOMAIN$;
```
with:
```nginx
server_name ~^.*\.example\.io$;
```
If you are using a subdomain, make sure to escape all dots (`.`) except from
the first one with a backslash (\). For example `pages.example.io` would be:
```nginx
server_name ~^.*\.pages\.example\.io$;
```
## Access control
GitLab Pages access control can be configured per project. Access to a Pages
site can be controlled based on a user's membership to that project.
Access control works by registering the Pages daemon as an OAuth application
with GitLab. Whenever a request to access a private Pages site is made by an
unauthenticated user, the Pages daemon redirects the user to GitLab. If
authentication is successful, the user is redirected back to Pages with a token,
which is persisted in a cookie. The cookies are signed with a secret key, so
tampering can be detected.
Each request to view a resource in a private site is authenticated by Pages
using that token. For each request it receives, it makes a request to the GitLab
API to check that the user is authorized to read that site.
Access Control parameters for Pages are set in a configuration file, which
by convention is named `gitlab-pages-config`. The configuration file is passed to
pages using the `-config flag` or `CONFIG` environment variable.
Pages access control is disabled by default. To enable it:
1. Modify your `config/gitlab.yml` file:
```yaml
pages:
access_control: true
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
1. Create a new [system OAuth application](../../integration/oauth_provider.md#create-a-user-owned-application).
This should be called `GitLab Pages` and have a `Redirect URL` of
`https://projects.example.io/auth`. It does not need to be a "trusted"
application, but it does need the `api` scope.
1. Start the Pages daemon by passing a configuration file with the following arguments:
```shell
auth-client-id=<OAuth Application ID generated by GitLab>
auth-client-secret=<OAuth code generated by GitLab>
auth-redirect-uri='http://projects.example.io/auth'
auth-secret=<40 random hex characters>
auth-server=<URL of the GitLab instance>
```
1. Users can now configure it in their [projects' settings](../../user/project/pages/pages_access_control.md).
## Change storage path
Follow the steps below to change the default path where GitLab Pages' contents
are stored.
1. Pages are stored by default in `/home/git/gitlab/shared/pages`.
If you wish to store them in another location you must set it up in
`gitlab.yml` under the `pages` section:
```yaml
pages:
enabled: true
# The location where pages are stored (default: shared/pages).
path: /mnt/storage/pages
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations).
## Set maximum Pages size
The default for the maximum size of unpacked archives per project is 100 MB.
To change this value:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Preferences**.
1. Expand **Pages**.
1. Update the value for **Maximum size of pages (MB)**.
## Backup
Pages are part of the [regular backup](../backup_restore/_index.md) so there is nothing to configure.
## Security
You should strongly consider running GitLab Pages under a different hostname
than GitLab to prevent XSS attacks.
|
https://docs.gitlab.com/administration/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/troubleshooting.md
|
2025-08-13
|
doc/administration/pages
|
[
"doc",
"administration",
"pages"
] |
troubleshooting.md
|
Plan
|
Knowledge
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting GitLab Pages administration
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page contains a list of issues you might encounter when administering GitLab Pages.
## How to see GitLab Pages logs
You can see Pages daemon logs by running:
```shell
sudo gitlab-ctl tail gitlab-pages
```
You can also find the log file in `/var/log/gitlab/gitlab-pages/current`.
For more information, see [Getting the correlation ID from your logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
## Debug GitLab Pages
The following sequence diagram illustrates how GitLab Pages requests are served.
For more information on how a GitLab Pages site is deployed and serves static content from Object Storage,
see the GitLab Pages Architecture documentation.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: GitLab Pages Request Flow
accDescr: Sequence diagram showing how a user request flows through GitLab Pages components to serve static files.
actor User
participant PagesNGINX as Pages NGINX
participant Pages as GitLab Pages
participant GitlabNGINX as GitLab NGINX
participant GitlabAPI as GitLab Rails
participant ObjectStorage as Object Storage
User->>PagesNGINX: Request to Pages
activate PagesNGINX
PagesNGINX->>Pages: Forwarded to Pages
activate Pages
Pages->>GitlabNGINX: Fetch domain info
activate GitlabNGINX
GitlabNGINX->>GitlabAPI: Forwarded to GitLab API
activate GitlabAPI
GitlabAPI->>GitlabNGINX: 200 OK (domain info)
deactivate GitlabAPI
GitlabNGINX->>Pages: 200 OK (domain info)
deactivate GitlabNGINX
Note right of Pages: Domain information cached in Pages
Pages->>ObjectStorage: Fetch static files
activate ObjectStorage
ObjectStorage->>Pages: 200 OK (files)
deactivate ObjectStorage
Pages->>User: 200 OK (static files served)
deactivate Pages
deactivate PagesNGINX
```
### Identify error logs
You should check logs in the order shown in the previous sequence diagram.
Filtering based on your domain can also help identify relevant logs.
To start tailing the logs:
1. For **GitLab Pages NGINX** logs, run:
```shell
# View GitLab Pages NGINX error logs
sudo gitlab-ctl tail nginx/gitlab_pages_error.log
# View GitLab Pages NGINX access logs
sudo gitlab-ctl tail nginx/gitlab_pages_access.log
```
1. For **GitLab Pages** logs, run: Start by identifying the [correlation ID from your logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
```shell
sudo gitlab-ctl tail gitlab-pages
```
1. For **GitLab NGINX** logs, run:
```shell
# View GitLab NGINX error logs
sudo gitlab-ctl tail nginx/gitlab_error.log
# View GitLab NGINX access logs
sudo gitlab-ctl tail nginx/gitlab_access.log
```
1. For **GitLab Rails** logs, run:
You can filter these logs based on the `correlation_id` [identified in GitLab Pages logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
```shell
sudo gitlab-ctl tail gitlab-rails
```
## Authorization code flow
The following sequence chart illustrates the OAuth authentication flow between the user, GitLab Pages,
and GitLab Rails for accessing protected Pages sites.
For more information, see
[GitLab OAuth authorization code flow](../../api/oauth2.md#authorization-code-flow).
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: GitLab Pages OAuth Flow
accDescr: Sequence diagram showing the OAuth authentication flow between User, GitLab Pages, and GitLab Rails for accessing protected pages sites.
actor User
participant PagesService as GitLab Pages
participant GitlabApp as GitLab Rails
User->>PagesService: GET Request for site
activate PagesService
PagesService-->>User: 302 Redirect to project subdomain https://projects.gitlab.io/auth?state=state1
deactivate PagesService
Note left of User: Cookie state1
User->>PagesService: GET https://projects.gitlab.io/auth?state=state1
activate PagesService
PagesService-->>User: 302 Redirect to gitlab.com/oauth/authorize?state=state1
deactivate PagesService
User->>GitlabApp: GET oauth/authorize?state=state1
activate GitlabApp
GitlabApp-->>User: 200 OK (authorization form)
deactivate GitlabApp
User->>GitlabApp: POST authorization form
activate GitlabApp
GitlabApp-->>User: 302 Redirect to oauth/redirect
deactivate GitlabApp
User->>GitlabApp: GET oauth/redirect?state=state1
activate GitlabApp
GitlabApp-->>User: 200 OK (with auth code)
deactivate GitlabApp
User->>PagesService: GET https://projects.gitlab.io/auth?code=code1&state=state1
activate PagesService
PagesService->>GitlabApp: POST oauth/token with code=code1
activate GitlabApp
GitlabApp-->>PagesService: 200 OK (access token)
deactivate GitlabApp
PagesService-->>User: 302 Redirect to https://[namespace].gitlab.io/auth?code=code2&state=state1
deactivate PagesService
User->>PagesService: GET https://[namespace].gitlab.io/auth?code=code2&state=state1
activate PagesService
PagesService-->>User: 302 Redirect to site
deactivate PagesService
User->>PagesService: GET Request for site
activate PagesService
PagesService-->>User: 200 OK (site content)
deactivate PagesService
```
## `unsupported protocol scheme \"\""`
If you see the following error:
```plaintext
{"error":"failed to connect to internal Pages API: Get \"/api/v4/internal/pages/status\": unsupported protocol scheme \"\"","level":"warning","msg":"attempted to connect to the API","time":"2021-06-23T20:03:30Z"}
```
It means you didn't set the HTTP(S) protocol scheme in the Pages server settings.
To fix it:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['gitlab_server'] = "https://<your_gitlab_server_public_host_and_port>"
gitlab_pages['internal_gitlab_server'] = "https://<your_gitlab_server_private_host_and_port>" # optional, gitlab_pages['gitlab_server'] is used as default
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## 502 error when connecting to GitLab Pages proxy when server does not listen over IPv6
In some cases, NGINX might default to using IPv6 to connect to the GitLab Pages
service even when the server does not listen over IPv6. You can identify when
this is happening if you see something similar to the log entry below in the
`gitlab_pages_error.log`:
```plaintext
2020/02/24 16:32:05 [error] 112654#0: *4982804 connect() failed (111: Connection refused) while connecting to upstream, client: 123.123.123.123, server: ~^(?<group>.*)\.pages\.example\.com$, request: "GET /-/group/project/-/jobs/1234/artifacts/artifact.txt HTTP/1.1", upstream: "http://[::1]:8090//-/group/project/-/jobs/1234/artifacts/artifact.txt", host: "group.example.com"
```
To resolve this, set an explicit IP and port for the GitLab Pages `listen_proxy` setting
to define the explicit address that the GitLab Pages daemon should listen on:
```ruby
gitlab_pages['listen_proxy'] = '127.0.0.1:8090'
```
## Intermittent 502 errors or after a few days
If you run Pages on a system that uses `systemd` and
[`tmpfiles.d`](https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html),
you may encounter intermittent 502 errors trying to serve Pages with an error similar to:
```plaintext
dial tcp: lookup gitlab.example.com on [::1]:53: dial udp [::1]:53: connect: no route to host"
```
GitLab Pages creates a [bind mount](https://man7.org/linux/man-pages/man8/mount.8.html)
inside `/tmp/gitlab-pages-*` that includes files like `/etc/hosts`.
However, `systemd` may clean the `/tmp/` directory on a regular basis so the DNS
configuration may be lost.
To stop `systemd` from cleaning the Pages related content:
1. Tell `tmpfiles.d` to not remove the Pages `/tmp` directory:
```shell
echo 'x /tmp/gitlab-pages-*' >> /etc/tmpfiles.d/gitlab-pages-jail.conf
```
1. Restart GitLab Pages:
```shell
sudo gitlab-ctl restart gitlab-pages
```
## Unable to access GitLab Pages
If you can't access your GitLab Pages (such as receiving `502 Bad Gateway` errors, or a login loop)
and in your Pages log shows this error:
```plaintext
"error":"retrieval context done: context deadline exceeded","host":"root.docs-cit.otenet.gr","level":"error","msg":"could not fetch domain information from a source"
```
1. Add the following to `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['internal_gitlab_server'] = 'http://localhost:8080'
```
1. Restart GitLab Pages:
```shell
sudo gitlab-ctl restart gitlab-pages
```
## Failed to connect to the internal GitLab API
If you see the following error:
```plaintext
ERRO[0010] Failed to connect to the internal GitLab API after 0.50s error="failed to connect to internal Pages API: HTTP status: 401"
```
If you are [Running GitLab Pages on a separate server](_index.md#running-gitlab-pages-on-a-separate-server)
you must copy the `/etc/gitlab/gitlab-secrets.json` file
from the **GitLab server** to the **Pages server**.
Other reasons may include network connectivity issues between your
**GitLab server** and your **Pages server** such as firewall configurations or closed ports.
For example, if there is a connection timeout:
```plaintext
error="failed to connect to internal Pages API: Get \"https://gitlab.example.com:3000/api/v4/internal/pages/status\": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)"
```
## Pages cannot communicate with an instance of the GitLab API
If you use the default value for `domain_config_source=auto` and run multiple instances of GitLab
Pages, you may see intermittent 502 error responses while serving Pages content. You may also see
the following warning in the Pages logs:
```plaintext
WARN[0010] Pages cannot communicate with an instance of the GitLab API. Please sync your gitlab-secrets.json file https://gitlab.com/gitlab-org/gitlab-pages/-/issues/535#workaround. error="pages endpoint unauthorized"
```
This can happen if your `gitlab-secrets.json` file is out of date between GitLab Rails and GitLab
Pages. Follow steps 8-10 of [Running GitLab Pages on a separate server](_index.md#running-gitlab-pages-on-a-separate-server),
in all of your GitLab Pages instances.
## Intermittent 502 errors when using an AWS Network Load Balancer and GitLab Pages
Connections will time out when using a Network Load Balancer with client IP preservation enabled and [the request is looped back to the source server](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-troubleshooting.html#loopback-timeout).
This can happen to GitLab instances with multiple servers
running both the core GitLab application and GitLab Pages. This can also happen when a single
container is running both the core GitLab application and GitLab Pages.
AWS [recommends using an IP target type](https://repost.aws/knowledge-center/target-connection-fails-load-balancer)
to resolve this issue.
Turning off [client IP preservation](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#client-ip-preservation)
may resolve this issue when the core GitLab application and GitLab Pages run on the same host or
container.
## 500 error with `securecookie: failed to generate random iv` and `Failed to save the session`
This problem most likely results from an out-dated operating system.
The [Pages daemon uses the `securecookie` library](https://gitlab.com/search?group_id=9970&project_id=734943&repository_ref=master&scope=blobs&search=securecookie&snippets=false) to get random strings via [`crypto/rand` in Go](https://pkg.go.dev/crypto/rand#pkg-variables).
This requires the `getrandom` system call or `/dev/urandom` to be available on the host OS.
Upgrading to an [officially supported operating system](../../install/package/_index.md#supported-platforms) is recommended.
## The requested scope is invalid, malformed, or unknown
This problem comes from the permissions of the GitLab Pages OAuth application. To fix it:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications > GitLab Pages**.
1. Edit the application.
1. Under **Scopes**, ensure that the `api` scope is selected.
1. Save your changes.
When running a [separate Pages server](_index.md#running-gitlab-pages-on-a-separate-server),
this setting needs to be configured on the main GitLab server.
## Workaround in case no wildcard DNS entry can be set
If the wildcard DNS [prerequisite](_index.md#prerequisites) can't be met, you can still use GitLab Pages in a limited fashion:
1. [Move](../../user/project/working_with_projects.md#transfer-a-project)
all projects you need to use Pages with into a single group namespace, for example `pages`.
1. Configure a [DNS entry](_index.md#dns-configuration) without the `*.`-wildcard, for example `pages.example.io`.
1. Configure `pages_external_url http://example.io/` in your `gitlab.rb` file.
Omit the group namespace here, because it automatically is prepended by GitLab.
## Pages daemon fails with permission denied errors
If `/tmp` is mounted with `noexec`, the Pages daemon fails to start with an error like:
```plaintext
{"error":"fork/exec /gitlab-pages: permission denied","level":"fatal","msg":"could not create pages daemon","time":"2021-02-02T21:54:34Z"}
```
In this case, change `TMPDIR` to a location that is not mounted with `noexec`. Add the following to
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env'] = {'TMPDIR' => '<new_tmp_path>'}
```
Once added, reconfigure with `sudo gitlab-ctl reconfigure` and restart GitLab with
`sudo gitlab-ctl restart`.
## `The redirect URI included is not valid.` when using Pages Access Control
You may see this error if `pages_external_url` was updated at some point of time. Verify the following:
1. Check the [System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application):
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications** and then **Add new application**.
1. Ensure the **Callback URL/Redirect URI** is using the protocol (HTTP or HTTPS) that
`pages_external_url` is configured to use.
1. The domain and path components of `Redirect URI` are valid: they should look like `projects.<pages_external_url>/auth`.
## 500 error `cannot serve from disk`
If you get a 500 response from Pages and encounter an error similar to:
```plaintext
ERRO[0145] cannot serve from disk error="gitlab: disk access is disabled via enable-disk=false" project_id=27 source_path="file:///shared/pages/@hashed/67/06/670671cd97404156226e507973f2ab8330d3022ca96e0c93bdbdb320c41adcaf/pages_deployments/14/artifacts.zip" source_type=zip
```
It means that GitLab Rails is telling GitLab Pages to serve content from a location on disk,
however, GitLab Pages was configured to disable disk access.
To enable disk access:
1. Enable disk access for GitLab Pages in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['enable_disk'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## `httprange: new resource 403`
If you see an error similar to:
```plaintext
{"error":"httprange: new resource 403: \"403 Forbidden\"","host":"root.pages.example.com","level":"error","msg":"vfs.Root","path":"/pages1/","time":"2021-06-10T08:45:19Z"}
```
And you run pages on the separate server syncing files via NFS, it may mean that
the shared pages directory is mounted on a different path on the main GitLab server and the
GitLab Pages server.
In that case, it's highly recommended you to configure
[object storage and migrate any existing pages data to it](_index.md#object-storage-settings).
Alternatively, you can mount the GitLab Pages shared directory to the same path on
both servers.
## GitLab Pages deploy job fails with error "is not a recognized provider"
If the **pages** job succeeds but the **deploy** job gives the error "is not a recognized provider":

The error message `is not a recognized provider` could be coming from the `fog` gem that GitLab uses to connect to cloud providers for object storage.
To fix that:
1. Check your `gitlab.rb` file. If you have `gitlab_rails['pages_object_store_enabled']` enabled, but no bucket details have been configured, either:
- Configure object storage for your Pages deployments, following the [S3-compatible connection settings](_index.md#s3-compatible-connection-settings) guide.
- Store your deployments locally, by commenting out that line.
1. Save the changes you made to your `gitlab.rb` file, then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## 404 error `The page you're looking for could not be found`
If you get a `404 Page Not Found` response from GitLab Pages:
1. Check `.gitlab-ci.yml` contains the job `pages:`.
1. Check the current project's pipeline to confirm the job `pages:deploy` is being run.
Without the `pages:deploy` job, the updates to your GitLab Pages site are never published.
## 503 error `Client authentication failed due to unknown client`
If Pages is a registered OAuth application and [access control is enabled](../../user/project/pages/pages_access_control.md), this error indicates that the authentication token stored in `/etc/gitlab/gitlab-secrets.json` has become invalid:
```plaintext
Client authentication failed due to unknown client, no client authentication included,
or unsupported authentication method.
```
To resolve:
1. Back up your secrets file:
```shell
sudo cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.$(date +\%Y\%m\%d)
```
1. Edit `/etc/gitlab/gitlab-secrets.json` and remove the `gitlab_pages` section.
1. Reconfigure GitLab and regenerate the OAuth token:
```shell
sudo gitlab-ctl reconfigure
```
|
---
stage: Plan
group: Knowledge
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting GitLab Pages administration
breadcrumbs:
- doc
- administration
- pages
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page contains a list of issues you might encounter when administering GitLab Pages.
## How to see GitLab Pages logs
You can see Pages daemon logs by running:
```shell
sudo gitlab-ctl tail gitlab-pages
```
You can also find the log file in `/var/log/gitlab/gitlab-pages/current`.
For more information, see [Getting the correlation ID from your logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
## Debug GitLab Pages
The following sequence diagram illustrates how GitLab Pages requests are served.
For more information on how a GitLab Pages site is deployed and serves static content from Object Storage,
see the GitLab Pages Architecture documentation.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: GitLab Pages Request Flow
accDescr: Sequence diagram showing how a user request flows through GitLab Pages components to serve static files.
actor User
participant PagesNGINX as Pages NGINX
participant Pages as GitLab Pages
participant GitlabNGINX as GitLab NGINX
participant GitlabAPI as GitLab Rails
participant ObjectStorage as Object Storage
User->>PagesNGINX: Request to Pages
activate PagesNGINX
PagesNGINX->>Pages: Forwarded to Pages
activate Pages
Pages->>GitlabNGINX: Fetch domain info
activate GitlabNGINX
GitlabNGINX->>GitlabAPI: Forwarded to GitLab API
activate GitlabAPI
GitlabAPI->>GitlabNGINX: 200 OK (domain info)
deactivate GitlabAPI
GitlabNGINX->>Pages: 200 OK (domain info)
deactivate GitlabNGINX
Note right of Pages: Domain information cached in Pages
Pages->>ObjectStorage: Fetch static files
activate ObjectStorage
ObjectStorage->>Pages: 200 OK (files)
deactivate ObjectStorage
Pages->>User: 200 OK (static files served)
deactivate Pages
deactivate PagesNGINX
```
### Identify error logs
You should check logs in the order shown in the previous sequence diagram.
Filtering based on your domain can also help identify relevant logs.
To start tailing the logs:
1. For **GitLab Pages NGINX** logs, run:
```shell
# View GitLab Pages NGINX error logs
sudo gitlab-ctl tail nginx/gitlab_pages_error.log
# View GitLab Pages NGINX access logs
sudo gitlab-ctl tail nginx/gitlab_pages_access.log
```
1. For **GitLab Pages** logs, run: Start by identifying the [correlation ID from your logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
```shell
sudo gitlab-ctl tail gitlab-pages
```
1. For **GitLab NGINX** logs, run:
```shell
# View GitLab NGINX error logs
sudo gitlab-ctl tail nginx/gitlab_error.log
# View GitLab NGINX access logs
sudo gitlab-ctl tail nginx/gitlab_access.log
```
1. For **GitLab Rails** logs, run:
You can filter these logs based on the `correlation_id` [identified in GitLab Pages logs](../logs/tracing_correlation_id.md#getting-the-correlation-id-from-your-logs).
```shell
sudo gitlab-ctl tail gitlab-rails
```
## Authorization code flow
The following sequence chart illustrates the OAuth authentication flow between the user, GitLab Pages,
and GitLab Rails for accessing protected Pages sites.
For more information, see
[GitLab OAuth authorization code flow](../../api/oauth2.md#authorization-code-flow).
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: GitLab Pages OAuth Flow
accDescr: Sequence diagram showing the OAuth authentication flow between User, GitLab Pages, and GitLab Rails for accessing protected pages sites.
actor User
participant PagesService as GitLab Pages
participant GitlabApp as GitLab Rails
User->>PagesService: GET Request for site
activate PagesService
PagesService-->>User: 302 Redirect to project subdomain https://projects.gitlab.io/auth?state=state1
deactivate PagesService
Note left of User: Cookie state1
User->>PagesService: GET https://projects.gitlab.io/auth?state=state1
activate PagesService
PagesService-->>User: 302 Redirect to gitlab.com/oauth/authorize?state=state1
deactivate PagesService
User->>GitlabApp: GET oauth/authorize?state=state1
activate GitlabApp
GitlabApp-->>User: 200 OK (authorization form)
deactivate GitlabApp
User->>GitlabApp: POST authorization form
activate GitlabApp
GitlabApp-->>User: 302 Redirect to oauth/redirect
deactivate GitlabApp
User->>GitlabApp: GET oauth/redirect?state=state1
activate GitlabApp
GitlabApp-->>User: 200 OK (with auth code)
deactivate GitlabApp
User->>PagesService: GET https://projects.gitlab.io/auth?code=code1&state=state1
activate PagesService
PagesService->>GitlabApp: POST oauth/token with code=code1
activate GitlabApp
GitlabApp-->>PagesService: 200 OK (access token)
deactivate GitlabApp
PagesService-->>User: 302 Redirect to https://[namespace].gitlab.io/auth?code=code2&state=state1
deactivate PagesService
User->>PagesService: GET https://[namespace].gitlab.io/auth?code=code2&state=state1
activate PagesService
PagesService-->>User: 302 Redirect to site
deactivate PagesService
User->>PagesService: GET Request for site
activate PagesService
PagesService-->>User: 200 OK (site content)
deactivate PagesService
```
## `unsupported protocol scheme \"\""`
If you see the following error:
```plaintext
{"error":"failed to connect to internal Pages API: Get \"/api/v4/internal/pages/status\": unsupported protocol scheme \"\"","level":"warning","msg":"attempted to connect to the API","time":"2021-06-23T20:03:30Z"}
```
It means you didn't set the HTTP(S) protocol scheme in the Pages server settings.
To fix it:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['gitlab_server'] = "https://<your_gitlab_server_public_host_and_port>"
gitlab_pages['internal_gitlab_server'] = "https://<your_gitlab_server_private_host_and_port>" # optional, gitlab_pages['gitlab_server'] is used as default
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
## 502 error when connecting to GitLab Pages proxy when server does not listen over IPv6
In some cases, NGINX might default to using IPv6 to connect to the GitLab Pages
service even when the server does not listen over IPv6. You can identify when
this is happening if you see something similar to the log entry below in the
`gitlab_pages_error.log`:
```plaintext
2020/02/24 16:32:05 [error] 112654#0: *4982804 connect() failed (111: Connection refused) while connecting to upstream, client: 123.123.123.123, server: ~^(?<group>.*)\.pages\.example\.com$, request: "GET /-/group/project/-/jobs/1234/artifacts/artifact.txt HTTP/1.1", upstream: "http://[::1]:8090//-/group/project/-/jobs/1234/artifacts/artifact.txt", host: "group.example.com"
```
To resolve this, set an explicit IP and port for the GitLab Pages `listen_proxy` setting
to define the explicit address that the GitLab Pages daemon should listen on:
```ruby
gitlab_pages['listen_proxy'] = '127.0.0.1:8090'
```
## Intermittent 502 errors or after a few days
If you run Pages on a system that uses `systemd` and
[`tmpfiles.d`](https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html),
you may encounter intermittent 502 errors trying to serve Pages with an error similar to:
```plaintext
dial tcp: lookup gitlab.example.com on [::1]:53: dial udp [::1]:53: connect: no route to host"
```
GitLab Pages creates a [bind mount](https://man7.org/linux/man-pages/man8/mount.8.html)
inside `/tmp/gitlab-pages-*` that includes files like `/etc/hosts`.
However, `systemd` may clean the `/tmp/` directory on a regular basis so the DNS
configuration may be lost.
To stop `systemd` from cleaning the Pages related content:
1. Tell `tmpfiles.d` to not remove the Pages `/tmp` directory:
```shell
echo 'x /tmp/gitlab-pages-*' >> /etc/tmpfiles.d/gitlab-pages-jail.conf
```
1. Restart GitLab Pages:
```shell
sudo gitlab-ctl restart gitlab-pages
```
## Unable to access GitLab Pages
If you can't access your GitLab Pages (such as receiving `502 Bad Gateway` errors, or a login loop)
and in your Pages log shows this error:
```plaintext
"error":"retrieval context done: context deadline exceeded","host":"root.docs-cit.otenet.gr","level":"error","msg":"could not fetch domain information from a source"
```
1. Add the following to `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['internal_gitlab_server'] = 'http://localhost:8080'
```
1. Restart GitLab Pages:
```shell
sudo gitlab-ctl restart gitlab-pages
```
## Failed to connect to the internal GitLab API
If you see the following error:
```plaintext
ERRO[0010] Failed to connect to the internal GitLab API after 0.50s error="failed to connect to internal Pages API: HTTP status: 401"
```
If you are [Running GitLab Pages on a separate server](_index.md#running-gitlab-pages-on-a-separate-server)
you must copy the `/etc/gitlab/gitlab-secrets.json` file
from the **GitLab server** to the **Pages server**.
Other reasons may include network connectivity issues between your
**GitLab server** and your **Pages server** such as firewall configurations or closed ports.
For example, if there is a connection timeout:
```plaintext
error="failed to connect to internal Pages API: Get \"https://gitlab.example.com:3000/api/v4/internal/pages/status\": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)"
```
## Pages cannot communicate with an instance of the GitLab API
If you use the default value for `domain_config_source=auto` and run multiple instances of GitLab
Pages, you may see intermittent 502 error responses while serving Pages content. You may also see
the following warning in the Pages logs:
```plaintext
WARN[0010] Pages cannot communicate with an instance of the GitLab API. Please sync your gitlab-secrets.json file https://gitlab.com/gitlab-org/gitlab-pages/-/issues/535#workaround. error="pages endpoint unauthorized"
```
This can happen if your `gitlab-secrets.json` file is out of date between GitLab Rails and GitLab
Pages. Follow steps 8-10 of [Running GitLab Pages on a separate server](_index.md#running-gitlab-pages-on-a-separate-server),
in all of your GitLab Pages instances.
## Intermittent 502 errors when using an AWS Network Load Balancer and GitLab Pages
Connections will time out when using a Network Load Balancer with client IP preservation enabled and [the request is looped back to the source server](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-troubleshooting.html#loopback-timeout).
This can happen to GitLab instances with multiple servers
running both the core GitLab application and GitLab Pages. This can also happen when a single
container is running both the core GitLab application and GitLab Pages.
AWS [recommends using an IP target type](https://repost.aws/knowledge-center/target-connection-fails-load-balancer)
to resolve this issue.
Turning off [client IP preservation](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#client-ip-preservation)
may resolve this issue when the core GitLab application and GitLab Pages run on the same host or
container.
## 500 error with `securecookie: failed to generate random iv` and `Failed to save the session`
This problem most likely results from an out-dated operating system.
The [Pages daemon uses the `securecookie` library](https://gitlab.com/search?group_id=9970&project_id=734943&repository_ref=master&scope=blobs&search=securecookie&snippets=false) to get random strings via [`crypto/rand` in Go](https://pkg.go.dev/crypto/rand#pkg-variables).
This requires the `getrandom` system call or `/dev/urandom` to be available on the host OS.
Upgrading to an [officially supported operating system](../../install/package/_index.md#supported-platforms) is recommended.
## The requested scope is invalid, malformed, or unknown
This problem comes from the permissions of the GitLab Pages OAuth application. To fix it:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications > GitLab Pages**.
1. Edit the application.
1. Under **Scopes**, ensure that the `api` scope is selected.
1. Save your changes.
When running a [separate Pages server](_index.md#running-gitlab-pages-on-a-separate-server),
this setting needs to be configured on the main GitLab server.
## Workaround in case no wildcard DNS entry can be set
If the wildcard DNS [prerequisite](_index.md#prerequisites) can't be met, you can still use GitLab Pages in a limited fashion:
1. [Move](../../user/project/working_with_projects.md#transfer-a-project)
all projects you need to use Pages with into a single group namespace, for example `pages`.
1. Configure a [DNS entry](_index.md#dns-configuration) without the `*.`-wildcard, for example `pages.example.io`.
1. Configure `pages_external_url http://example.io/` in your `gitlab.rb` file.
Omit the group namespace here, because it automatically is prepended by GitLab.
## Pages daemon fails with permission denied errors
If `/tmp` is mounted with `noexec`, the Pages daemon fails to start with an error like:
```plaintext
{"error":"fork/exec /gitlab-pages: permission denied","level":"fatal","msg":"could not create pages daemon","time":"2021-02-02T21:54:34Z"}
```
In this case, change `TMPDIR` to a location that is not mounted with `noexec`. Add the following to
`/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['env'] = {'TMPDIR' => '<new_tmp_path>'}
```
Once added, reconfigure with `sudo gitlab-ctl reconfigure` and restart GitLab with
`sudo gitlab-ctl restart`.
## `The redirect URI included is not valid.` when using Pages Access Control
You may see this error if `pages_external_url` was updated at some point of time. Verify the following:
1. Check the [System OAuth application](../../integration/oauth_provider.md#create-an-instance-wide-application):
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications** and then **Add new application**.
1. Ensure the **Callback URL/Redirect URI** is using the protocol (HTTP or HTTPS) that
`pages_external_url` is configured to use.
1. The domain and path components of `Redirect URI` are valid: they should look like `projects.<pages_external_url>/auth`.
## 500 error `cannot serve from disk`
If you get a 500 response from Pages and encounter an error similar to:
```plaintext
ERRO[0145] cannot serve from disk error="gitlab: disk access is disabled via enable-disk=false" project_id=27 source_path="file:///shared/pages/@hashed/67/06/670671cd97404156226e507973f2ab8330d3022ca96e0c93bdbdb320c41adcaf/pages_deployments/14/artifacts.zip" source_type=zip
```
It means that GitLab Rails is telling GitLab Pages to serve content from a location on disk,
however, GitLab Pages was configured to disable disk access.
To enable disk access:
1. Enable disk access for GitLab Pages in `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_pages['enable_disk'] = true
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## `httprange: new resource 403`
If you see an error similar to:
```plaintext
{"error":"httprange: new resource 403: \"403 Forbidden\"","host":"root.pages.example.com","level":"error","msg":"vfs.Root","path":"/pages1/","time":"2021-06-10T08:45:19Z"}
```
And you run pages on the separate server syncing files via NFS, it may mean that
the shared pages directory is mounted on a different path on the main GitLab server and the
GitLab Pages server.
In that case, it's highly recommended you to configure
[object storage and migrate any existing pages data to it](_index.md#object-storage-settings).
Alternatively, you can mount the GitLab Pages shared directory to the same path on
both servers.
## GitLab Pages deploy job fails with error "is not a recognized provider"
If the **pages** job succeeds but the **deploy** job gives the error "is not a recognized provider":

The error message `is not a recognized provider` could be coming from the `fog` gem that GitLab uses to connect to cloud providers for object storage.
To fix that:
1. Check your `gitlab.rb` file. If you have `gitlab_rails['pages_object_store_enabled']` enabled, but no bucket details have been configured, either:
- Configure object storage for your Pages deployments, following the [S3-compatible connection settings](_index.md#s3-compatible-connection-settings) guide.
- Store your deployments locally, by commenting out that line.
1. Save the changes you made to your `gitlab.rb` file, then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
## 404 error `The page you're looking for could not be found`
If you get a `404 Page Not Found` response from GitLab Pages:
1. Check `.gitlab-ci.yml` contains the job `pages:`.
1. Check the current project's pipeline to confirm the job `pages:deploy` is being run.
Without the `pages:deploy` job, the updates to your GitLab Pages site are never published.
## 503 error `Client authentication failed due to unknown client`
If Pages is a registered OAuth application and [access control is enabled](../../user/project/pages/pages_access_control.md), this error indicates that the authentication token stored in `/etc/gitlab/gitlab-secrets.json` has become invalid:
```plaintext
Client authentication failed due to unknown client, no client authentication included,
or unsupported authentication method.
```
To resolve:
1. Back up your secrets file:
```shell
sudo cp /etc/gitlab/gitlab-secrets.json /etc/gitlab/gitlab-secrets.json.$(date +\%Y\%m\%d)
```
1. Edit `/etc/gitlab/gitlab-secrets.json` and remove the `gitlab_pages` section.
1. Reconfigure GitLab and regenerate the OAuth token:
```shell
sudo gitlab-ctl reconfigure
```
|
https://docs.gitlab.com/administration/postgresql
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/postgresql.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
postgresql.md
|
Data Access
|
Database Operations
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
PostgreSQL
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page contains information about PostgreSQL the GitLab Support team uses
when troubleshooting. GitLab makes this information public, so that anyone can
make use of the Support team's collected knowledge.
{{< alert type="warning" >}}
Some procedures documented here may break your GitLab instance. Use at your
own risk.
{{< /alert >}}
If you're on a [paid tier](https://about.gitlab.com/pricing/) and aren't sure
how to use these commands, [contact Support](https://about.gitlab.com/support/)
for assistance with any issues you're having.
## Start a database console
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
Recommended for:
- Single-node instances.
- Scaled out or hybrid environments, on the Patroni nodes, usually the leader.
- Scaled out or hybrid environments, on the server running the PostgreSQL service.
```shell
sudo gitlab-psql
```
On a single-node instance, or a web or Sidekiq node you can also use the Rails database console, but
it takes longer to initialize:
```shell
sudo gitlab-rails dbconsole --database main
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it <container-id> gitlab-psql
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
Use the `psql` command that's part of [your PostgreSQL installation](../../install/self_compiled/_index.md#7-database).
```shell
sudo -u git -H psql -d gitlabhq_production
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
- If you run a hybrid environment, and PostgreSQL runs on a Linux packaged installation (Omnibus),
the recommended approach is to use the database console locally on those servers. Refer to the details
for Linux package.
- Use the console that's part of your external third-party PostgreSQL service.
- Run `gitlab-rails db-console` in the toolbox pod.
- Refer to our [Kubernetes cheat sheet](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html#gitlab-specific-kubernetes-information) for details.
{{< /tab >}}
{{< /tabs >}}
To exit the console, type: `quit`.
## Other GitLab PostgreSQL documentation
This section is for links to information elsewhere in the GitLab documentation.
### Procedures
- [Database procedures for Linux package installations](https://docs.gitlab.com/omnibus/settings/database.html) including:
- SSL: enabling, disabling, and verifying.
- Enabling Write Ahead Log (WAL) archiving.
- Using an external (non-Omnibus) PostgreSQL installation; and backing it up.
- Listening on TCP/IP as well as or instead of sockets.
- Storing data in another location.
- Destructively reseeding the GitLab database.
- Guidance around updating packaged PostgreSQL, including how to stop it
from happening automatically.
- [Information about external PostgreSQL](../postgresql/external.md).
- [Running Geo with external PostgreSQL](../geo/setup/external_database.md).
- [Upgrades when running PostgreSQL configured for HA](https://docs.gitlab.com/omnibus/settings/database.html#upgrading-a-gitlab-ha-cluster).
- Consuming PostgreSQL from [within CI runners](../../ci/services/postgres.md).
- Managing PostgreSQL versions on Linux package installations from the Linux package development
documentation.
- [PostgreSQL scaling](../postgresql/replication_and_failover.md)
- Including [troubleshooting](../postgresql/replication_and_failover_troubleshooting.md)
`gitlab-ctl patroni check-leader` and PgBouncer errors.
- Developer database documentation,
some of which is absolutely not for production use. Including:
- Understanding EXPLAIN plans.
## Support topics
### Database deadlocks
References:
- [Deadlocks can occur if an instance is flooded with pushes](https://gitlab.com/gitlab-org/gitlab/-/issues/33650).
Provided for context about how GitLab code can have this sort of
unanticipated effect in unusual situations.
```plaintext
ERROR: deadlock detected
```
Three applicable timeouts are identified in the issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528); our recommended settings are as follows:
```ini
deadlock_timeout = 5s
statement_timeout = 15s
idle_in_transaction_session_timeout = 60s
```
Quoting from issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528):
<!-- vale gitlab_base.FutureTense = NO -->
> "If a deadlock is hit, and we resolve it through aborting the transaction after a short period, then the retry mechanisms we already have will make the deadlocked piece of work try again, and it's unlikely we'll deadlock multiple times in a row."
<!-- vale gitlab_base.FutureTense = YES -->
{{< alert type="note" >}}
In Support, our general approach to reconfiguring timeouts (applies also to the
HTTP stack) is that it's acceptable to do it temporarily as a workaround. If it
makes GitLab usable for the customer, then it buys time to understand the
problem more completely, implement a hot fix, or make some other change that
addresses the root cause. Generally, the timeouts should be put back to
reasonable defaults after the root cause is resolved.
{{< /alert >}}
In this case, the guidance we had from development was to drop `deadlock_timeout`
or `statement_timeout`, but to leave the third setting at 60 seconds. Setting
`idle_in_transaction` protects the database from sessions potentially hanging for
days. There's more discussion in [the issue relating to introducing this timeout on GitLab.com](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/1053).
PostgreSQL defaults:
- `statement_timeout = 0` (never)
- `idle_in_transaction_session_timeout = 0` (never)
Comments in issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528)
indicate that these should both be set to at least a number of minutes for all
Linux package installations (so they don't hang indefinitely). However, 15 s
for `statement_timeout` is very short, and is only effective if the
underlying infrastructure is very performant.
See current settings with:
```shell
sudo gitlab-rails runner "c = ApplicationRecord.connection ; puts c.execute('SHOW statement_timeout').to_a ;
puts c.execute('SHOW deadlock_timeout').to_a ;
puts c.execute('SHOW idle_in_transaction_session_timeout').to_a ;"
```
It may take a little while to respond.
```ruby
{"statement_timeout"=>"1min"}
{"deadlock_timeout"=>"0"}
{"idle_in_transaction_session_timeout"=>"1min"}
```
These settings can be updated in `/etc/gitlab/gitlab.rb` with:
```ruby
postgresql['deadlock_timeout'] = '5s'
postgresql['statement_timeout'] = '15s'
postgresql['idle_in_transaction_session_timeout'] = '60s'
```
Once saved, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< alert type="note" >}}
These are Linux package settings. If an external database, such as a customer's PostgreSQL installation
or Amazon RDS is being used, these values don't get set, and would have to be set externally.
{{< /alert >}}
### Temporarily changing the statement timeout
{{< alert type="warning" >}}
The following advice does not apply in case
[PgBouncer](../postgresql/pgbouncer.md) is enabled,
because the changed timeout might affect more transactions than intended.
{{< /alert >}}
In some situations, it may be desirable to set a different statement timeout
without having to [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation),
which in this case would restart Puma and Sidekiq.
For example, a backup may fail with the following errors in the output of the
[backup command](../backup_restore/_index.md#back-up-gitlab)
because the statement timeout was too short:
```plaintext
pg_dump: error: Error message from server: server closed the connection unexpectedly
```
You may also see errors in the [PostgreSQL logs](../logs/_index.md#postgresql-logs):
```plaintext
canceling statement due to statement timeout
```
To temporarily change the statement timeout:
1. Open `/var/opt/gitlab/gitlab-rails/etc/database.yml` in an editor
1. Set the value of `statement_timeout` to `0`, which sets an unlimited statement timeout.
1. [Confirm in a new Rails console session](../operations/rails_console.md#using-the-rails-runner)
that this value is used:
```shell
sudo gitlab-rails runner "ActiveRecord::Base.connection_db_config[:variables]"
```
1. Perform the action for which you need a different timeout
(for example the backup or the Rails command).
1. Revert the edit in `/var/opt/gitlab/gitlab-rails/etc/database.yml`.
### Observe (RE)INDEX progress report
In some situations, you might want to observe the progress of a `CREATE INDEX` or `REINDEX` operation. For example, you can do this to confirm whether the `CREATE INDEX` or `REINDEX` operation is active, or to check which phase the operation is in.
Prerequisites:
- You must use PostgreSQL version 12 or later.
To observe a `CREATE INDEX` or `REINDEX` operation:
- Use the built-in [`pg_stat_progress_create_index` view](https://www.postgresql.org/docs/16/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING).
For example, from a database console session, run the following command:
```sql
SELECT * FROM pg_stat_progress_create_index \watch 0.2
```
To learn more about producing human-friendly output and writing data to log files, see [this snippet](https://gitlab.com/-/snippets/3750940).
## Troubleshooting
### Database connection is refused
If you encounter the following errors, check if `max_connections` is high enough to ensure stable connections.
```shell
connection to server at "xxx.xxx.xxx.xxx", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
```
```shell
psql: error: connection to server on socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432" failed:
FATAL: sorry, too many clients already
```
To adjust `max_connections`, see [configuring multiple database connections](https://docs.gitlab.com/omnibus/settings/database/#configuring-multiple-database-connections).
### Database is not accepting commands to avoid wraparound data loss
This error likely means that `autovacuum` is failing to complete its run:
```plaintext
ERROR: database is not accepting commands to avoid wraparound data loss in database "gitlabhq_production"
```
Or
```plaintext
ERROR: failed to re-find parent key in index "XXX" for deletion target page XXX
```
To resolve the error, run `VACUUM` manually:
1. Stop GitLab with the command `gitlab-ctl stop`.
1. Place the database in single-user mode with the command:
```shell
/opt/gitlab/embedded/bin/postgres --single -D /var/opt/gitlab/postgresql/data gitlabhq_production
```
1. In the `backend>` prompt, run `VACUUM;`. This command can take several minutes to complete.
1. Wait for the command to complete, then press <kbd>Control</kbd> + <kbd>D</kbd> to exit.
1. Start GitLab with the command `gitlab-ctl start`.
### GitLab database requirements
See [database requirements](../../install/requirements.md#postgresql) and review and install the
[required extension list](../../install/postgresql_extensions.md).
### Serialization errors in the `production/sidekiq` log
If you receive errors like this example in your `production/sidekiq` log, read
about [setting `default_transaction_isolation` into read committed](https://docs.gitlab.com/omnibus/settings/database.html#set-default_transaction_isolation-into-read-committed) to fix the problem:
```plaintext
ActiveRecord::StatementInvalid PG::TRSerializationFailure: ERROR: could not serialize access due to concurrent update
```
### PostgreSQL replication slot errors
If you receive errors like this example, read about how to resolve PostgreSQL HA
[replication slot errors](https://docs.gitlab.com/omnibus/settings/database.html#troubleshooting-upgrades-in-an-ha-cluster):
```plaintext
pg_basebackup: could not create temporary replication slot "pg_basebackup_12345": ERROR: all replication slots are in use
HINT: Free one or increase max_replication_slots.
```
### Geo replication errors
If you receive errors like this example, read about how to resolve
[Geo replication errors](../geo/replication/troubleshooting/postgresql_replication.md):
```plaintext
ERROR: replication slots can only be used if max_replication_slots > 0
FATAL: could not start WAL streaming: ERROR: replication slot "geo_secondary_my_domain_com" does not exist
Command exceeded allowed execution time
PANIC: could not write to file 'pg_xlog/xlogtemp.123': No space left on device
```
### Review Geo configuration and common errors
When troubleshooting problems with Geo, you should:
- Review [common Geo errors](../geo/replication/troubleshooting/common.md#fixing-common-errors).
- [Review your Geo configuration](../geo/replication/troubleshooting/_index.md), including:
- Reconfiguring hosts and ports.
- Reviewing and fixing the user and password mappings.
### Mismatch in `pg_dump` and `psql` versions
If you receive errors like this example, read about how to
[back up and restore a non-packaged PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#backup-and-restore-a-non-packaged-postgresql-database):
```plaintext
Dumping PostgreSQL database gitlabhq_production ... pg_dump: error: server version: 13.3; pg_dump version: 14.2
pg_dump: error: aborting because of server version mismatch
```
### Extension `btree_gist` is not allow-listed
Deploying PostgreSQL on an Azure Database for PostgreSQL - Flexible Server may result in this error:
```plaintext
extension "btree_gist" is not allow-listed for "azure_pg_admin" users in Azure Database for PostgreSQL
```
To resolve this error, [allow-list the extension](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-extensions#how-to-use-postgresql-extensions) prior to install.
|
---
stage: Data Access
group: Database Operations
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: PostgreSQL
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page contains information about PostgreSQL the GitLab Support team uses
when troubleshooting. GitLab makes this information public, so that anyone can
make use of the Support team's collected knowledge.
{{< alert type="warning" >}}
Some procedures documented here may break your GitLab instance. Use at your
own risk.
{{< /alert >}}
If you're on a [paid tier](https://about.gitlab.com/pricing/) and aren't sure
how to use these commands, [contact Support](https://about.gitlab.com/support/)
for assistance with any issues you're having.
## Start a database console
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
Recommended for:
- Single-node instances.
- Scaled out or hybrid environments, on the Patroni nodes, usually the leader.
- Scaled out or hybrid environments, on the server running the PostgreSQL service.
```shell
sudo gitlab-psql
```
On a single-node instance, or a web or Sidekiq node you can also use the Rails database console, but
it takes longer to initialize:
```shell
sudo gitlab-rails dbconsole --database main
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it <container-id> gitlab-psql
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
Use the `psql` command that's part of [your PostgreSQL installation](../../install/self_compiled/_index.md#7-database).
```shell
sudo -u git -H psql -d gitlabhq_production
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
- If you run a hybrid environment, and PostgreSQL runs on a Linux packaged installation (Omnibus),
the recommended approach is to use the database console locally on those servers. Refer to the details
for Linux package.
- Use the console that's part of your external third-party PostgreSQL service.
- Run `gitlab-rails db-console` in the toolbox pod.
- Refer to our [Kubernetes cheat sheet](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html#gitlab-specific-kubernetes-information) for details.
{{< /tab >}}
{{< /tabs >}}
To exit the console, type: `quit`.
## Other GitLab PostgreSQL documentation
This section is for links to information elsewhere in the GitLab documentation.
### Procedures
- [Database procedures for Linux package installations](https://docs.gitlab.com/omnibus/settings/database.html) including:
- SSL: enabling, disabling, and verifying.
- Enabling Write Ahead Log (WAL) archiving.
- Using an external (non-Omnibus) PostgreSQL installation; and backing it up.
- Listening on TCP/IP as well as or instead of sockets.
- Storing data in another location.
- Destructively reseeding the GitLab database.
- Guidance around updating packaged PostgreSQL, including how to stop it
from happening automatically.
- [Information about external PostgreSQL](../postgresql/external.md).
- [Running Geo with external PostgreSQL](../geo/setup/external_database.md).
- [Upgrades when running PostgreSQL configured for HA](https://docs.gitlab.com/omnibus/settings/database.html#upgrading-a-gitlab-ha-cluster).
- Consuming PostgreSQL from [within CI runners](../../ci/services/postgres.md).
- Managing PostgreSQL versions on Linux package installations from the Linux package development
documentation.
- [PostgreSQL scaling](../postgresql/replication_and_failover.md)
- Including [troubleshooting](../postgresql/replication_and_failover_troubleshooting.md)
`gitlab-ctl patroni check-leader` and PgBouncer errors.
- Developer database documentation,
some of which is absolutely not for production use. Including:
- Understanding EXPLAIN plans.
## Support topics
### Database deadlocks
References:
- [Deadlocks can occur if an instance is flooded with pushes](https://gitlab.com/gitlab-org/gitlab/-/issues/33650).
Provided for context about how GitLab code can have this sort of
unanticipated effect in unusual situations.
```plaintext
ERROR: deadlock detected
```
Three applicable timeouts are identified in the issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528); our recommended settings are as follows:
```ini
deadlock_timeout = 5s
statement_timeout = 15s
idle_in_transaction_session_timeout = 60s
```
Quoting from issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528):
<!-- vale gitlab_base.FutureTense = NO -->
> "If a deadlock is hit, and we resolve it through aborting the transaction after a short period, then the retry mechanisms we already have will make the deadlocked piece of work try again, and it's unlikely we'll deadlock multiple times in a row."
<!-- vale gitlab_base.FutureTense = YES -->
{{< alert type="note" >}}
In Support, our general approach to reconfiguring timeouts (applies also to the
HTTP stack) is that it's acceptable to do it temporarily as a workaround. If it
makes GitLab usable for the customer, then it buys time to understand the
problem more completely, implement a hot fix, or make some other change that
addresses the root cause. Generally, the timeouts should be put back to
reasonable defaults after the root cause is resolved.
{{< /alert >}}
In this case, the guidance we had from development was to drop `deadlock_timeout`
or `statement_timeout`, but to leave the third setting at 60 seconds. Setting
`idle_in_transaction` protects the database from sessions potentially hanging for
days. There's more discussion in [the issue relating to introducing this timeout on GitLab.com](https://gitlab.com/gitlab-com/gl-infra/production/-/issues/1053).
PostgreSQL defaults:
- `statement_timeout = 0` (never)
- `idle_in_transaction_session_timeout = 0` (never)
Comments in issue [#30528](https://gitlab.com/gitlab-org/gitlab/-/issues/30528)
indicate that these should both be set to at least a number of minutes for all
Linux package installations (so they don't hang indefinitely). However, 15 s
for `statement_timeout` is very short, and is only effective if the
underlying infrastructure is very performant.
See current settings with:
```shell
sudo gitlab-rails runner "c = ApplicationRecord.connection ; puts c.execute('SHOW statement_timeout').to_a ;
puts c.execute('SHOW deadlock_timeout').to_a ;
puts c.execute('SHOW idle_in_transaction_session_timeout').to_a ;"
```
It may take a little while to respond.
```ruby
{"statement_timeout"=>"1min"}
{"deadlock_timeout"=>"0"}
{"idle_in_transaction_session_timeout"=>"1min"}
```
These settings can be updated in `/etc/gitlab/gitlab.rb` with:
```ruby
postgresql['deadlock_timeout'] = '5s'
postgresql['statement_timeout'] = '15s'
postgresql['idle_in_transaction_session_timeout'] = '60s'
```
Once saved, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< alert type="note" >}}
These are Linux package settings. If an external database, such as a customer's PostgreSQL installation
or Amazon RDS is being used, these values don't get set, and would have to be set externally.
{{< /alert >}}
### Temporarily changing the statement timeout
{{< alert type="warning" >}}
The following advice does not apply in case
[PgBouncer](../postgresql/pgbouncer.md) is enabled,
because the changed timeout might affect more transactions than intended.
{{< /alert >}}
In some situations, it may be desirable to set a different statement timeout
without having to [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation),
which in this case would restart Puma and Sidekiq.
For example, a backup may fail with the following errors in the output of the
[backup command](../backup_restore/_index.md#back-up-gitlab)
because the statement timeout was too short:
```plaintext
pg_dump: error: Error message from server: server closed the connection unexpectedly
```
You may also see errors in the [PostgreSQL logs](../logs/_index.md#postgresql-logs):
```plaintext
canceling statement due to statement timeout
```
To temporarily change the statement timeout:
1. Open `/var/opt/gitlab/gitlab-rails/etc/database.yml` in an editor
1. Set the value of `statement_timeout` to `0`, which sets an unlimited statement timeout.
1. [Confirm in a new Rails console session](../operations/rails_console.md#using-the-rails-runner)
that this value is used:
```shell
sudo gitlab-rails runner "ActiveRecord::Base.connection_db_config[:variables]"
```
1. Perform the action for which you need a different timeout
(for example the backup or the Rails command).
1. Revert the edit in `/var/opt/gitlab/gitlab-rails/etc/database.yml`.
### Observe (RE)INDEX progress report
In some situations, you might want to observe the progress of a `CREATE INDEX` or `REINDEX` operation. For example, you can do this to confirm whether the `CREATE INDEX` or `REINDEX` operation is active, or to check which phase the operation is in.
Prerequisites:
- You must use PostgreSQL version 12 or later.
To observe a `CREATE INDEX` or `REINDEX` operation:
- Use the built-in [`pg_stat_progress_create_index` view](https://www.postgresql.org/docs/16/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING).
For example, from a database console session, run the following command:
```sql
SELECT * FROM pg_stat_progress_create_index \watch 0.2
```
To learn more about producing human-friendly output and writing data to log files, see [this snippet](https://gitlab.com/-/snippets/3750940).
## Troubleshooting
### Database connection is refused
If you encounter the following errors, check if `max_connections` is high enough to ensure stable connections.
```shell
connection to server at "xxx.xxx.xxx.xxx", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
```
```shell
psql: error: connection to server on socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432" failed:
FATAL: sorry, too many clients already
```
To adjust `max_connections`, see [configuring multiple database connections](https://docs.gitlab.com/omnibus/settings/database/#configuring-multiple-database-connections).
### Database is not accepting commands to avoid wraparound data loss
This error likely means that `autovacuum` is failing to complete its run:
```plaintext
ERROR: database is not accepting commands to avoid wraparound data loss in database "gitlabhq_production"
```
Or
```plaintext
ERROR: failed to re-find parent key in index "XXX" for deletion target page XXX
```
To resolve the error, run `VACUUM` manually:
1. Stop GitLab with the command `gitlab-ctl stop`.
1. Place the database in single-user mode with the command:
```shell
/opt/gitlab/embedded/bin/postgres --single -D /var/opt/gitlab/postgresql/data gitlabhq_production
```
1. In the `backend>` prompt, run `VACUUM;`. This command can take several minutes to complete.
1. Wait for the command to complete, then press <kbd>Control</kbd> + <kbd>D</kbd> to exit.
1. Start GitLab with the command `gitlab-ctl start`.
### GitLab database requirements
See [database requirements](../../install/requirements.md#postgresql) and review and install the
[required extension list](../../install/postgresql_extensions.md).
### Serialization errors in the `production/sidekiq` log
If you receive errors like this example in your `production/sidekiq` log, read
about [setting `default_transaction_isolation` into read committed](https://docs.gitlab.com/omnibus/settings/database.html#set-default_transaction_isolation-into-read-committed) to fix the problem:
```plaintext
ActiveRecord::StatementInvalid PG::TRSerializationFailure: ERROR: could not serialize access due to concurrent update
```
### PostgreSQL replication slot errors
If you receive errors like this example, read about how to resolve PostgreSQL HA
[replication slot errors](https://docs.gitlab.com/omnibus/settings/database.html#troubleshooting-upgrades-in-an-ha-cluster):
```plaintext
pg_basebackup: could not create temporary replication slot "pg_basebackup_12345": ERROR: all replication slots are in use
HINT: Free one or increase max_replication_slots.
```
### Geo replication errors
If you receive errors like this example, read about how to resolve
[Geo replication errors](../geo/replication/troubleshooting/postgresql_replication.md):
```plaintext
ERROR: replication slots can only be used if max_replication_slots > 0
FATAL: could not start WAL streaming: ERROR: replication slot "geo_secondary_my_domain_com" does not exist
Command exceeded allowed execution time
PANIC: could not write to file 'pg_xlog/xlogtemp.123': No space left on device
```
### Review Geo configuration and common errors
When troubleshooting problems with Geo, you should:
- Review [common Geo errors](../geo/replication/troubleshooting/common.md#fixing-common-errors).
- [Review your Geo configuration](../geo/replication/troubleshooting/_index.md), including:
- Reconfiguring hosts and ports.
- Reviewing and fixing the user and password mappings.
### Mismatch in `pg_dump` and `psql` versions
If you receive errors like this example, read about how to
[back up and restore a non-packaged PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#backup-and-restore-a-non-packaged-postgresql-database):
```plaintext
Dumping PostgreSQL database gitlabhq_production ... pg_dump: error: server version: 13.3; pg_dump version: 14.2
pg_dump: error: aborting because of server version mismatch
```
### Extension `btree_gist` is not allow-listed
Deploying PostgreSQL on an Azure Database for PostgreSQL - Flexible Server may result in this error:
```plaintext
extension "btree_gist" is not allow-listed for "azure_pg_admin" users in Azure Database for PostgreSQL
```
To resolve this error, [allow-list the extension](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-extensions#how-to-use-postgresql-extensions) prior to install.
|
https://docs.gitlab.com/administration/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting a GitLab installation
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page documents a collection of resources to help you troubleshoot a GitLab
installation.
This list is not necessarily comprehensive. If you don't find what you're looking
for in this list, you should search the documentation.
## Troubleshooting guides
- [SSL](https://docs.gitlab.com/omnibus/settings/ssl/ssl_troubleshooting.html)
- [Geo](../geo/replication/troubleshooting/_index.md)
- [SAML](../../user/group/saml_sso/troubleshooting.md)
- [Kubernetes cheat sheet](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html)
- [Linux cheat sheet](linux_cheat_sheet.md)
- [Parsing GitLab logs with `jq`](../logs/log_parsing.md)
- [Diagnostics tools](diagnostics_tools.md)
Some feature documentation pages also have a troubleshooting section at the end
that you can check for feature-specific help, including helpful Rails commands.
If you need a testing environment to troubleshoot, see the
[apps for a testing environment](test_environments.md).
## Support team troubleshooting info
The GitLab Support Team has collected a lot of information about troubleshooting GitLab.
The following documents are used by the Support Team or by customers
with direct guidance from a Support Team member. GitLab administrators may find the
information useful for troubleshooting. However, if you are experiencing trouble with your
GitLab instance, you should check your [support options](https://about.gitlab.com/support/)
before referring to these documents.
{{< alert type="warning" >}}
The commands in the following documentation might result in data loss or
other damage to a GitLab instance. They should be used only by experienced administrators
who are aware of the risks.
{{< /alert >}}
- [Diagnostics tools](diagnostics_tools.md)
- [Linux commands](linux_cheat_sheet.md)
- [Troubleshooting Kubernetes](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html)
- [Troubleshooting PostgreSQL](postgresql.md)
- [Guide to test environments](test_environments.md) (for Support Engineers)
- [Troubleshooting SSL](https://docs.gitlab.com/omnibus/settings/ssl/ssl_troubleshooting.html)
- Related links:
- [Repairing and recovering broken Git repositories](https://git.seveas.net/repairing-and-recovering-broken-git-repositories.html)
- [Testing with OpenSSL](https://www.feistyduck.com/library/openssl-cookbook/online/testing-with-openssl/index.html)
- [`strace` zine](https://wizardzines.com/zines/strace/)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting a GitLab installation
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page documents a collection of resources to help you troubleshoot a GitLab
installation.
This list is not necessarily comprehensive. If you don't find what you're looking
for in this list, you should search the documentation.
## Troubleshooting guides
- [SSL](https://docs.gitlab.com/omnibus/settings/ssl/ssl_troubleshooting.html)
- [Geo](../geo/replication/troubleshooting/_index.md)
- [SAML](../../user/group/saml_sso/troubleshooting.md)
- [Kubernetes cheat sheet](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html)
- [Linux cheat sheet](linux_cheat_sheet.md)
- [Parsing GitLab logs with `jq`](../logs/log_parsing.md)
- [Diagnostics tools](diagnostics_tools.md)
Some feature documentation pages also have a troubleshooting section at the end
that you can check for feature-specific help, including helpful Rails commands.
If you need a testing environment to troubleshoot, see the
[apps for a testing environment](test_environments.md).
## Support team troubleshooting info
The GitLab Support Team has collected a lot of information about troubleshooting GitLab.
The following documents are used by the Support Team or by customers
with direct guidance from a Support Team member. GitLab administrators may find the
information useful for troubleshooting. However, if you are experiencing trouble with your
GitLab instance, you should check your [support options](https://about.gitlab.com/support/)
before referring to these documents.
{{< alert type="warning" >}}
The commands in the following documentation might result in data loss or
other damage to a GitLab instance. They should be used only by experienced administrators
who are aware of the risks.
{{< /alert >}}
- [Diagnostics tools](diagnostics_tools.md)
- [Linux commands](linux_cheat_sheet.md)
- [Troubleshooting Kubernetes](https://docs.gitlab.com/charts/troubleshooting/kubernetes_cheat_sheet.html)
- [Troubleshooting PostgreSQL](postgresql.md)
- [Guide to test environments](test_environments.md) (for Support Engineers)
- [Troubleshooting SSL](https://docs.gitlab.com/omnibus/settings/ssl/ssl_troubleshooting.html)
- Related links:
- [Repairing and recovering broken Git repositories](https://git.seveas.net/repairing-and-recovering-broken-git-repositories.html)
- [Testing with OpenSSL](https://www.feistyduck.com/library/openssl-cookbook/online/testing-with-openssl/index.html)
- [`strace` zine](https://wizardzines.com/zines/strace/)
|
https://docs.gitlab.com/administration/gitlab_rails_cheat_sheet
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/gitlab_rails_cheat_sheet.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
gitlab_rails_cheat_sheet.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Rails Console Cheat Sheet
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This was the GitLab Support Team's collection of information regarding the GitLab Rails
console, for use while troubleshooting. It is listed here for posterity,
as most content has been moved to feature-specific troubleshooting pages and sections,
see epic [&8147](https://gitlab.com/groups/gitlab-org/-/epics/8147#tree).
You may want to update your bookmarks accordingly.
If you are currently having an issue with GitLab,
it is highly recommended that you first check
our guide on [the Rails console](../operations/rails_console.md),
and your [support options](https://about.gitlab.com/support/),
before attempting the information pointed to from here.
{{< alert type="warning" >}}
Some of these scripts could be damaging if not run correctly,
or under the right conditions. We highly recommend running them under the
guidance of a Support Engineer, or running them in a test environment with a
backup of the instance ready to be restored, just in case.
{{< /alert >}}
{{< alert type="warning" >}}
As GitLab changes, changes to the code are inevitable,
and so some scripts may not work as they once used to. These are not kept
up-to-date as these scripts/commands were added as they were found/needed. As
mentioned previously, we recommend running these scripts under the supervision of a
Support Engineer, who can also verify that they continue to work as they
should and, if needed, update the script for the latest version of GitLab.
{{< /alert >}}
## Mirrors
### Find mirrors with "bad decrypt" errors
This content has been converted to a Rake task, see [verify database values can be decrypted using the current secrets](../raketasks/check.md#verify-database-values-can-be-decrypted-using-the-current-secrets).
### Transfer mirror users and tokens to a single service account
This content has been moved to [Troubleshooting Repository mirroring](../../user/project/repository/mirror/troubleshooting.md#transfer-mirror-users-and-tokens-to-a-single-service-account).
## Merge requests
## CI
This content has been moved to [CI/CD maintenance](../cicd/maintenance.md).
## License
This content has been moved to [Activate GitLab EE with a license file or key](../license_file.md).
## Registry
### Registry Disk Space Usage by Project
To view storage space by project in the container registry, see [Registry Disk Space Usage by Project](../packages/container_registry.md#registry-disk-space-usage-by-project).
### Run the cleanup policy
To reduce storage space in the container registry, see [Run the cleanup policy](../packages/container_registry.md#run-the-cleanup-policy).
## Sidekiq
This content has been moved to [Troubleshooting Sidekiq](../sidekiq/sidekiq_troubleshooting.md).
## Geo
### Reverify all uploads (or any SSF data type which is verified)
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#resync-and-reverify-multiple-components).
### Artifacts
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Repository verification failures
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Resync repositories
Moved to [Geo replication troubleshooting - Resync repository types](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
Moved to [Geo replication troubleshooting - Resync project and project wiki repositories](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Blob types
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
## Generate Service Ping
This content has been moved to Troubleshooting Service Ping in the GitLab development documentation.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab Rails Console Cheat Sheet
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This was the GitLab Support Team's collection of information regarding the GitLab Rails
console, for use while troubleshooting. It is listed here for posterity,
as most content has been moved to feature-specific troubleshooting pages and sections,
see epic [&8147](https://gitlab.com/groups/gitlab-org/-/epics/8147#tree).
You may want to update your bookmarks accordingly.
If you are currently having an issue with GitLab,
it is highly recommended that you first check
our guide on [the Rails console](../operations/rails_console.md),
and your [support options](https://about.gitlab.com/support/),
before attempting the information pointed to from here.
{{< alert type="warning" >}}
Some of these scripts could be damaging if not run correctly,
or under the right conditions. We highly recommend running them under the
guidance of a Support Engineer, or running them in a test environment with a
backup of the instance ready to be restored, just in case.
{{< /alert >}}
{{< alert type="warning" >}}
As GitLab changes, changes to the code are inevitable,
and so some scripts may not work as they once used to. These are not kept
up-to-date as these scripts/commands were added as they were found/needed. As
mentioned previously, we recommend running these scripts under the supervision of a
Support Engineer, who can also verify that they continue to work as they
should and, if needed, update the script for the latest version of GitLab.
{{< /alert >}}
## Mirrors
### Find mirrors with "bad decrypt" errors
This content has been converted to a Rake task, see [verify database values can be decrypted using the current secrets](../raketasks/check.md#verify-database-values-can-be-decrypted-using-the-current-secrets).
### Transfer mirror users and tokens to a single service account
This content has been moved to [Troubleshooting Repository mirroring](../../user/project/repository/mirror/troubleshooting.md#transfer-mirror-users-and-tokens-to-a-single-service-account).
## Merge requests
## CI
This content has been moved to [CI/CD maintenance](../cicd/maintenance.md).
## License
This content has been moved to [Activate GitLab EE with a license file or key](../license_file.md).
## Registry
### Registry Disk Space Usage by Project
To view storage space by project in the container registry, see [Registry Disk Space Usage by Project](../packages/container_registry.md#registry-disk-space-usage-by-project).
### Run the cleanup policy
To reduce storage space in the container registry, see [Run the cleanup policy](../packages/container_registry.md#run-the-cleanup-policy).
## Sidekiq
This content has been moved to [Troubleshooting Sidekiq](../sidekiq/sidekiq_troubleshooting.md).
## Geo
### Reverify all uploads (or any SSF data type which is verified)
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#resync-and-reverify-multiple-components).
### Artifacts
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Repository verification failures
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Resync repositories
Moved to [Geo replication troubleshooting - Resync repository types](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
Moved to [Geo replication troubleshooting - Resync project and project wiki repositories](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
### Blob types
Moved to [Geo replication troubleshooting](../geo/replication/troubleshooting/synchronization_verification.md#manually-retry-replication-or-verification).
## Generate Service Ping
This content has been moved to Troubleshooting Service Ping in the GitLab development documentation.
|
https://docs.gitlab.com/administration/diagnostics_tools
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/diagnostics_tools.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
diagnostics_tools.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Diagnostics tools
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
These are some of the diagnostics tools the GitLab Support team uses during troubleshooting.
They are listed here for transparency, and for users with experience
with troubleshooting GitLab. If you are currently having an issue with GitLab, you
may want to check your [support options](https://about.gitlab.com/support/) first,
before attempting to use these tools.
## SOS scripts
- [`gitlabsos`](https://gitlab.com/gitlab-com/support/toolbox/gitlabsos/)
gathers information and recent logs from a Linux package or Docker-based GitLab instance
and its operating system.
The Linux package and Docker image for GitLab versions 18.3 and up bundle `gitlabsos`:
```shell
sudo gitlabsos
```
- [`kubesos`](https://gitlab.com/gitlab-com/support/toolbox/kubesos/)
gathers k8s cluster configuration and recent logs from a GitLab Helm chart deployment.
- [`gitlab:db:sos`](../raketasks/maintenance.md#collect-information-and-statistics-about-the-database)
gathers detailed diagnostic data about your database.
## strace-parser
[`strace-parser`](https://gitlab.com/gitlab-com/support/toolbox/strace-parser)
analyzes and summarize raw `strace` data.
The [`strace` zine](https://wizardzines.com/zines/strace/) is recommended for context.
## `gitlabrb_sanitizer`
[1](https://gitlab.com/gitlab-com/support/toolbox/gitlabrb_sanitizer/) outputs a copy of `/etc/gitlab/gitlab.rb` content with sensitive values redacted.
The Linux package and Docker image for GitLab versions 18.3 and up
bundle `gitlabrb_sanitizer` with `gitlabsos`. `gitlabsos` automatically uses it to
sanitize the configuration.
## `fast-stats`
[`fast-stats`](https://gitlab.com/gitlab-com/support/toolbox/fast-stats#fast-stats)
summarizes errors and resource-intensive usage statistics quickly,
to help debug performance and configuration problems.
`fast-stats` is particularly useful to parse and compare large volumes of logs,
or to start troubleshooting unknown problems.
The Linux package and Docker image for GitLab versions 18.3 and up include `fast-stats`:
```shell
/opt/gitlab/embedded/bin/fast-stats
```
## `greenhat`
[`greenhat`](https://gitlab.com/gitlab-com/support/toolbox/greenhat/)
provides an interactive shell to analyze, filter, and summarize [SOS logs](#sos-scripts).
## GitLab Detective
[GitLab Detective](https://gitlab.com/gitlab-com/support/toolbox/gitlab-detective)
runs automated checks on a GitLab installation to identify and resolve common issues.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Diagnostics tools
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
These are some of the diagnostics tools the GitLab Support team uses during troubleshooting.
They are listed here for transparency, and for users with experience
with troubleshooting GitLab. If you are currently having an issue with GitLab, you
may want to check your [support options](https://about.gitlab.com/support/) first,
before attempting to use these tools.
## SOS scripts
- [`gitlabsos`](https://gitlab.com/gitlab-com/support/toolbox/gitlabsos/)
gathers information and recent logs from a Linux package or Docker-based GitLab instance
and its operating system.
The Linux package and Docker image for GitLab versions 18.3 and up bundle `gitlabsos`:
```shell
sudo gitlabsos
```
- [`kubesos`](https://gitlab.com/gitlab-com/support/toolbox/kubesos/)
gathers k8s cluster configuration and recent logs from a GitLab Helm chart deployment.
- [`gitlab:db:sos`](../raketasks/maintenance.md#collect-information-and-statistics-about-the-database)
gathers detailed diagnostic data about your database.
## strace-parser
[`strace-parser`](https://gitlab.com/gitlab-com/support/toolbox/strace-parser)
analyzes and summarize raw `strace` data.
The [`strace` zine](https://wizardzines.com/zines/strace/) is recommended for context.
## `gitlabrb_sanitizer`
[1](https://gitlab.com/gitlab-com/support/toolbox/gitlabrb_sanitizer/) outputs a copy of `/etc/gitlab/gitlab.rb` content with sensitive values redacted.
The Linux package and Docker image for GitLab versions 18.3 and up
bundle `gitlabrb_sanitizer` with `gitlabsos`. `gitlabsos` automatically uses it to
sanitize the configuration.
## `fast-stats`
[`fast-stats`](https://gitlab.com/gitlab-com/support/toolbox/fast-stats#fast-stats)
summarizes errors and resource-intensive usage statistics quickly,
to help debug performance and configuration problems.
`fast-stats` is particularly useful to parse and compare large volumes of logs,
or to start troubleshooting unknown problems.
The Linux package and Docker image for GitLab versions 18.3 and up include `fast-stats`:
```shell
/opt/gitlab/embedded/bin/fast-stats
```
## `greenhat`
[`greenhat`](https://gitlab.com/gitlab-com/support/toolbox/greenhat/)
provides an interactive shell to analyze, filter, and summarize [SOS logs](#sos-scripts).
## GitLab Detective
[GitLab Detective](https://gitlab.com/gitlab-com/support/toolbox/gitlab-detective)
runs automated checks on a GitLab installation to identify and resolve common issues.
|
https://docs.gitlab.com/administration/linux_cheat_sheet
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/linux_cheat_sheet.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
linux_cheat_sheet.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Linux cheat sheet
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the GitLab Support Team's collection of information regarding Linux, that they
sometimes use while troubleshooting. It is listed here for transparency,
and for users with experience with Linux. If you are currently
having an issue with GitLab, you may want to check your [support options](https://about.gitlab.com/support/)
first, before attempting to use this information.
{{< alert type="warning" >}}
It is [beyond the scope of GitLab Support to assist in systems administration](https://about.gitlab.com/support/statement-of-support/#training). GitLab administrators are expected to know these commands for their distribution
of choice. If you are a GitLab Support Engineer, consider this a cross-reference to
translate `yum` -> `apt-get` and the like.
{{< /alert >}}
Most of the commands below have not been labeled as to which distribution they work
on. Contributions are welcome to help add them.
## System Commands
### Distribution Information
```shell
# Debian/Ubuntu
uname -a
lsb_release -a
# CentOS/RedHat
cat /etc/centos-release
cat /etc/redhat-release
# This will provide a lot more information
cat /etc/os-release
```
### Shut down or Reboot
```shell
shutdown -h now
reboot
```
### Permissions
```shell
# change the user:group ownership of a file/dir
chown root:git <file_or_dir>
# make a file executable
chmod u+x <file>
```
### Files and directories
```shell
# create a new directory and all subdirectories
mkdir -p dir/dir2/dir3
# Send a command's output to file.txt, no STDOUT
ls > file.txt
# Send a command's output to file.txt AND see it in STDOUT
ls | tee /tmp/file.txt
# Search and Replace within a file
sed -i 's/original-text/new-text/g' <filename>
```
### See all set environment variables
```shell
env
```
## Searching
### Filenames
```shell
# search for a file in a filesystem
find . -name 'filename.rb' -print
# locate a file
locate <filename>
# see command history
history
# search CLI history
<ctrl>-R
```
### File contents
```shell
# -B/A = show 2 lines before/after search_term
grep -B 2 -A 2 search_term <filename>
# -<number> shows both before and after
grep -2 search_term <filename>
# Search on all files in directory (recursively)
grep -r search_term <directory>
# Grep namespace/project/name of a GitLab repository
grep 'fullpath' /var/opt/gitlab/git-data/repositories/@hashed/<repo hash>/.git/config
# search through *.gz files is the same except with zgrep
zgrep search_term <filename>
# Fast grep printing lines containing a string pattern
fgrep -R string_pattern <filename or directory>
```
### CLI
```shell
# View command history
history
# Run last command that started with 'his' (3 letters min)
!his
# Search through command history
<ctrl>-R
# Execute last command with sudo
sudo !!
```
## Managing resources
### Memory, Disk, & CPU usage
```shell
# disk space info. The '-h' gives the data in human-readable values
df -h
# size of each file/dir and its contents in the current dir
du -hd 1
# or alternative
du -h --max-depth=1
# find files greater than certain size(k, M, G) and list them in order
# get rid of the + for exact, - for less than
find / -type f -size +100M -print0 | xargs -0 du -hs | sort -h
# Find free memory on a system
free -m
# Find what processes are using memory/CPU and organize by it
# Load average is 1/CPU for 1, 5, and 15 minutes
top -o %MEM
top -o %CPU
```
### Strace
```shell
# strace a process
strace -tt -T -f -y -yy -s 1024 -p <pid>
# -tt print timestamps with microsecond accuracy
# -T print the time spent in each syscall
# -f also trace any child processes that forked
# -y print the path associated with file handles
# -yy print socket and device file handle details
# -s max string length to print for an event
# -o output file
# run strace on all puma processes
ps auwx | grep puma | awk '{ print " -p " $2}' | xargs strace -tt -T -f -y -yy -s 1024 -o /tmp/puma.txt
```
Be aware that strace can have major impacts to system performance when it is running.
#### Strace Resources
- See the [strace zine](https://wizardzines.com/zines/strace/) for a quick walkthrough.
- Brendan Gregg has a more detailed explanation of [how to use strace](http://www.brendangregg.com/blog/2014-05-11/strace-wow-much-syscall.html).
- We have a [series of GitLab Unfiltered videos](https://www.youtube.com/playlist?list=PL05JrBw4t0KoC7cIkoAFcRhr4gsVesekg) on using strace to understand GitLab.
### The Strace Parser tool
Our [strace-parser tool](https://gitlab.com/wchandler/strace-parser) can be used to
provide a high level summary of the `strace` output. It is similar to `strace -C`,
but provides much more detailed statistics.
MacOS and Linux binaries [are available](https://gitlab.com/gitlab-com/support/toolbox/strace-parser/-/tags),
or you can build it from source if you have the Rust compiler.
#### How to use the tool
First run the tool with `summary` flag to get a summary of the top processes sorted by time spent actively performing tasks.
You can also sort based on total time, # of system calls made, PID #, and # of child processes
using the `-s` or `--sort` flag. The number of results defaults to 25 processes, but
can be changed using the `-c`/`--count` option. See `--help` for full details.
```shell
$ ./strace-parser sidekiq_trace.txt summary -c15 -s=pid
Top 15 PIDs by PID #
-----------
pid actv (ms) wait (ms) user (ms) total (ms) % of actv syscalls children
------- ---------- ---------- ---------- ---------- --------- --------- ---------
16706 0.000 0.000 0.000 0.000 0.00% 0 0
16708 0.000 0.000 0.000 0.000 0.00% 0 0
16716 0.000 0.000 0.000 0.000 0.00% 0 0
16717 0.000 0.000 0.000 0.000 0.00% 0 0
16718 0.000 0.000 0.000 0.000 0.00% 0 0
16719 0.000 0.000 0.000 0.000 0.00% 0 0
16720 0.389 9796.434 1.090 9797.912 0.02% 16 0
16721 0.000 0.000 0.000 0.000 0.00% 0 0
16722 0.000 0.000 0.000 0.000 0.00% 0 0
16723 0.000 0.000 0.000 0.000 0.00% 0 0
16804 0.218 11099.535 1.881 11101.634 0.01% 36 0
16813 0.000 0.000 0.000 0.000 0.00% 0 0
16814 1.740 11825.640 4.616 11831.996 0.10% 57 0
16815 2.364 12039.993 7.669 12050.026 0.14% 80 0
16816 0.000 0.000 0.000 0.000 0.00% 0 0
PIDs 93
real 0m12.287s
user 0m1.474s
sys 0m1.686s
```
Based on the summary, you can then view the details of system calls made by one or more
processes using the `-p`/`--pid` for a specific process, or `-s`/`--stats` flags for
a sorted list. `--stats` takes the same sorting and count options as summary.
```shell
./strace-parser sidekiq_trace.txt p 16815
PID 16815
80 syscalls, active time: 2.364ms, user time: 7.669ms, total time: 12050.026ms
start time: 22:46:14.830267 end time: 22:46:26.880293
syscall count total (ms) max (ms) avg (ms) min (ms) errors
----------------- -------- ---------- ---------- ---------- ---------- --------
futex 5 10100.229 5400.106 2020.046 0.022 ETIMEDOUT: 2
restart_syscall 1 1939.764 1939.764 1939.764 1939.764 ETIMEDOUT: 1
getpid 33 1.020 0.046 0.031 0.018
clock_gettime 14 0.420 0.038 0.030 0.021
stat 6 0.277 0.072 0.046 0.031
read 6 0.170 0.036 0.028 0.020
openat 3 0.126 0.045 0.042 0.038
close 3 0.099 0.034 0.033 0.031
lseek 3 0.089 0.035 0.030 0.021
ioctl 3 0.082 0.033 0.027 0.023 ENOTTY: 3
fstat 3 0.081 0.034 0.027 0.022
---------------
Slowest file open times for PID 16815:
dur (ms) timestamp error filename
---------- --------------- --------------- ---------
0.045 22:46:16.771318 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
0.043 22:46:26.877954 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
0.038 22:46:22.174610 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
```
In the previous example, we can see which files took longer to open for `PID 16815`.
When nothing stands out in the results, a good way to get more context is to run `strace`
on your own GitLab instance while performing the action performed by the customer,
then compare summaries of both results and dive into the differences.
#### Stats for the open syscall
Rough numbers for calls to `open` and `openat` (used to access files) on various configurations.
Slow storage can cause the dreaded `DeadlineExceeded` error in Gitaly.
Also [see this entry](../operations/filesystem_benchmarking.md)
in the handbook for quick tests customers can perform to check their file system performance.
Keep in mind that timing information from `strace` is often somewhat inaccurate, so
small differences should not be considered significant.
|Setup | access times |
|:--------------|:--------------|
| EFS | 10 - 30 ms |
| Local Storage | 0.01 - 1 ms |
## Networking
### Ports
```shell
# Find the programs that are listening on ports
netstat -plnt
ss -plnt
lsof -i -P | grep <port>
```
### Internet/DNS
```shell
# Show domain IP address
dig +short example.com
nslookup example.com
# Check DNS using specific nameserver
# 8.8.8.8 = google, 1.1.1.1 = cloudflare, 208.67.222.222 = opendns
dig @8.8.8.8 example.com
nslookup example.com 1.1.1.1
# Find host provider
whois <ip_address> | grep -i "orgname\|netname"
# Curl headers with redirect
curl --head --location "https://example.com"
# Test if a host is reachable on the network. `ping6` works on IPv6 networks.
ping example.com
# Show the route taken to a host. `traceroute6` works on IPv6 networks.
traceroute example.com
mtr example.com
# List details of network interfaces
ip address
# Check local DNS settings
cat /etc/hosts
cat /etc/resolv.conf
systemd-resolve --status
# Capture traffic to/from a host
sudo tcpdump host www.example.com
```
## Package Management
```shell
# Debian/Ubuntu
# List packages
dpkg -l
apt list --installed
# Find an installed package
dpkg -l | grep <package>
apt list --installed | grep <package>
# Install a package
dpkg -i <package_name>.deb
apt-get install <package>
apt install <package>
# CentOS/RedHat
# Install a package
yum install <package>
dnf install <package> # RHEL/CentOS 8+
rpm -ivh <package_name>.rpm
# Find an installed package
rpm -qa | grep <package>
```
## Logs
```shell
# Print last lines in log file where 'n'
# is the number of lines to print
tail -n /path/to/log/file
```
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Linux cheat sheet
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the GitLab Support Team's collection of information regarding Linux, that they
sometimes use while troubleshooting. It is listed here for transparency,
and for users with experience with Linux. If you are currently
having an issue with GitLab, you may want to check your [support options](https://about.gitlab.com/support/)
first, before attempting to use this information.
{{< alert type="warning" >}}
It is [beyond the scope of GitLab Support to assist in systems administration](https://about.gitlab.com/support/statement-of-support/#training). GitLab administrators are expected to know these commands for their distribution
of choice. If you are a GitLab Support Engineer, consider this a cross-reference to
translate `yum` -> `apt-get` and the like.
{{< /alert >}}
Most of the commands below have not been labeled as to which distribution they work
on. Contributions are welcome to help add them.
## System Commands
### Distribution Information
```shell
# Debian/Ubuntu
uname -a
lsb_release -a
# CentOS/RedHat
cat /etc/centos-release
cat /etc/redhat-release
# This will provide a lot more information
cat /etc/os-release
```
### Shut down or Reboot
```shell
shutdown -h now
reboot
```
### Permissions
```shell
# change the user:group ownership of a file/dir
chown root:git <file_or_dir>
# make a file executable
chmod u+x <file>
```
### Files and directories
```shell
# create a new directory and all subdirectories
mkdir -p dir/dir2/dir3
# Send a command's output to file.txt, no STDOUT
ls > file.txt
# Send a command's output to file.txt AND see it in STDOUT
ls | tee /tmp/file.txt
# Search and Replace within a file
sed -i 's/original-text/new-text/g' <filename>
```
### See all set environment variables
```shell
env
```
## Searching
### Filenames
```shell
# search for a file in a filesystem
find . -name 'filename.rb' -print
# locate a file
locate <filename>
# see command history
history
# search CLI history
<ctrl>-R
```
### File contents
```shell
# -B/A = show 2 lines before/after search_term
grep -B 2 -A 2 search_term <filename>
# -<number> shows both before and after
grep -2 search_term <filename>
# Search on all files in directory (recursively)
grep -r search_term <directory>
# Grep namespace/project/name of a GitLab repository
grep 'fullpath' /var/opt/gitlab/git-data/repositories/@hashed/<repo hash>/.git/config
# search through *.gz files is the same except with zgrep
zgrep search_term <filename>
# Fast grep printing lines containing a string pattern
fgrep -R string_pattern <filename or directory>
```
### CLI
```shell
# View command history
history
# Run last command that started with 'his' (3 letters min)
!his
# Search through command history
<ctrl>-R
# Execute last command with sudo
sudo !!
```
## Managing resources
### Memory, Disk, & CPU usage
```shell
# disk space info. The '-h' gives the data in human-readable values
df -h
# size of each file/dir and its contents in the current dir
du -hd 1
# or alternative
du -h --max-depth=1
# find files greater than certain size(k, M, G) and list them in order
# get rid of the + for exact, - for less than
find / -type f -size +100M -print0 | xargs -0 du -hs | sort -h
# Find free memory on a system
free -m
# Find what processes are using memory/CPU and organize by it
# Load average is 1/CPU for 1, 5, and 15 minutes
top -o %MEM
top -o %CPU
```
### Strace
```shell
# strace a process
strace -tt -T -f -y -yy -s 1024 -p <pid>
# -tt print timestamps with microsecond accuracy
# -T print the time spent in each syscall
# -f also trace any child processes that forked
# -y print the path associated with file handles
# -yy print socket and device file handle details
# -s max string length to print for an event
# -o output file
# run strace on all puma processes
ps auwx | grep puma | awk '{ print " -p " $2}' | xargs strace -tt -T -f -y -yy -s 1024 -o /tmp/puma.txt
```
Be aware that strace can have major impacts to system performance when it is running.
#### Strace Resources
- See the [strace zine](https://wizardzines.com/zines/strace/) for a quick walkthrough.
- Brendan Gregg has a more detailed explanation of [how to use strace](http://www.brendangregg.com/blog/2014-05-11/strace-wow-much-syscall.html).
- We have a [series of GitLab Unfiltered videos](https://www.youtube.com/playlist?list=PL05JrBw4t0KoC7cIkoAFcRhr4gsVesekg) on using strace to understand GitLab.
### The Strace Parser tool
Our [strace-parser tool](https://gitlab.com/wchandler/strace-parser) can be used to
provide a high level summary of the `strace` output. It is similar to `strace -C`,
but provides much more detailed statistics.
MacOS and Linux binaries [are available](https://gitlab.com/gitlab-com/support/toolbox/strace-parser/-/tags),
or you can build it from source if you have the Rust compiler.
#### How to use the tool
First run the tool with `summary` flag to get a summary of the top processes sorted by time spent actively performing tasks.
You can also sort based on total time, # of system calls made, PID #, and # of child processes
using the `-s` or `--sort` flag. The number of results defaults to 25 processes, but
can be changed using the `-c`/`--count` option. See `--help` for full details.
```shell
$ ./strace-parser sidekiq_trace.txt summary -c15 -s=pid
Top 15 PIDs by PID #
-----------
pid actv (ms) wait (ms) user (ms) total (ms) % of actv syscalls children
------- ---------- ---------- ---------- ---------- --------- --------- ---------
16706 0.000 0.000 0.000 0.000 0.00% 0 0
16708 0.000 0.000 0.000 0.000 0.00% 0 0
16716 0.000 0.000 0.000 0.000 0.00% 0 0
16717 0.000 0.000 0.000 0.000 0.00% 0 0
16718 0.000 0.000 0.000 0.000 0.00% 0 0
16719 0.000 0.000 0.000 0.000 0.00% 0 0
16720 0.389 9796.434 1.090 9797.912 0.02% 16 0
16721 0.000 0.000 0.000 0.000 0.00% 0 0
16722 0.000 0.000 0.000 0.000 0.00% 0 0
16723 0.000 0.000 0.000 0.000 0.00% 0 0
16804 0.218 11099.535 1.881 11101.634 0.01% 36 0
16813 0.000 0.000 0.000 0.000 0.00% 0 0
16814 1.740 11825.640 4.616 11831.996 0.10% 57 0
16815 2.364 12039.993 7.669 12050.026 0.14% 80 0
16816 0.000 0.000 0.000 0.000 0.00% 0 0
PIDs 93
real 0m12.287s
user 0m1.474s
sys 0m1.686s
```
Based on the summary, you can then view the details of system calls made by one or more
processes using the `-p`/`--pid` for a specific process, or `-s`/`--stats` flags for
a sorted list. `--stats` takes the same sorting and count options as summary.
```shell
./strace-parser sidekiq_trace.txt p 16815
PID 16815
80 syscalls, active time: 2.364ms, user time: 7.669ms, total time: 12050.026ms
start time: 22:46:14.830267 end time: 22:46:26.880293
syscall count total (ms) max (ms) avg (ms) min (ms) errors
----------------- -------- ---------- ---------- ---------- ---------- --------
futex 5 10100.229 5400.106 2020.046 0.022 ETIMEDOUT: 2
restart_syscall 1 1939.764 1939.764 1939.764 1939.764 ETIMEDOUT: 1
getpid 33 1.020 0.046 0.031 0.018
clock_gettime 14 0.420 0.038 0.030 0.021
stat 6 0.277 0.072 0.046 0.031
read 6 0.170 0.036 0.028 0.020
openat 3 0.126 0.045 0.042 0.038
close 3 0.099 0.034 0.033 0.031
lseek 3 0.089 0.035 0.030 0.021
ioctl 3 0.082 0.033 0.027 0.023 ENOTTY: 3
fstat 3 0.081 0.034 0.027 0.022
---------------
Slowest file open times for PID 16815:
dur (ms) timestamp error filename
---------- --------------- --------------- ---------
0.045 22:46:16.771318 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
0.043 22:46:26.877954 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
0.038 22:46:22.174610 - /opt/gitlab/embedded/service/gitlab-rails/config/database.yml
```
In the previous example, we can see which files took longer to open for `PID 16815`.
When nothing stands out in the results, a good way to get more context is to run `strace`
on your own GitLab instance while performing the action performed by the customer,
then compare summaries of both results and dive into the differences.
#### Stats for the open syscall
Rough numbers for calls to `open` and `openat` (used to access files) on various configurations.
Slow storage can cause the dreaded `DeadlineExceeded` error in Gitaly.
Also [see this entry](../operations/filesystem_benchmarking.md)
in the handbook for quick tests customers can perform to check their file system performance.
Keep in mind that timing information from `strace` is often somewhat inaccurate, so
small differences should not be considered significant.
|Setup | access times |
|:--------------|:--------------|
| EFS | 10 - 30 ms |
| Local Storage | 0.01 - 1 ms |
## Networking
### Ports
```shell
# Find the programs that are listening on ports
netstat -plnt
ss -plnt
lsof -i -P | grep <port>
```
### Internet/DNS
```shell
# Show domain IP address
dig +short example.com
nslookup example.com
# Check DNS using specific nameserver
# 8.8.8.8 = google, 1.1.1.1 = cloudflare, 208.67.222.222 = opendns
dig @8.8.8.8 example.com
nslookup example.com 1.1.1.1
# Find host provider
whois <ip_address> | grep -i "orgname\|netname"
# Curl headers with redirect
curl --head --location "https://example.com"
# Test if a host is reachable on the network. `ping6` works on IPv6 networks.
ping example.com
# Show the route taken to a host. `traceroute6` works on IPv6 networks.
traceroute example.com
mtr example.com
# List details of network interfaces
ip address
# Check local DNS settings
cat /etc/hosts
cat /etc/resolv.conf
systemd-resolve --status
# Capture traffic to/from a host
sudo tcpdump host www.example.com
```
## Package Management
```shell
# Debian/Ubuntu
# List packages
dpkg -l
apt list --installed
# Find an installed package
dpkg -l | grep <package>
apt list --installed | grep <package>
# Install a package
dpkg -i <package_name>.deb
apt-get install <package>
apt install <package>
# CentOS/RedHat
# Install a package
yum install <package>
dnf install <package> # RHEL/CentOS 8+
rpm -ivh <package_name>.rpm
# Find an installed package
rpm -qa | grep <package>
```
## Logs
```shell
# Print last lines in log file where 'n'
# is the number of lines to print
tail -n /path/to/log/file
```
|
https://docs.gitlab.com/administration/test_environments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/test_environments.md
|
2025-08-13
|
doc/administration/troubleshooting
|
[
"doc",
"administration",
"troubleshooting"
] |
test_environments.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Apps for a testing environment
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the GitLab Support Team's collection of information regarding testing environments,
for use while troubleshooting. It is listed here for transparency, and it may be useful
for users with experience with these tools. If you are currently having an issue with
GitLab, you may want to check your [support options](https://about.gitlab.com/support/)
first, before attempting to use this information.
{{< alert type="note" >}}
This page was initially written for Support Engineers, so some of the links
are only available internally at GitLab.
{{< /alert >}}
## Docker
The following were tested on Docker containers running in the cloud. Support Engineers,
see [these docs](https://gitlab.com/gitlab-com/dev-resources/tree/master/dev-resources#running-docker-containers)
on how to run Docker containers on `dev-resources`. Other setups haven't been tested,
but contributions are welcome.
### GitLab
See [our official Docker installation method](../../install/docker/_index.md)
for how to run GitLab on Docker.
### SAML
#### SAML for Authentication
In the following examples, when replacing `<GITLAB_IP_OR_DOMAIN>` and `<SAML_IP_OR_DOMAIN>` it is important to prepend your IP or domain name, with the protocol (`http://` or `https://`) being used.
We can use the [`test-saml-idp` Docker image](https://hub.docker.com/r/jamedjo/test-saml-idp)
to do the work for us:
```shell
docker run --name gitlab_saml -p 8080:8080 -p 8443:8443 \
-e SIMPLESAMLPHP_SP_ENTITY_ID=<GITLAB_IP_OR_DOMAIN> \
-e SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE=<GITLAB_IP_OR_DOMAIN>/users/auth/saml/callback \
-d jamedjo/test-saml-idp
```
The following must also go in your `/etc/gitlab/gitlab.rb`. See [our SAML docs](../../integration/saml.md)
for more, as well as the list of [default usernames, passwords, and emails](https://hub.docker.com/r/jamedjo/test-saml-idp/#usage).
```ruby
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['saml']
gitlab_rails['omniauth_sync_email_from_provider'] = 'saml'
gitlab_rails['omniauth_sync_profile_from_provider'] = ['saml']
gitlab_rails['omniauth_sync_profile_attributes'] = ['email']
gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'saml'
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['omniauth_auto_link_ldap_user'] = false
gitlab_rails['omniauth_auto_link_saml_user'] = true
gitlab_rails['omniauth_providers'] = [
{
"name" => "saml",
"label" => "SAML",
"args" => {
assertion_consumer_service_url: '<GITLAB_IP_OR_DOMAIN>/users/auth/saml/callback',
idp_cert_fingerprint: '119b9e027959cdb7c662cfd075d9e2ef384e445f',
idp_sso_target_url: '<SAML_IP_OR_DOMAIN>:8080/simplesaml/saml2/idp/SSOService.php',
issuer: '<GITLAB_IP_OR_DOMAIN>',
name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
}
}
]
```
#### GroupSAML for GitLab.com
See [the GDK SAML documentation](https://gitlab.com/gitlab-org/gitlab-development-kit/blob/main/doc/howto/saml.md).
### Elasticsearch
```shell
docker run -d --name elasticsearch \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" \
docker.elastic.co/elasticsearch/elasticsearch:5.5.1
```
Then confirm it works in the browser at `curl "http://<IP_ADDRESS>:9200/_cat/health"`.
In Elasticsearch, the default username is `elastic`, and the default password is `changeme`.
### Kroki
See [our Kroki docs](../integration/kroki.md#docker)
on running Kroki in Docker.
### PlantUML
See [our PlantUML docs](../integration/plantuml.md#docker)
on running PlantUML in Docker.
### Jira
```shell
docker run -d -p 8081:8080 cptactionhank/atlassian-jira:latest
```
Then go to `<IP_ADDRESS>:8081` in the browser to set it up. This requires a
Jira license.
### Grafana
```shell
docker run -d --name grafana -e "GF_SECURITY_ADMIN_PASSWORD=gitlab" -p 3000:3000 grafana/grafana
```
Access it at `<IP_ADDRESS>:3000`.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Apps for a testing environment
breadcrumbs:
- doc
- administration
- troubleshooting
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the GitLab Support Team's collection of information regarding testing environments,
for use while troubleshooting. It is listed here for transparency, and it may be useful
for users with experience with these tools. If you are currently having an issue with
GitLab, you may want to check your [support options](https://about.gitlab.com/support/)
first, before attempting to use this information.
{{< alert type="note" >}}
This page was initially written for Support Engineers, so some of the links
are only available internally at GitLab.
{{< /alert >}}
## Docker
The following were tested on Docker containers running in the cloud. Support Engineers,
see [these docs](https://gitlab.com/gitlab-com/dev-resources/tree/master/dev-resources#running-docker-containers)
on how to run Docker containers on `dev-resources`. Other setups haven't been tested,
but contributions are welcome.
### GitLab
See [our official Docker installation method](../../install/docker/_index.md)
for how to run GitLab on Docker.
### SAML
#### SAML for Authentication
In the following examples, when replacing `<GITLAB_IP_OR_DOMAIN>` and `<SAML_IP_OR_DOMAIN>` it is important to prepend your IP or domain name, with the protocol (`http://` or `https://`) being used.
We can use the [`test-saml-idp` Docker image](https://hub.docker.com/r/jamedjo/test-saml-idp)
to do the work for us:
```shell
docker run --name gitlab_saml -p 8080:8080 -p 8443:8443 \
-e SIMPLESAMLPHP_SP_ENTITY_ID=<GITLAB_IP_OR_DOMAIN> \
-e SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE=<GITLAB_IP_OR_DOMAIN>/users/auth/saml/callback \
-d jamedjo/test-saml-idp
```
The following must also go in your `/etc/gitlab/gitlab.rb`. See [our SAML docs](../../integration/saml.md)
for more, as well as the list of [default usernames, passwords, and emails](https://hub.docker.com/r/jamedjo/test-saml-idp/#usage).
```ruby
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['saml']
gitlab_rails['omniauth_sync_email_from_provider'] = 'saml'
gitlab_rails['omniauth_sync_profile_from_provider'] = ['saml']
gitlab_rails['omniauth_sync_profile_attributes'] = ['email']
gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'saml'
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['omniauth_auto_link_ldap_user'] = false
gitlab_rails['omniauth_auto_link_saml_user'] = true
gitlab_rails['omniauth_providers'] = [
{
"name" => "saml",
"label" => "SAML",
"args" => {
assertion_consumer_service_url: '<GITLAB_IP_OR_DOMAIN>/users/auth/saml/callback',
idp_cert_fingerprint: '119b9e027959cdb7c662cfd075d9e2ef384e445f',
idp_sso_target_url: '<SAML_IP_OR_DOMAIN>:8080/simplesaml/saml2/idp/SSOService.php',
issuer: '<GITLAB_IP_OR_DOMAIN>',
name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
}
}
]
```
#### GroupSAML for GitLab.com
See [the GDK SAML documentation](https://gitlab.com/gitlab-org/gitlab-development-kit/blob/main/doc/howto/saml.md).
### Elasticsearch
```shell
docker run -d --name elasticsearch \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" \
docker.elastic.co/elasticsearch/elasticsearch:5.5.1
```
Then confirm it works in the browser at `curl "http://<IP_ADDRESS>:9200/_cat/health"`.
In Elasticsearch, the default username is `elastic`, and the default password is `changeme`.
### Kroki
See [our Kroki docs](../integration/kroki.md#docker)
on running Kroki in Docker.
### PlantUML
See [our PlantUML docs](../integration/plantuml.md#docker)
on running PlantUML in Docker.
### Jira
```shell
docker run -d -p 8081:8080 cptactionhank/atlassian-jira:latest
```
Then go to `<IP_ADDRESS>:8081` in the browser to set it up. This requires a
Jira license.
### Grafana
```shell
docker run -d --name grafana -e "GF_SECURITY_ADMIN_PASSWORD=gitlab" -p 3000:3000 grafana/grafana
```
Access it at `<IP_ADDRESS>:3000`.
|
https://docs.gitlab.com/administration/3k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/3k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
3k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 60 RPS or 3,000 users
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 60 requests per second (RPS), the typical peak load of up to 3,000 users, both manual and automated, based on real data.
This architecture is the smallest one available with HA built in. If you require HA but
have a lower user count or total load the [Supported Modifications for lower user counts](#supported-modifications-for-lower-user-counts-ha)
section details how to reduce this architecture's size while maintaining HA.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS
- **High Availability**: Yes, although [Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with).
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|--------------|----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 2 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D2s v3` |
| GitLab Rails<sup>8</sup> | 3 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` | `F8s v2` |
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 3k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x2" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "Redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 60 RPS / 3k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 60 RPS |
| Web | 6 RPS |
| Git (Pull) | 6 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance Considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 60 RPS or 3,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul/Sentinel 1
- `10.6.0.12`: Consul/Sentinel 2
- `10.6.0.13`: Consul/Sentinel 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.20`: Internal Load Balancer
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
- `10.6.0.51`: Gitaly 1
- `10.6.0.52`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
- `10.6.0.41`: GitLab application 1
- `10.6.0.42`: GitLab application 2
- `10.6.0.43`: GitLab application 3
- `10.6.0.81`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you are guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux GitLab package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you use the default
username of `gitlab` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you use the default
username of `pgbouncer` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you use the default
username of `gitlab_replicator` (recommended). The command requests a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you use the default
username of `gitlab-consul` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, defaults to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs are used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
pgbouncer_exporter['listen_address'] = '0.0.0.0:9188'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. Ensure each node is talking to the current master:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
If there is an error `psql: ERROR: Auth failed` after typing in the
password, ensure you previously generated the MD5 password hashes with the correct
format. The correct format is to concatenate the password and the username:
`PASSWORDUSERNAME`. For example, `Sup3rS3cr3tpgbouncer` would be the text
needed to generate an MD5 password hash for the `pgbouncer` user.
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31530) 77150s; run: log: (pid 31106) 77182s
run: logrotate: (pid 32613) 3357s; run: log: (pid 30107) 77500s
run: node-exporter: (pid 31550) 77149s; run: log: (pid 30138) 77493s
run: pgbouncer: (pid 32033) 75593s; run: log: (pid 31117) 77175s
run: pgbouncer-exporter: (pid 31558) 77148s; run: log: (pid 31498) 77156s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis cluster
This is the section where we install and set up the new Redis instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database. However, if you are using Geo, separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup don't have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect via a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on the GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# ...
#
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
# Gitaly Auth Token
# Should be the same as praefect_internal_token
auth: {
# ...
token: '<praefect_internal_token>',
},
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
pack_objects_cache: {
# ...
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the master node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379},
]
# Gitaly Cluster
## repositories_storages gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30114) 77353s; run: log: (pid 29756) 77367s
run: logrotate: (pid 9898) 3561s; run: log: (pid 29653) 77380s
run: node-exporter: (pid 30134) 77353s; run: log: (pid 29706) 77372s
run: sidekiq: (pid 30142) 77351s; run: log: (pid 29638) 77386s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the Redis primary node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379}
]
## Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
sidekiq['listen_address'] = "0.0.0.0"
puma['listen'] = '0.0.0.0'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
# Object storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 4890) 8647s; run: log: (pid 29962) 79128s
run: gitlab-exporter: (pid 4902) 8647s; run: log: (pid 29913) 79134s
run: gitlab-workhorse: (pid 4904) 8646s; run: log: (pid 29713) 79155s
run: logrotate: (pid 12425) 1446s; run: log: (pid 29798) 79146s
run: nginx: (pid 4925) 8646s; run: log: (pid 29726) 79152s
run: node-exporter: (pid 4931) 8645s; run: log: (pid 29855) 79140s
run: puma: (pid 4936) 8645s; run: log: (pid 29656) 79161s
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Ensure that all migrations ran:
```shell
gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31637) 17337s; run: log: (pid 29748) 78432s
run: logrotate: (pid 31809) 2936s; run: log: (pid 29581) 78462s
run: nginx: (pid 31665) 17335s; run: log: (pid 29556) 78468s
run: prometheus: (pid 31672) 17335s; run: log: (pid 29633) 78456s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the need to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Supported modifications for lower user counts (HA)
The 60 RPS or 3,000 users GitLab reference architecture is the smallest we recommend that achieves High Availability (HA).
However, for environments that must serve fewer users or a lower RPS but maintain HA, there are several
supported modifications you can make to this architecture to reduce complexity and cost.
It should be noted that to achieve HA with GitLab, the 60 RPS or 3,000 users architecture's makeup is ultimately what is
required. Each component has various considerations and rules to follow, and the architecture
meets all of these. Smaller versions of this architecture will be fundamentally the same,
but with smaller performance requirements, the following modifications are supported as follows:
{{< alert type="note" >}}
If not stated below, no other modifications are supported for lower use counts.
{{< /alert >}}
- Lowering node specs: Depending on your user count, you can lower all suggested node specs as desired. However, it's recommended that you don't go lower than the [general requirements](../../install/requirements.md).
- Combining select nodes: The following specific components are supported to be combined onto the same nodes to reduce complexity at the cost of some performance:
- GitLab Rails and Sidekiq: Sidekiq nodes can be removed, and the component instead enabled on the GitLab Rails nodes.
- PostgreSQL and PgBouncer: PgBouncer nodes could be removed and instead be enabled on PostgreSQL nodes with the Internal Load Balancer pointing to them. However, to enable [Database Load Balancing](../postgresql/database_load_balancing.md), a separate PgBouncer array is still required.
- Reducing the node counts: Some node types do not need consensus and can run with fewer nodes (but more than one for redundancy):
- GitLab Rails and Sidekiq: Stateless services don't have a minimum node count. Two are enough for redundancy.
- PostgreSQL and PgBouncer: A quorum is not strictly necessary. Two PostgreSQL nodes and two PgBouncer nodes are enough for redundancy.
- Consul, Redis Sentinel, and Praefect: Require an odd number, and a minimum of three nodes, for a voting quorum.
- Running select components in reputable Cloud PaaS solutions: The following specific components are supported to be run on reputable Cloud Provider PaaS solutions. By doing this, additional dependent components can also be removed:
- PostgreSQL: Can be run on reputable Cloud PaaS solutions such as Google Cloud SQL or Amazon RDS. In this setup, the PgBouncer and Consul nodes are no longer required:
- Consul may still be desired if [Prometheus](../monitoring/prometheus/_index.md) auto discovery is a requirement, otherwise you must [manually add scrape configurations](../monitoring/prometheus/_index.md#adding-custom-scrape-configurations) for all nodes.
- Redis: Can be run on reputable Cloud PaaS solutions such as Google Memorystore and AWS ElastiCache. In this setup, the Redis Sentinel is no longer required.
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 16 vCPU<br/>20 GB memory (request)<br/>28 GB memory (limit) | 2 x `n1-standard-16` | 2 x `c5.4xlarge` |
| Sidekiq | 7.2 vCPU<br/>16 GB memory (request)<br/>32 GB memory (limit) | 3 x `n1-standard-4` | 3 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|-------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 3k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 60 RPS or 3,000 users we recommend a total Puma worker count of around 16 so in turn it's recommended to run at
least 4 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This allows the controllers to scale dynamically with the Webservice pods they serve, and takes advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 8 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts for the 60 RPS or 3,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/3k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 60 RPS or 3,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 60 requests per second (RPS), the typical peak load of up to 3,000 users, both manual and automated, based on real data.
This architecture is the smallest one available with HA built in. If you require HA but
have a lower user count or total load the [Supported Modifications for lower user counts](#supported-modifications-for-lower-user-counts-ha)
section details how to reduce this architecture's size while maintaining HA.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS
- **High Availability**: Yes, although [Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with).
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|--------------|----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 2 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D2s v3` |
| GitLab Rails<sup>8</sup> | 3 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` | `F8s v2` |
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 3k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x2" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "Redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 60 RPS / 3k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 60 RPS |
| Web | 6 RPS |
| Git (Pull) | 6 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance Considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 60 RPS or 3,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul/Sentinel 1
- `10.6.0.12`: Consul/Sentinel 2
- `10.6.0.13`: Consul/Sentinel 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.20`: Internal Load Balancer
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
- `10.6.0.51`: Gitaly 1
- `10.6.0.52`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
- `10.6.0.41`: GitLab application 1
- `10.6.0.42`: GitLab application 2
- `10.6.0.43`: GitLab application 3
- `10.6.0.81`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you are guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux GitLab package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you use the default
username of `gitlab` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you use the default
username of `pgbouncer` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you use the default
username of `gitlab_replicator` (recommended). The command requests a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you use the default
username of `gitlab-consul` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, defaults to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs are used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
pgbouncer_exporter['listen_address'] = '0.0.0.0:9188'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. Ensure each node is talking to the current master:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
If there is an error `psql: ERROR: Auth failed` after typing in the
password, ensure you previously generated the MD5 password hashes with the correct
format. The correct format is to concatenate the password and the username:
`PASSWORDUSERNAME`. For example, `Sup3rS3cr3tpgbouncer` would be the text
needed to generate an MD5 password hash for the `pgbouncer` user.
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31530) 77150s; run: log: (pid 31106) 77182s
run: logrotate: (pid 32613) 3357s; run: log: (pid 30107) 77500s
run: node-exporter: (pid 31550) 77149s; run: log: (pid 30138) 77493s
run: pgbouncer: (pid 32033) 75593s; run: log: (pid 31117) 77175s
run: pgbouncer-exporter: (pid 31558) 77148s; run: log: (pid 31498) 77156s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis cluster
This is the section where we install and set up the new Redis instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database. However, if you are using Geo, separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup don't have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect via a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on the GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# ...
#
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
# Gitaly Auth Token
# Should be the same as praefect_internal_token
auth: {
# ...
token: '<praefect_internal_token>',
},
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
pack_objects_cache: {
# ...
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the master node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379},
]
# Gitaly Cluster
## repositories_storages gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30114) 77353s; run: log: (pid 29756) 77367s
run: logrotate: (pid 9898) 3561s; run: log: (pid 29653) 77380s
run: node-exporter: (pid 30134) 77353s; run: log: (pid 29706) 77372s
run: sidekiq: (pid 30142) 77351s; run: log: (pid 29638) 77386s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the Redis primary node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379}
]
## Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
sidekiq['listen_address'] = "0.0.0.0"
puma['listen'] = '0.0.0.0'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
# Object storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 4890) 8647s; run: log: (pid 29962) 79128s
run: gitlab-exporter: (pid 4902) 8647s; run: log: (pid 29913) 79134s
run: gitlab-workhorse: (pid 4904) 8646s; run: log: (pid 29713) 79155s
run: logrotate: (pid 12425) 1446s; run: log: (pid 29798) 79146s
run: nginx: (pid 4925) 8646s; run: log: (pid 29726) 79152s
run: node-exporter: (pid 4931) 8645s; run: log: (pid 29855) 79140s
run: puma: (pid 4936) 8645s; run: log: (pid 29656) 79161s
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Ensure that all migrations ran:
```shell
gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31637) 17337s; run: log: (pid 29748) 78432s
run: logrotate: (pid 31809) 2936s; run: log: (pid 29581) 78462s
run: nginx: (pid 31665) 17335s; run: log: (pid 29556) 78468s
run: prometheus: (pid 31672) 17335s; run: log: (pid 29633) 78456s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the need to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Supported modifications for lower user counts (HA)
The 60 RPS or 3,000 users GitLab reference architecture is the smallest we recommend that achieves High Availability (HA).
However, for environments that must serve fewer users or a lower RPS but maintain HA, there are several
supported modifications you can make to this architecture to reduce complexity and cost.
It should be noted that to achieve HA with GitLab, the 60 RPS or 3,000 users architecture's makeup is ultimately what is
required. Each component has various considerations and rules to follow, and the architecture
meets all of these. Smaller versions of this architecture will be fundamentally the same,
but with smaller performance requirements, the following modifications are supported as follows:
{{< alert type="note" >}}
If not stated below, no other modifications are supported for lower use counts.
{{< /alert >}}
- Lowering node specs: Depending on your user count, you can lower all suggested node specs as desired. However, it's recommended that you don't go lower than the [general requirements](../../install/requirements.md).
- Combining select nodes: The following specific components are supported to be combined onto the same nodes to reduce complexity at the cost of some performance:
- GitLab Rails and Sidekiq: Sidekiq nodes can be removed, and the component instead enabled on the GitLab Rails nodes.
- PostgreSQL and PgBouncer: PgBouncer nodes could be removed and instead be enabled on PostgreSQL nodes with the Internal Load Balancer pointing to them. However, to enable [Database Load Balancing](../postgresql/database_load_balancing.md), a separate PgBouncer array is still required.
- Reducing the node counts: Some node types do not need consensus and can run with fewer nodes (but more than one for redundancy):
- GitLab Rails and Sidekiq: Stateless services don't have a minimum node count. Two are enough for redundancy.
- PostgreSQL and PgBouncer: A quorum is not strictly necessary. Two PostgreSQL nodes and two PgBouncer nodes are enough for redundancy.
- Consul, Redis Sentinel, and Praefect: Require an odd number, and a minimum of three nodes, for a voting quorum.
- Running select components in reputable Cloud PaaS solutions: The following specific components are supported to be run on reputable Cloud Provider PaaS solutions. By doing this, additional dependent components can also be removed:
- PostgreSQL: Can be run on reputable Cloud PaaS solutions such as Google Cloud SQL or Amazon RDS. In this setup, the PgBouncer and Consul nodes are no longer required:
- Consul may still be desired if [Prometheus](../monitoring/prometheus/_index.md) auto discovery is a requirement, otherwise you must [manually add scrape configurations](../monitoring/prometheus/_index.md#adding-custom-scrape-configurations) for all nodes.
- Redis: Can be run on reputable Cloud PaaS solutions such as Google Memorystore and AWS ElastiCache. In this setup, the Redis Sentinel is no longer required.
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 16 vCPU<br/>20 GB memory (request)<br/>28 GB memory (limit) | 2 x `n1-standard-16` | 2 x `c5.4xlarge` |
| Sidekiq | 7.2 vCPU<br/>16 GB memory (request)<br/>32 GB memory (limit) | 3 x `n1-standard-4` | 3 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|-------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 3k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 60 RPS or 3,000 users we recommend a total Puma worker count of around 16 so in turn it's recommended to run at
least 4 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This allows the controllers to scale dynamically with the Webservice pods they serve, and takes advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 8 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts for the 60 RPS or 3,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/3k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/25k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/25k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
25k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 500 RPS or 25,000 users
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 500 requests per second (RPS) - The typical peak load of up to 25,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|--------------|-----------|
| External load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5n.2xlarge` | `F8s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` | `D16s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5n.2xlarge` | `F8s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` | `D32s v3` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 5 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 25k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x5" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before starting, see the [requirements](_index.md#requirements) for reference architectures.
## Testing methodology
The 500 RPS / 25k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 500 RPS |
| Web | 50 RPS |
| Git (Pull) | 50 RPS |
| Git (Push) | 10 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 500 RPS or 25,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no need to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
The Internal Load Balancer is used to balance any internal connections the GitLab environment requires
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
It's a separate node from the External Load Balancer and shouldn't have any access externally.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. These components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks
(Internet),
using a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_sentinel_role' 'redis_master_role'
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
# Port of primary Redis server for Sentinel, uncomment to change to non default.
# Defaults to `6379`.
# redis['master_port'] = 6379
# Set up password authentication for Redis (use the same password in all nodes).
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
# Must be the same in every Redis node.
redis['master_name'] = 'gitlab-redis-cache'
# The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the same contents as the primary node in the previous section replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server role as 'redis_replica_role' and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = `0.0.0.0`
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach.
# Set bind to '0.0.0.0' to listen on all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
# Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Persistent instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_master_role'
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_replica_role' and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.62:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup should not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Praefect documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object Storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the need to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 140 vCPU<br/>175 GB memory (request)<br/>245 GB memory (limit) | 5 x `n1-standard-32` | 5 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|------------------------|------------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 25k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 500 RPS or 25,000 users we recommend a total Puma worker count of around 140 so in turn it's recommended to run at
least 35 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 500 RPS or 25,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/25k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 500 RPS or 25,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 500 requests per second (RPS) - The typical peak load of up to 25,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|--------------|-----------|
| External load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5n.2xlarge` | `F8s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` | `D16s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5n.2xlarge` | `F8s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` | `D32s v3` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 5 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 25k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x5" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before starting, see the [requirements](_index.md#requirements) for reference architectures.
## Testing methodology
The 500 RPS / 25k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 500 RPS |
| Web | 50 RPS |
| Git (Pull) | 50 RPS |
| Git (Push) | 10 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 500 RPS or 25,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no need to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
The Internal Load Balancer is used to balance any internal connections the GitLab environment requires
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
It's a separate node from the External Load Balancer and shouldn't have any access externally.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. These components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks
(Internet),
using a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_sentinel_role' 'redis_master_role'
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
# Port of primary Redis server for Sentinel, uncomment to change to non default.
# Defaults to `6379`.
# redis['master_port'] = 6379
# Set up password authentication for Redis (use the same password in all nodes).
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
# Must be the same in every Redis node.
redis['master_name'] = 'gitlab-redis-cache'
# The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the same contents as the primary node in the previous section replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server role as 'redis_replica_role' and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = `0.0.0.0`
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach.
# Set bind to '0.0.0.0' to listen on all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
# Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Persistent instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_master_role'
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_replica_role' and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.62:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup should not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Praefect documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object Storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the need to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 140 vCPU<br/>175 GB memory (request)<br/>245 GB memory (limit) | 5 x `n1-standard-32` | 5 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|------------------------|------------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 25k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 500 RPS or 25,000 users we recommend a total Puma worker count of around 140 so in turn it's recommended to run at
least 35 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 500 RPS or 25,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/25k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/1k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/1k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
1k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 20 RPS or 1,000 users
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This reference architecture targets a peak load of 20 requests per second (RPS). Based on real data, this load typically corresponds to up to 1,000 users, which includes both manual and automated interactions.
For a full list of reference architectures, see
[available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 20 RPS, Web: 2 RPS, Git (Pull): 2 RPS, Git (Push): 1 RPS
- **High Availability**: No. For a high availability environment,
follow a modified [3K reference architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
- **Cloud Native Hybrid**: No. For a cloud native hybrid environment, you
can follow a [modified hybrid reference architecture](#cloud-native-hybrid-reference-architecture-with-helm-charts).
- **Unsure which Reference Architecture to use?** For more information, see [deciding which architecture to start with](_index.md#deciding-which-architecture-to-start-with).
| Users | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|--------------|----------------------|----------------|--------------|----------|
| Up to 1,000 or 20 RPS | 8 vCPU, 16 GB memory | `n1-standard-8`<sup>2</sup> | `c5.2xlarge` | `F8s v2` |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. For GCP, the closest and equivalent standard machine type has been selected that matches the recommended requirement of 8 vCPU and 16 GB of RAM. A [custom machine type](https://cloud.google.com/compute/docs/instances/creating-instance-with-custom-machine-type) can also be used if desired.
<!-- markdownlint-enable MD029 -->
The following diagram shows that while GitLab can be installed on a single server, it is internally composed of multiple services. When an instance scales, these services are separated and independently scaled according to their specific demands.
In some cases, you can leverage PaaS for some services. For example, you can use Cloud Object Storage for some file systems. For the sake of redundancy, some services become clusters of nodes and store the same data.
In a horizontally scaled GitLab configuration, various ancillary services are required to coordinate clusters or discover resources. For example, PgBouncer for PostgreSQL connection management, or Consul for Prometheus end point discovery.
```plantuml
@startuml 1k
card "**Prometheus**" as monitor #7FFFD4
package "GitLab Single Server" as gitlab-single-server {
together {
card "**GitLab Rails**" as gitlab #32CD32
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
card "**Sidekiq**" as sidekiq #ff8dd1
}
card "Local Storage" as local_storage #white
}
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]--> redis
gitlab -[#32CD32]--> sidekiq
gitaly -[#32CD32]--> local_storage
postgres -[#32CD32]--> local_storage
sidekiq -[#32CD32]--> local_storage
gitlab -[#32CD32]--> local_storage
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]-> postgres
monitor .[#7FFFD4]-> gitaly
monitor .[#7FFFD4,norank]--> redis
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
{{< alert type="warning" >}}
**The node's specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads), they might significantly impact the performance of the environment**.
If this applies to you, [further adjustments might be required](_index.md#scaling-an-environment). See the linked documentation and contact us if required for further guidance.
{{< /alert >}}
## Testing methodology
The 20 RPS / 1k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 20 RPS |
| Web | 2 RPS |
| Git (Pull) | 2 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
## Setup instructions
To install GitLab for this default reference architecture, use the standard
[installation instructions](../../install/_index.md).
You can also optionally configure GitLab to use an [external PostgreSQL service](../postgresql/external.md)
or [external object storage service](../object_storage.md). It improves performance and reliability, but at an increased complexity cost.
## Configure advanced search
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements depends on your
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, see
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
## Cloud Native Hybrid reference architecture with Helm Charts
In the Cloud Native Hybrid reference architecture setup, the select stateless
components are deployed in Kubernetes by using our official [Helm Charts](https://docs.gitlab.com/charts/).
The stateful components are deployed in compute VMs with the Linux package.
The smallest reference architecture available for use in Kubernetes is the [2k or 40 RPS GitLab Cloud Native Hybrid](2k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) (non HA) and [3k or 60 RPS GitLab Cloud Native Hybrid](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) (HA).
For environments that serve fewer users or a lower RPS, you can lower the node specification. Depending on your user count, you can lower all suggested node specifications as desired. However, you should not go lower than the [general requirements](../../install/requirements.md).
## Next steps
Now you have a fresh GitLab environment with core functionality configured accordingly. You might want to configure additional optional GitLab features depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features. See the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 20 RPS or 1,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This reference architecture targets a peak load of 20 requests per second (RPS). Based on real data, this load typically corresponds to up to 1,000 users, which includes both manual and automated interactions.
For a full list of reference architectures, see
[available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 20 RPS, Web: 2 RPS, Git (Pull): 2 RPS, Git (Push): 1 RPS
- **High Availability**: No. For a high availability environment,
follow a modified [3K reference architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
- **Cloud Native Hybrid**: No. For a cloud native hybrid environment, you
can follow a [modified hybrid reference architecture](#cloud-native-hybrid-reference-architecture-with-helm-charts).
- **Unsure which Reference Architecture to use?** For more information, see [deciding which architecture to start with](_index.md#deciding-which-architecture-to-start-with).
| Users | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|--------------|----------------------|----------------|--------------|----------|
| Up to 1,000 or 20 RPS | 8 vCPU, 16 GB memory | `n1-standard-8`<sup>2</sup> | `c5.2xlarge` | `F8s v2` |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. For GCP, the closest and equivalent standard machine type has been selected that matches the recommended requirement of 8 vCPU and 16 GB of RAM. A [custom machine type](https://cloud.google.com/compute/docs/instances/creating-instance-with-custom-machine-type) can also be used if desired.
<!-- markdownlint-enable MD029 -->
The following diagram shows that while GitLab can be installed on a single server, it is internally composed of multiple services. When an instance scales, these services are separated and independently scaled according to their specific demands.
In some cases, you can leverage PaaS for some services. For example, you can use Cloud Object Storage for some file systems. For the sake of redundancy, some services become clusters of nodes and store the same data.
In a horizontally scaled GitLab configuration, various ancillary services are required to coordinate clusters or discover resources. For example, PgBouncer for PostgreSQL connection management, or Consul for Prometheus end point discovery.
```plantuml
@startuml 1k
card "**Prometheus**" as monitor #7FFFD4
package "GitLab Single Server" as gitlab-single-server {
together {
card "**GitLab Rails**" as gitlab #32CD32
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
card "**Sidekiq**" as sidekiq #ff8dd1
}
card "Local Storage" as local_storage #white
}
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]--> redis
gitlab -[#32CD32]--> sidekiq
gitaly -[#32CD32]--> local_storage
postgres -[#32CD32]--> local_storage
sidekiq -[#32CD32]--> local_storage
gitlab -[#32CD32]--> local_storage
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]-> postgres
monitor .[#7FFFD4]-> gitaly
monitor .[#7FFFD4,norank]--> redis
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
{{< alert type="warning" >}}
**The node's specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads), they might significantly impact the performance of the environment**.
If this applies to you, [further adjustments might be required](_index.md#scaling-an-environment). See the linked documentation and contact us if required for further guidance.
{{< /alert >}}
## Testing methodology
The 20 RPS / 1k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 20 RPS |
| Web | 2 RPS |
| Git (Pull) | 2 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
## Setup instructions
To install GitLab for this default reference architecture, use the standard
[installation instructions](../../install/_index.md).
You can also optionally configure GitLab to use an [external PostgreSQL service](../postgresql/external.md)
or [external object storage service](../object_storage.md). It improves performance and reliability, but at an increased complexity cost.
## Configure advanced search
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements depends on your
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, see
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
## Cloud Native Hybrid reference architecture with Helm Charts
In the Cloud Native Hybrid reference architecture setup, the select stateless
components are deployed in Kubernetes by using our official [Helm Charts](https://docs.gitlab.com/charts/).
The stateful components are deployed in compute VMs with the Linux package.
The smallest reference architecture available for use in Kubernetes is the [2k or 40 RPS GitLab Cloud Native Hybrid](2k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) (non HA) and [3k or 60 RPS GitLab Cloud Native Hybrid](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) (HA).
For environments that serve fewer users or a lower RPS, you can lower the node specification. Depending on your user count, you can lower all suggested node specifications as desired. However, you should not go lower than the [general requirements](../../install/requirements.md).
## Next steps
Now you have a fresh GitLab environment with core functionality configured accordingly. You might want to configure additional optional GitLab features depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features. See the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/50k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/50k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
50k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 1000 RPS or 50,000 users
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 1000 requests per second (RPS), the typical peak load of up to 50,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|---------------|-----------|
| External load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` | `D32s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 64 vCPU, 240 GB memory | `n1-standard-64` | `m5.16xlarge` | `D64s v3` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 12 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 50k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x12" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before starting, see the [requirements](_index.md#requirements) for reference architectures.
## Testing methodology
The 1000 RPS / 50k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 1000 RPS |
| Web | 100 RPS |
| Git (Pull) | 100 RPS |
| Git (Push) | 20 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 1000 RPS or 50,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.116`: GitLab application 6
- `10.6.0.117`: GitLab application 7
- `10.6.0.118`: GitLab application 8
- `10.6.0.119`: GitLab application 9
- `10.6.0.120`: GitLab application 10
- `10.6.0.121`: GitLab application 11
- `10.6.0.122`: GitLab application 12
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs will be used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from increasing CPU cores.
For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance at this scale.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks
(Internet),
using a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_master_role' with Sentinel and enable Consul agent
roles(['redis_sentinel_role', 'redis_master_role', 'consul_role'])
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the same contents as the primary node in the previous section by replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server role as 'redis_replica_role' with Sentinel and enable Consul agent
roles(['roles_sentinel_role', 'redis_replica_role', 'consul_role'])
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package
node you configured and add or replace the file of the same name on this
server. If this is the first Linux package node you are configuring then you
can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes
to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Queues instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and enable the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_replica_role' with Sentinel and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup should not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or later. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of the Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect via a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is Internal Load Balancer for Praefect
# Token is praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.116`: GitLab application 6
- `10.6.0.117`: GitLab application 7
- `10.6.0.118`: GitLab application 8
- `10.6.0.119`: GitLab application 9
- `10.6.0.120`: GitLab application 10
- `10.6.0.121`: GitLab application 11
- `10.6.0.122`: GitLab application 12
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is Internal Load Balancer for Praefect
# Token is praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 308 vCPU<br/>385 GB memory (request)<br/>539 GB memory (limit) | 11 x `n1-standard-32` | 11 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|------------------------|------------------|---------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 64 vCPU, 240 GB memory | `n1-standard-64` | `m5.16xlarge` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 50k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 1000 RPS or 50,000 users we recommend a total Puma worker count of around 308 so in turn it's recommended to run at
least 77 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
These supporting deployments include various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 1000 RPS or 50,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/50k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 1000 RPS or 50,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 1000 requests per second (RPS), the typical peak load of up to 50,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|---------------|-----------|
| External load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` | `D32s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 64 vCPU, 240 GB memory | `n1-standard-64` | `m5.16xlarge` | `D64s v3` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 12 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 50k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x12" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before starting, see the [requirements](_index.md#requirements) for reference architectures.
## Testing methodology
The 1000 RPS / 50k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint type | Target throughput |
| ------------- | ----------------- |
| API | 1000 RPS |
| Web | 100 RPS |
| Git (Pull) | 100 RPS |
| Git (Push) | 20 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 1000 RPS or 50,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.116`: GitLab application 6
- `10.6.0.117`: GitLab application 7
- `10.6.0.118`: GitLab application 8
- `10.6.0.119`: GitLab application 9
- `10.6.0.120`: GitLab application 10
- `10.6.0.121`: GitLab application 11
- `10.6.0.122`: GitLab application 12
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs will be used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from increasing CPU cores.
For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance at this scale.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks
(Internet),
using a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_master_role' with Sentinel and enable Consul agent
roles(['redis_sentinel_role', 'redis_master_role', 'consul_role'])
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the same contents as the primary node in the previous section by replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server role as 'redis_replica_role' with Sentinel and enable Consul agent
roles(['roles_sentinel_role', 'redis_replica_role', 'consul_role'])
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package
node you configured and add or replace the file of the same name on this
server. If this is the first Linux package node you are configuring then you
can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes
to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Queues instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and enable the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_replica_role' with Sentinel and enable Consul agent
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html) are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store data on Gitaly Cluster (Praefect) status.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup should not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or later. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of the Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect via a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is Internal Load Balancer for Praefect
# Token is praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.114`: GitLab application 4
- `10.6.0.115`: GitLab application 5
- `10.6.0.116`: GitLab application 6
- `10.6.0.117`: GitLab application 7
- `10.6.0.118`: GitLab application 8
- `10.6.0.119`: GitLab application 9
- `10.6.0.120`: GitLab application 10
- `10.6.0.121`: GitLab application 11
- `10.6.0.122`: GitLab application 12
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is Internal Load Balancer for Praefect
# Token is praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 308 vCPU<br/>385 GB memory (request)<br/>539 GB memory (limit) | 11 x `n1-standard-32` | 11 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|------------------------|------------------|---------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 32 vCPU, 120 GB memory | `n1-standard-32` | `m5.8xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 64 vCPU, 240 GB memory | `n1-standard-64` | `m5.16xlarge` |
| Praefect<sup>6</sup> | 3 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Can be optionally run on reputable third-party load balancing services (LB PaaS). See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 50k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 1000 RPS or 50,000 users we recommend a total Puma worker count of around 308 so in turn it's recommended to run at
least 77 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
These supporting deployments include various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 1000 RPS or 50,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/50k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/2k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/2k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
2k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 40 RPS or 2,000 users
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 40 requests per second (RPS), the typical peak load of up to 2,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS
- **High Availability**: No. For a highly-available environment, you can
follow a modified [3K or 60 RPS reference architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
- **Cloud Native Hybrid**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with).
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------|-------|------------------------|-----------------|--------------|----------|
| External Load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| PostgreSQL<sup>2</sup> | 1 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Redis<sup>3</sup> | 1 | 1 vCPU, 3.75 GB memory | `n1-standard-1` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Sidekiq<sup>7</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>7</sup> | 2 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` | `F8s v2` |
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS).
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. See [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly specifications are based on the use of normal-sized repositories in good health.
However, if you have large monorepos (larger than several gigabytes) this can **significantly** impact Git and Gitaly performance and an increase of specifications will likely be required.
Refer to [large monorepos](_index.md#large-monorepos) for more information.
7. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to deploy them over multiple availability zones for resilience if desired.
{{< /alert >}}
```plantuml
@startuml 2k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**GitLab Rails** x2" as gitlab #32CD32
card "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Prometheus**" as monitor #7FFFD4
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]> object_storage
gitlab -[#32CD32]--> redis
sidekiq -[#ff8dd1]> object_storage
sidekiq -[#ff8dd1]--> redis
sidekiq .[#ff8dd1]--> postgres
sidekiq -[hidden]-> monitor
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]-> gitaly
monitor .[#7FFFD4]-> postgres
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4,norank]u--> elb
monitor .[#7FFFD4]u-> sidekiq
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 40 RPS / 2k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 40 RPS |
| Web | 4 RPS |
| Git (Pull) | 4 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 40 RPS or 2,000 users:
1. [Configure the external load balancing node](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly](#configure-gitaly), which provides access to the Git
repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage) used for
shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring an external PostgreSQL database
to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
### Standalone PostgreSQL using the Linux package
1. SSH in to the PostgreSQL server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Generate a password hash for PostgreSQL. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `POSTGRESQL_PASSWORD_HASH`.
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Edit `/etc/gitlab/gitlab.rb` and add the contents below, updating placeholder
values appropriately.
- `POSTGRESQL_PASSWORD_HASH` - The value output from the previous step
- `APPLICATION_SERVER_IP_BLOCKS` - A space delimited list of IP subnets or IP
addresses of the GitLab Rails and Sidekiq servers that will connect to the
database. Example: `%w(123.123.123.123/32 123.123.123.234/32)`
```ruby
# Disable all components except PostgreSQL related ones
roles(['postgres_role'])
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
postgres_exporter['dbname'] = 'gitlabhq_production'
postgres_exporter['password'] = 'POSTGRESQL_PASSWORD_HASH'
# Set the PostgreSQL address and port
postgresql['listen_address'] = '0.0.0.0'
postgresql['port'] = 5432
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = 'POSTGRESQL_PASSWORD_HASH'
# Replace APPLICATION_SERVER_IP_BLOCK with the CIDR address of the application node
postgresql['trust_auth_cidr_addresses'] = %w(127.0.0.1/32 APPLICATION_SERVER_IP_BLOCK)
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the PostgreSQL node's IP address or hostname, port, and
plain text password. These details are necessary when configuring the
[GitLab application server](#configure-gitlab-rails) later.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
In this section, you'll be guided through configuring an external Redis instance
to be used with GitLab.
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Standalone Redis using the Linux package
The Linux package can be used to configure a standalone Redis server.
The steps below are the minimum necessary to configure a Redis server with
the Linux package:
1. SSH in to the Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
## Enable Redis
roles(["redis_master_role"])
redis['bind'] = '0.0.0.0'
redis['port'] = 6379
redis['password'] = 'SECRET_PASSWORD_HERE'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://0.0.0.0:6379',
'redis.password' => 'SECRET_PASSWORD_HERE',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the Redis node's IP address or hostname, port, and
Redis password. These will be necessary when
[configuring the GitLab application servers](#configure-gitlab-rails) later.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly
[Gitaly](../gitaly/_index.md) server node requirements are dependent on data size,
specifically the number of projects and those projects' sizes.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Be sure to note the following items:
- The GitLab Rails application shards repositories into
[repository storage paths](../repository_storage_paths.md).
- A Gitaly server can host one or more storage paths.
- A GitLab server can use one or more Gitaly server nodes.
- Gitaly addresses must be specified to be correctly resolvable for all
Gitaly clients.
- Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-tls-support).
{{< alert type="note" >}}
The token referred to throughout the Gitaly documentation is an arbitrary
password selected by the administrator. This token is unrelated to tokens
created for the GitLab API or other similar web API tokens.
{{< /alert >}}
The following procedure describes how to configure a single Gitaly server named
`gitaly1.internal` with the secret token `gitalysecret`. We assume your GitLab
installation has two repository storages: `default` and `storage1`.
To configure the Gitaly server, on the server node you want to use for Gitaly:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
{{< alert type="note" >}}
You can't remove the `default` entry from `gitaly['configuration'][:storage]` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# ...
#
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
prometheus_listen_addr: '0.0.0.0:9236',
# Gitaly Auth Token
# Should be the same as praefect_internal_token
auth: {
# ...
#
# Gitaly's authentication token is used to authenticate gRPC requests to Gitaly. This must match
# the respective value in GitLab Rails application setup.
token: 'gitalysecret',
},
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
pack_objects_cache: {
# ...
enabled: true,
},
storage: [
{
name: 'default',
path: '/var/opt/gitlab/git-data',
},
{
name: 'storage1',
path: '/mnt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
### Gitaly TLS support
Gitaly supports TLS encryption. To communicate
with a Gitaly instance that listens for secure connections, you must use `tls://` URL
scheme in the `gitaly_address` of the corresponding storage entry in the GitLab configuration.
You must bring your own certificates as this isn't provided automatically.
The certificate, or its certificate authority, must be installed on all Gitaly
nodes (including the Gitaly node using the certificate) and on all client nodes
that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates).
{{< alert type="note" >}}
The self-signed certificate must specify the address you use to access the
Gitaly server. If you are addressing the Gitaly server by a hostname, add it as a Subject Alternative
Name. If you are addressing the Gitaly server by its IP address, you must add it
as a Subject Alternative Name to the certificate.
{{< /alert >}}
It's possible to configure Gitaly servers with both an unencrypted listening
address (`listen_addr`) and an encrypted listening address (`tls_listen_addr`)
at the same time. This allows you to do a gradual transition from unencrypted to
encrypted traffic, if necessary.
To configure Gitaly with TLS:
1. Create the `/etc/gitlab/ssl` directory and copy your key and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Copy the cert to `/etc/gitlab/trusted-certs` so Gitaly will trust the cert when
calling into itself:
```shell
sudo cp /etc/gitlab/ssl/cert.pem /etc/gitlab/trusted-certs/
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
<!-- Updates to following example must also be made at https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab -->
```ruby
gitaly['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:9999',
tls: {
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Delete `gitaly['listen_addr']` to allow only encrypted connections.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
To configure the Sidekiq server, on the server node you want to use for Sidekiq:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
external_url 'https://gitlab.example.com'
## Redis connection details
gitlab_rails['redis_port'] = '6379'
gitlab_rails['redis_host'] = '10.1.0.6' # IP/hostname of Redis server
gitlab_rails['redis_password'] = 'Redis Password'
# Gitaly and GitLab use two shared secrets for authentication, one to authenticate gRPC requests
# to Gitaly, and a second stored in /etc/gitlab/gitlab-secrets.json for authentication callbacks from GitLab-Shell to the GitLab internal API.
# The following must be the same as their respective values
# of the Gitaly setup
gitlab_rails['gitaly_token'] = 'gitalysecret'
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage1' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage2' => { 'gitaly_address' => 'tcp://gitaly2.internal:8075' },
}
## PostgreSQL connection details
gitlab_rails['db_adapter'] = 'postgresql'
gitlab_rails['db_encoding'] = 'unicode'
gitlab_rails['db_host'] = '10.1.0.5' # IP/hostname of database server
gitlab_rails['db_password'] = 'DB password'
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: logrotate: (pid 192292) 2990s; run: log: (pid 26374) 93048s
run: node-exporter: (pid 26864) 92997s; run: log: (pid 26446) 93036s
run: sidekiq: (pid 26870) 92996s; run: log: (pid 26391) 93042s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
In our architecture, we run each GitLab Rails node using the Puma webserver, and
have its number of workers set to 90% of available CPUs, with four threads. For
nodes running Rails with other components, the worker value should be reduced
accordingly. We've determined that a worker value of 50% achieves a good balance,
but this is dependent on workload.
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# Gitaly and GitLab use two shared secrets for authentication, one to authenticate gRPC requests
# to Gitaly, and a second stored in /etc/gitlab/gitlab-secrets.json for authentication callbacks from GitLab-Shell to the GitLab internal API.
# The following must be the same as their respective values
# of the Gitaly setup
gitlab_rails['gitaly_token'] = 'gitalysecret'
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage1' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage2' => { 'gitaly_address' => 'tcp://gitaly2.internal:8075' },
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
gitlab_rails['db_adapter'] = 'postgresql'
gitlab_rails['db_encoding'] = 'unicode'
gitlab_rails['db_host'] = '10.1.0.5' # IP/hostname of database server
gitlab_rails['db_password'] = 'DB password'
## Redis connection details
gitlab_rails['redis_port'] = '6379'
gitlab_rails['redis_host'] = '10.1.0.6' # IP/hostname of Redis server
gitlab_rails['redis_password'] = 'Redis Password'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics. Replace placeholder `monitoring.gitlab.example.com` with
# the address and/or subnets gathered from the monitoring node
gitlab_rails['monitoring_whitelist'] = ['<MONITOR NODE IP>/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['<MONITOR NODE IP>/32', '127.0.0.0/8']
# Object Storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
```
1. If you're using [Gitaly with TLS support](#gitaly-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tls://gitaly1.internal:9999' },
'storage1' => { 'gitaly_address' => 'tls://gitaly1.internal:9999' },
'storage2' => { 'gitaly_address' => 'tls://gitaly2.internal:9999' },
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX won't start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role'])
nginx['enable'] = false
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
```
1. Prometheus also needs some scrape configurations to pull all the data from the various
nodes where we configured exporters. Assuming that your nodes' IPs are:
```plaintext
1.1.1.1: postgres
1.1.1.2: redis
1.1.1.3: gitaly1
1.1.1.4: rails1
1.1.1.5: rails2
1.1.1.6: sidekiq
```
Add the following to `/etc/gitlab/gitlab.rb`:
```ruby
prometheus['scrape_configs'] = [
{
'job_name': 'postgres',
'static_configs' => [
'targets' => ['1.1.1.1:9187'],
],
},
{
'job_name': 'redis',
'static_configs' => [
'targets' => ['1.1.1.2:9121'],
],
},
{
'job_name': 'gitaly',
'static_configs' => [
'targets' => ['1.1.1.3:9236'],
],
},
{
'job_name': 'gitlab-nginx',
'static_configs' => [
'targets' => ['1.1.1.4:8060', '1.1.1.5:8060'],
],
},
{
'job_name': 'gitlab-workhorse',
'static_configs' => [
'targets' => ['1.1.1.4:9229', '1.1.1.5:9229'],
],
},
{
'job_name': 'gitlab-rails',
'metrics_path': '/-/metrics',
'static_configs' => [
'targets' => ['1.1.1.4:8080', '1.1.1.5:8080'],
],
},
{
'job_name': 'gitlab-sidekiq',
'static_configs' => [
'targets' => ['1.1.1.6:8082'],
],
},
{
'job_name': 'static-node',
'static_configs' => [
'targets' => ['1.1.1.1:9100', '1.1.1.2:9100', '1.1.1.3:9100', '1.1.1.4:9100', '1.1.1.5:9100', '1.1.1.6:9100'],
],
},
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="note" >}}
The 2,000 reference architecture is not a highly-available setup. To achieve HA,
you can follow a modified [3K or 60 RPS reference architecture](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative).
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 12 vCPU<br/>15 GB memory (request)<br/>21 GB memory (limit) | 3 x `n1-standard-8` | 3 x `c5.2xlarge` |
| Sidekiq | 3.6 vCPU<br/>8 GB memory (request)<br/>16 GB memory (limit) | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommend [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment and any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-----------------------------|-------|------------------------|-----------------|-------------|
| PostgreSQL<sup>2</sup> | 1 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Redis<sup>3</sup> | 1 | 1 vCPU, 3.75 GB memory | `n1-standard-1` | `m5.large` |
| Gitaly<sup>5</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Object storage<sup>4</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
4. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
5. Gitaly specifications are based on the use of normal-sized repositories in good health.
However, if you have large monorepos (larger than several gigabytes) this can **significantly** impact Git and Gitaly performance and an increase of specifications will likely be required.
Refer to [large monorepos](_index.md#large-monorepos) for more information.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 2k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
collections "**Supporting Services**" as support
}
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]-> object_storage
gitlab -[#32CD32]--> redis
sidekiq -[#ff8dd1]--> gitaly
sidekiq -[#ff8dd1]-> object_storage
sidekiq -[#ff8dd1]--> postgres
sidekiq -[#ff8dd1]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 40 RPS or 2,000 users, we recommend a total Puma worker count of around 12 so in turn it's recommended to run at
least 3 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This allows the controllers to scale dynamically with the Webservice pods they serve, and takes advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 4 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts for the 40 RPS or 2,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/2k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 40 RPS or 2,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 40 requests per second (RPS), the typical peak load of up to 2,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
- **Target Load**: API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS
- **High Availability**: No. For a highly-available environment, you can
follow a modified [3K or 60 RPS reference architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
- **Cloud Native Hybrid**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with).
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------|-------|------------------------|-----------------|--------------|----------|
| External Load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| PostgreSQL<sup>2</sup> | 1 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Redis<sup>3</sup> | 1 | 1 vCPU, 3.75 GB memory | `n1-standard-1` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Sidekiq<sup>7</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>7</sup> | 2 | 8 vCPU, 7.2 GB memory | `n1-highcpu-8` | `c5.2xlarge` | `F8s v2` |
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS).
Sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. See [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly specifications are based on the use of normal-sized repositories in good health.
However, if you have large monorepos (larger than several gigabytes) this can **significantly** impact Git and Gitaly performance and an increase of specifications will likely be required.
Refer to [large monorepos](_index.md#large-monorepos) for more information.
7. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to deploy them over multiple availability zones for resilience if desired.
{{< /alert >}}
```plantuml
@startuml 2k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**GitLab Rails** x2" as gitlab #32CD32
card "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Prometheus**" as monitor #7FFFD4
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]> object_storage
gitlab -[#32CD32]--> redis
sidekiq -[#ff8dd1]> object_storage
sidekiq -[#ff8dd1]--> redis
sidekiq .[#ff8dd1]--> postgres
sidekiq -[hidden]-> monitor
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]-> gitaly
monitor .[#7FFFD4]-> postgres
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4,norank]u--> elb
monitor .[#7FFFD4]u-> sidekiq
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 40 RPS / 2k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 40 RPS |
| Web | 4 RPS |
| Git (Pull) | 4 RPS |
| Git (Push) | 1 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 40 RPS or 2,000 users:
1. [Configure the external load balancing node](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly](#configure-gitaly), which provides access to the Git
repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage) used for
shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring an external PostgreSQL database
to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
### Standalone PostgreSQL using the Linux package
1. SSH in to the PostgreSQL server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Generate a password hash for PostgreSQL. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `POSTGRESQL_PASSWORD_HASH`.
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Edit `/etc/gitlab/gitlab.rb` and add the contents below, updating placeholder
values appropriately.
- `POSTGRESQL_PASSWORD_HASH` - The value output from the previous step
- `APPLICATION_SERVER_IP_BLOCKS` - A space delimited list of IP subnets or IP
addresses of the GitLab Rails and Sidekiq servers that will connect to the
database. Example: `%w(123.123.123.123/32 123.123.123.234/32)`
```ruby
# Disable all components except PostgreSQL related ones
roles(['postgres_role'])
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
postgres_exporter['dbname'] = 'gitlabhq_production'
postgres_exporter['password'] = 'POSTGRESQL_PASSWORD_HASH'
# Set the PostgreSQL address and port
postgresql['listen_address'] = '0.0.0.0'
postgresql['port'] = 5432
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = 'POSTGRESQL_PASSWORD_HASH'
# Replace APPLICATION_SERVER_IP_BLOCK with the CIDR address of the application node
postgresql['trust_auth_cidr_addresses'] = %w(127.0.0.1/32 APPLICATION_SERVER_IP_BLOCK)
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the PostgreSQL node's IP address or hostname, port, and
plain text password. These details are necessary when configuring the
[GitLab application server](#configure-gitlab-rails) later.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
In this section, you'll be guided through configuring an external Redis instance
to be used with GitLab.
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Standalone Redis using the Linux package
The Linux package can be used to configure a standalone Redis server.
The steps below are the minimum necessary to configure a Redis server with
the Linux package:
1. SSH in to the Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
## Enable Redis
roles(["redis_master_role"])
redis['bind'] = '0.0.0.0'
redis['port'] = 6379
redis['password'] = 'SECRET_PASSWORD_HERE'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://0.0.0.0:6379',
'redis.password' => 'SECRET_PASSWORD_HERE',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the Redis node's IP address or hostname, port, and
Redis password. These will be necessary when
[configuring the GitLab application servers](#configure-gitlab-rails) later.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly
[Gitaly](../gitaly/_index.md) server node requirements are dependent on data size,
specifically the number of projects and those projects' sizes.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Be sure to note the following items:
- The GitLab Rails application shards repositories into
[repository storage paths](../repository_storage_paths.md).
- A Gitaly server can host one or more storage paths.
- A GitLab server can use one or more Gitaly server nodes.
- Gitaly addresses must be specified to be correctly resolvable for all
Gitaly clients.
- Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-tls-support).
{{< alert type="note" >}}
The token referred to throughout the Gitaly documentation is an arbitrary
password selected by the administrator. This token is unrelated to tokens
created for the GitLab API or other similar web API tokens.
{{< /alert >}}
The following procedure describes how to configure a single Gitaly server named
`gitaly1.internal` with the secret token `gitalysecret`. We assume your GitLab
installation has two repository storages: `default` and `storage1`.
To configure the Gitaly server, on the server node you want to use for Gitaly:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
{{< alert type="note" >}}
You can't remove the `default` entry from `gitaly['configuration'][:storage]` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# ...
#
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
prometheus_listen_addr: '0.0.0.0:9236',
# Gitaly Auth Token
# Should be the same as praefect_internal_token
auth: {
# ...
#
# Gitaly's authentication token is used to authenticate gRPC requests to Gitaly. This must match
# the respective value in GitLab Rails application setup.
token: 'gitalysecret',
},
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
pack_objects_cache: {
# ...
enabled: true,
},
storage: [
{
name: 'default',
path: '/var/opt/gitlab/git-data',
},
{
name: 'storage1',
path: '/mnt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
### Gitaly TLS support
Gitaly supports TLS encryption. To communicate
with a Gitaly instance that listens for secure connections, you must use `tls://` URL
scheme in the `gitaly_address` of the corresponding storage entry in the GitLab configuration.
You must bring your own certificates as this isn't provided automatically.
The certificate, or its certificate authority, must be installed on all Gitaly
nodes (including the Gitaly node using the certificate) and on all client nodes
that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates).
{{< alert type="note" >}}
The self-signed certificate must specify the address you use to access the
Gitaly server. If you are addressing the Gitaly server by a hostname, add it as a Subject Alternative
Name. If you are addressing the Gitaly server by its IP address, you must add it
as a Subject Alternative Name to the certificate.
{{< /alert >}}
It's possible to configure Gitaly servers with both an unencrypted listening
address (`listen_addr`) and an encrypted listening address (`tls_listen_addr`)
at the same time. This allows you to do a gradual transition from unencrypted to
encrypted traffic, if necessary.
To configure Gitaly with TLS:
1. Create the `/etc/gitlab/ssl` directory and copy your key and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Copy the cert to `/etc/gitlab/trusted-certs` so Gitaly will trust the cert when
calling into itself:
```shell
sudo cp /etc/gitlab/ssl/cert.pem /etc/gitlab/trusted-certs/
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
<!-- Updates to following example must also be made at https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab -->
```ruby
gitaly['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:9999',
tls: {
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Delete `gitaly['listen_addr']` to allow only encrypted connections.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
To configure the Sidekiq server, on the server node you want to use for Sidekiq:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
external_url 'https://gitlab.example.com'
## Redis connection details
gitlab_rails['redis_port'] = '6379'
gitlab_rails['redis_host'] = '10.1.0.6' # IP/hostname of Redis server
gitlab_rails['redis_password'] = 'Redis Password'
# Gitaly and GitLab use two shared secrets for authentication, one to authenticate gRPC requests
# to Gitaly, and a second stored in /etc/gitlab/gitlab-secrets.json for authentication callbacks from GitLab-Shell to the GitLab internal API.
# The following must be the same as their respective values
# of the Gitaly setup
gitlab_rails['gitaly_token'] = 'gitalysecret'
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage1' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage2' => { 'gitaly_address' => 'tcp://gitaly2.internal:8075' },
}
## PostgreSQL connection details
gitlab_rails['db_adapter'] = 'postgresql'
gitlab_rails['db_encoding'] = 'unicode'
gitlab_rails['db_host'] = '10.1.0.5' # IP/hostname of database server
gitlab_rails['db_password'] = 'DB password'
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: logrotate: (pid 192292) 2990s; run: log: (pid 26374) 93048s
run: node-exporter: (pid 26864) 92997s; run: log: (pid 26446) 93036s
run: sidekiq: (pid 26870) 92996s; run: log: (pid 26391) 93042s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
In our architecture, we run each GitLab Rails node using the Puma webserver, and
have its number of workers set to 90% of available CPUs, with four threads. For
nodes running Rails with other components, the worker value should be reduced
accordingly. We've determined that a worker value of 50% achieves a good balance,
but this is dependent on workload.
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# Gitaly and GitLab use two shared secrets for authentication, one to authenticate gRPC requests
# to Gitaly, and a second stored in /etc/gitlab/gitlab-secrets.json for authentication callbacks from GitLab-Shell to the GitLab internal API.
# The following must be the same as their respective values
# of the Gitaly setup
gitlab_rails['gitaly_token'] = 'gitalysecret'
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage1' => { 'gitaly_address' => 'tcp://gitaly1.internal:8075' },
'storage2' => { 'gitaly_address' => 'tcp://gitaly2.internal:8075' },
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
gitlab_rails['db_adapter'] = 'postgresql'
gitlab_rails['db_encoding'] = 'unicode'
gitlab_rails['db_host'] = '10.1.0.5' # IP/hostname of database server
gitlab_rails['db_password'] = 'DB password'
## Redis connection details
gitlab_rails['redis_port'] = '6379'
gitlab_rails['redis_host'] = '10.1.0.6' # IP/hostname of Redis server
gitlab_rails['redis_password'] = 'Redis Password'
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics. Replace placeholder `monitoring.gitlab.example.com` with
# the address and/or subnets gathered from the monitoring node
gitlab_rails['monitoring_whitelist'] = ['<MONITOR NODE IP>/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['<MONITOR NODE IP>/32', '127.0.0.0/8']
# Object Storage
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
```
1. If you're using [Gitaly with TLS support](#gitaly-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
'default' => { 'gitaly_address' => 'tls://gitaly1.internal:9999' },
'storage1' => { 'gitaly_address' => 'tls://gitaly1.internal:9999' },
'storage2' => { 'gitaly_address' => 'tls://gitaly2.internal:9999' },
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX won't start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role'])
nginx['enable'] = false
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
```
1. Prometheus also needs some scrape configurations to pull all the data from the various
nodes where we configured exporters. Assuming that your nodes' IPs are:
```plaintext
1.1.1.1: postgres
1.1.1.2: redis
1.1.1.3: gitaly1
1.1.1.4: rails1
1.1.1.5: rails2
1.1.1.6: sidekiq
```
Add the following to `/etc/gitlab/gitlab.rb`:
```ruby
prometheus['scrape_configs'] = [
{
'job_name': 'postgres',
'static_configs' => [
'targets' => ['1.1.1.1:9187'],
],
},
{
'job_name': 'redis',
'static_configs' => [
'targets' => ['1.1.1.2:9121'],
],
},
{
'job_name': 'gitaly',
'static_configs' => [
'targets' => ['1.1.1.3:9236'],
],
},
{
'job_name': 'gitlab-nginx',
'static_configs' => [
'targets' => ['1.1.1.4:8060', '1.1.1.5:8060'],
],
},
{
'job_name': 'gitlab-workhorse',
'static_configs' => [
'targets' => ['1.1.1.4:9229', '1.1.1.5:9229'],
],
},
{
'job_name': 'gitlab-rails',
'metrics_path': '/-/metrics',
'static_configs' => [
'targets' => ['1.1.1.4:8080', '1.1.1.5:8080'],
],
},
{
'job_name': 'gitlab-sidekiq',
'static_configs' => [
'targets' => ['1.1.1.6:8082'],
],
},
{
'job_name': 'static-node',
'static_configs' => [
'targets' => ['1.1.1.1:9100', '1.1.1.2:9100', '1.1.1.3:9100', '1.1.1.4:9100', '1.1.1.5:9100', '1.1.1.6:9100'],
],
},
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="note" >}}
The 2,000 reference architecture is not a highly-available setup. To achieve HA,
you can follow a modified [3K or 60 RPS reference architecture](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative).
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 12 vCPU<br/>15 GB memory (request)<br/>21 GB memory (limit) | 3 x `n1-standard-8` | 3 x `c5.2xlarge` |
| Sidekiq | 3.6 vCPU<br/>8 GB memory (request)<br/>16 GB memory (limit) | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommend [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment and any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-----------------------------|-------|------------------------|-----------------|-------------|
| PostgreSQL<sup>2</sup> | 1 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Redis<sup>3</sup> | 1 | 1 vCPU, 3.75 GB memory | `n1-standard-1` | `m5.large` |
| Gitaly<sup>5</sup> | 1 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Object storage<sup>4</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
4. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
5. Gitaly specifications are based on the use of normal-sized repositories in good health.
However, if you have large monorepos (larger than several gigabytes) this can **significantly** impact Git and Gitaly performance and an increase of specifications will likely be required.
Refer to [large monorepos](_index.md#large-monorepos) for more information.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 2k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
collections "**Supporting Services**" as support
}
card "**Gitaly**" as gitaly #FF8C00
card "**PostgreSQL**" as postgres #4EA7FF
card "**Redis**" as redis #FF6347
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
gitlab -[#32CD32]--> gitaly
gitlab -[#32CD32]--> postgres
gitlab -[#32CD32]-> object_storage
gitlab -[#32CD32]--> redis
sidekiq -[#ff8dd1]--> gitaly
sidekiq -[#ff8dd1]-> object_storage
sidekiq -[#ff8dd1]--> postgres
sidekiq -[#ff8dd1]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 40 RPS or 2,000 users, we recommend a total Puma worker count of around 12 so in turn it's recommended to run at
least 3 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This allows the controllers to scale dynamically with the Webservice pods they serve, and takes advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 4 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts for the 40 RPS or 2,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/2k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/reference_architectures
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architectures
|
Recommended deployments at scale.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The GitLab reference architectures are validated, production-ready environment designs for deploying GitLab at scale. Each architecture provides detailed specifications that you can use or adapt based on your requirements.
## Available reference architectures
The following reference architectures are available as recommended starting points for your environment.
The architectures are named in terms of peak load, based on user count or requests per second (RPS). RPS is calculated based on average real data.
{{< alert type="note" >}}
Each architecture is designed to be [scalable and elastic](#scaling-an-environment). They can be adjusted accordingly based on your workload, upwards or downwards. For example, some known heavy scenarios such as using [large monorepos](#large-monorepos) or notable [additional workloads](#additional-workloads).
{{< /alert >}}
For details about what each reference architecture is tested against, see the **Testing Methodology** section of each page.
### GitLab package (Omnibus)
The following is the list of Linux package based reference architectures:
- [Up to 20 RPS or 1,000 users](1k_users.md) <span style="color: #74717A;">_API: 20 RPS, Web: 2 RPS, Git (Pull): 2 RPS, Git (Push): 1 RPS_</span>
- [Up to 40 RPS or 2,000 users](2k_users.md) <span style="color: #74717A;">_API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS_</span>
- [Up to 60 RPS or 3,000 users](3k_users.md) <span style="color: #74717A;">_API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS_</span>
- [Up to 100 RPS or 5,000 users](5k_users.md) <span style="color: #74717A;">_API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS_</span>
- [Up to 200 RPS or 10,000 users](10k_users.md) <span style="color: #74717A;">_API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS_</span>
- [Up to 500 RPS or 25,000 users](25k_users.md) <span style="color: #74717A;">_API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS_</span>
- [Up to 1000 RPS or 50,000 users](50k_users.md) <span style="color: #74717A;">_API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS_</span>
### Cloud native hybrid
The following is a list of Cloud Native Hybrid reference architectures, where select recommended components can be run in Kubernetes:
- [Up to 40 RPS or 2,000 users](2k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS_</span>
- [Up to 60 RPS or 3,000 users](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS_</span>
- [Up to 100 RPS or 5,000 users](5k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS_</span>
- [Up to 200 RPS or 10,000 users](10k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS_</span>
- [Up to 500 RPS or 25,000 users](25k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS_</span>
- [Up to 1000 RPS or 50,000 users](50k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS_</span>
## Before you start
First, consider whether a self-managed approach is the right choice for you and your requirements.
Running any application in production is complex, and the same applies for GitLab. While we aim to make this as smooth as possible, there are still the general complexities based on your design. Typically you have to manage all aspects such as hardware, operating systems, networking, storage, security, GitLab itself, and more. This includes both the initial setup of the environment and the longer term maintenance.
You must have a working knowledge of running and maintaining applications in production if you decide to go down this route. If you aren't in this position, our [Professional Services](https://about.gitlab.com/services/#implementation-services) team offers implementation services. Those who want a more managed solution long term, can explore our other offerings such as [GitLab SaaS](../../subscriptions/gitlab_com/_index.md) or [GitLab Dedicated](../../subscriptions/gitlab_dedicated/_index.md).
If you are considering using the GitLab Self-Managed approach, we encourage you to read through this page in full, specifically the following sections:
- [Deciding which architecture to use](#deciding-which-architecture-to-start-with)
- [Large monorepos](#large-monorepos)
- [Additional workloads](#additional-workloads)
## Deciding which architecture to start with
The reference architectures are designed to strike a balance between three important factors: performance, resilience, and cost. They are designed to make it easier to set up GitLab at scale. However, it can still be a challenge to know which one meets your requirements and where to start accordingly.
As a general guide, **the more performant and/or resilient you want your environment to be, the more complex it is**.
This section explains the things to consider when picking a reference architecture.
### Expected load (RPS or user count)
The right architecture size depends primarily on your environment's expected peak load. The most objective measure of this load is through peak Requests per Second (RPS) coming into the environment.
Each architecture is designed to handle specific RPS targets for different types of requests (API, Web, Git). These details are described in the **Testing Methodology** section on each page.
Finding out the RPS can depend notably on the specific environment setup and monitoring stack. Some potential options include:
- [GitLab Prometheus](../monitoring/prometheus/_index.md#sample-prometheus-queries) with queries like `sum(irate(gitlab_transaction_duration_seconds_count{controller!~'HealthController|MetricsController'}[1m])) by (controller, action)`.
- [`get-rps` script](https://gitlab.com/gitlab-com/support/toolbox/dotfiles/-/blob/main/scripts/get-rps.rb?ref_type=heads) from GitLab Support.
- Other monitoring solutions.
- Load Balancer statistics.
If you can't determine your RPS, we provide an alternative sizing method based on equivalent User Count by Load Category. This count is mapped to typical RPS values, considering both manual and automated usage.
#### Initial sizing guide
To determine which architecture to pick for the expected load, see the following initial sizing guide table:
<table class="ra-table">
<col>
<tr>
<th style="text-align: center" rowspan="2"><br/>Load Category</th>
<th style="text-align: center" colspan="4" scope="colgroup">Requests per Second (RPS)</th>
<th rowspan="2" style="text-align: center"><br/>Typical User Count</th>
<th rowspan="2" style="text-align: center"><br/>Reference Architecture</th>
</tr>
<tr>
<th scope="col" style="text-align: center">API</th>
<th scope="col" style="text-align: center">Web</th>
<th scope="col" style="text-align: center">Git Pull</th>
<th scope="col" style="text-align: center">Git Push</th>
</tr>
<tr>
<td>X Small</td>
<td>20</td>
<td>2</td>
<td>2</td>
<td>1</td>
<td>1,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/1k_users.html">Up to 20 RPS or 1,000 users</a></th>
</tr>
<tr>
<td>Small</td>
<td>40</td>
<td>4</td>
<td>4</td>
<td>1</td>
<td>2,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/2k_users.html">Up to 40 RPS or 2,000 users</a></th>
</tr>
<tr>
<td>Medium</td>
<td>60</td>
<td>6</td>
<td>6</td>
<td>1</td>
<td>3,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/3k_users.html">Up to 60 RPS or 3,000 users</a></th>
</tr>
<tr>
<td>Large</td>
<td>100</td>
<td>10</td>
<td>10</td>
<td>2</td>
<td>5,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/5k_users.html">Up to 100 RPS or 5,000 users</a></th>
</tr>
<tr>
<td>X Large</td>
<td>200</td>
<td>20</td>
<td>20</td>
<td>4</td>
<td>10,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/10k_users.html">Up to 200 RPS or 10,000 users</a></th>
</tr>
<tr>
<td>2X Large</td>
<td>500</td>
<td>50</td>
<td>50</td>
<td>10</td>
<td>25,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/25k_users.html">Up to 500 RPS or 25,000 users</a></th>
</tr>
<tr>
<td>3X Large</td>
<td>1000</td>
<td>100</td>
<td>100</td>
<td>20</td>
<td>50,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/50k_users.html">Up to 1000 RPS or 50,000 users</a></th>
</tr>
</table>
{{< alert type="note" >}}
Before you select an initial architecture, review this section thoroughly. Consider other factors such as High Availability (HA) or use of large monorepos because they may impact the choice beyond just RPS or user count.
{{< /alert >}}
#### If in doubt, start large, monitor, and then scale down
If you're uncertain about the required environment size, consider starting with a larger size, [monitoring](#monitoring) it, and then [scaling down](#scaling-an-environment) accordingly if the metrics support your situation.
Starting large and then scaling down is a prudent approach when:
- You can't determine RPS
- The environment load could be atypically higher than expected
- You have [large monorepos](#large-monorepos) or notable [additional workloads](#additional-workloads)
For example, if you have 3,000 users but also know that there's automation at play that would significantly increase the concurrent load, then you could start with a 100 RPS / 5k User class environment, monitor it, and if the metrics support it, scale down all components at once, or one by one.
### Standalone (non-HA)
For environments serving 2,000 or fewer users, it's generally recommended to follow a standalone approach by deploying a non-HA, single, or multi-node environment. With this approach, you can employ strategies such as [automated backups](../backup_restore/backup_gitlab.md#configuring-cron-to-make-daily-backups) for recovery. These strategies provide a good level of recovery time objective (RTO) or recovery point objective (RPO) while avoiding the complexities that come with HA.
With standalone setups, especially single node environments, various options are available for [installation](../../install/_index.md) and management. The options include [the ability to deploy directly by using select cloud provider marketplaces](https://page.gitlab.com/cloud-partner-marketplaces.html) that reduce the complexity a little further.
### High Availability (HA)
High Availability ensures every component in the GitLab setup can handle failures through various mechanisms. However, to achieve this is complex, and the environments required can be sizable.
For environments serving 3,000 or more users, we generally recommend using an HA strategy. At this level, outages have a bigger impact against more users. All the architectures in this range have HA built in by design for this reason.
#### Do you need High Availability (HA)?
As mentioned previously, achieving HA comes at a cost. The environment requirements are sizable as each component needs to be multiplied, which comes with additional actual and maintenance costs.
For a lot of our customers with fewer than 3,000 users, we've found that a backup strategy is sufficient and even preferable. While this does have a slower recovery time, it also means you have a much smaller architecture and less maintenance costs as a result.
As a general guideline, employ HA only in the following scenarios:
- When you have 3,000 or more users.
- When GitLab being down would critically impact your workflow.
#### Scaled-down High Availability (HA) approach
If you still need HA for fewer users, you can achieve it with an adjusted [3K architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
#### Zero-downtime upgrades
[Zero-downtime upgrades](../../update/zero_downtime.md) are available for standard environments with HA (Cloud Native Hybrid is [not supported](https://gitlab.com/groups/gitlab-org/cloud-native/-/epics/52)). This allows for an environment to stay up during an upgrade. However, this process is more complex as a result and has some limitations as detailed in the documentation.
When going through this process, it's worth noting that there may still be brief moments of downtime when the HA mechanisms take effect.
In most cases, the downtime required for doing an upgrade shouldn't be substantial. Use this approach only if it's a key requirement for you.
### Cloud Native Hybrid (Kubernetes HA)
As an additional layer of HA resilience, you can deploy select components in Kubernetes, known as a Cloud Native Hybrid reference architecture. For stability
reasons, stateful components such as Gitaly [cannot be deployed in Kubernetes](#stateful-components-in-kubernetes).
Cloud Native Hybrid is an alternative and more **advanced** setup compared to a standard reference architecture. Running services in Kubernetes is complex. **Use this setup** only if you have strong working knowledge and experience in Kubernetes.
### GitLab Geo (Cross Regional Distribution / Disaster Recovery)
With [GitLab Geo](../geo/_index.md), you can achieve distributed environments in
different regions with a full Disaster Recovery (DR) setup in place. GitLab Geo
requires at least two separate environments:
- One primary site.
- One or more secondary sites that serve as replicas.
If the primary site becomes unavailable, you can fail over to one of the secondary sites.
Use this **advanced and complex** setup only if DR is
a key requirement for your environment. You must also make additional decisions
on how each site is configured. For example, if each secondary site would be the
same architecture as the primary or if each site is configured for HA.
### Large monorepos / Additional workloads
[Large monorepos](#large-monorepos) or significant [additional workloads](#additional-workloads) can affect the performance of the environment notably. Some adjustments may be required depending on the context.
If this situation applies to you, reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/)
for further guidance.
### Cloud provider services
For all the previously described strategies, you can run select GitLab components on equivalent cloud provider services such as the PostgreSQL database or Redis.
For more information, see the [recommended cloud providers and services](#recommended-cloud-providers-and-services).
### Decision Tree
Read through the guidance documented previously in full first before you refer to the following decision tree.
```mermaid
%%{init: { 'theme': 'base' } }%%
graph TD
L0A(<b>What Reference Architecture should I use?</b>)
L1A(<b>What is your <a href=#expected-load-rps--user-count>expected load</a>?</b>)
L2A("60 RPS / 3,000 users or more?")
L2B("40 RPS / 2,000 users or less?")
L3A("<a href=#do-you-need-high-availability-ha>Do you need HA?</a><br>(or zero-downtime upgrades)")
L3B[Do you have experience with<br/>and want additional resilience<br/>with select components in Kubernetes?]
L4A><b>Recommendation</b><br><br>60 RPS / 3,000 user architecture with HA<br>and supported reductions]
L4B><b>Recommendation</b><br><br>Architecture closest to <a href=#expected-load-rps--user-count>expected load</a> with HA]
L4C><b>Recommendation</b><br><br>Cloud Native Hybrid architecture<br>closest to <a href=#expected-load-rps--user-count>expected load</a>]
L4D>"<b>Recommendation</b><br><br>Standalone 20 RPS / 1,000 user or 40 RPS / 2,000 user<br/>architecture with Backups"]
L0A --> L1A
L1A --> L2A
L1A --> L2B
L2A -->|Yes| L3B
L3B -->|Yes| L4C
L3B -->|No| L4B
L2B --> L3A
L3A -->|Yes| L4A
L3A -->|No| L4D
L5A("<a href=#gitlab-geo-cross-regional-distribution--disaster-recovery>Do you need cross regional distribution</br> or disaster recovery?"</a>) --> |Yes| L6A><b>Additional Recommendation</b><br><br> GitLab Geo]
L4A ~~~ L5A
L4B ~~~ L5A
L4C ~~~ L5A
L4D ~~~ L5A
L5B("Do you have <a href=#large-monorepos>Large Monorepos</a> or expect</br> to have substantial <a href=#additional-workloads>additional workloads</a>?") --> |Yes| L6B><b>Additional Recommendations</b><br><br><a href=#if-in-doubt---start-large-monitor-and-scale-down>Start large, monitor and scale down</a><br><br> Contact GitLab representative or Support]
L4A ~~~ L5B
L4B ~~~ L5B
L4C ~~~ L5B
L4D ~~~ L5B
classDef default fill:#FCA326
linkStyle default fill:none,stroke:#7759C2
```
## Requirements
Before implementing a reference architecture, see the following requirements and guidance.
### Supported machine types
The architectures are designed to be flexible in terms of machine type selection while ensuring consistent performance. While we provide specific machine type examples in each reference architecture, these are not intended to be prescriptive defaults.
You can use any machine types that meet or exceed the specified requirements for each component, such as:
- Newer generation machine types (like GCP `n2` series or AWS `m6` series)
- Different architectures like ARM-based instances (such as AWS Graviton)
- Alternative machine type families that better match your specific workload characteristics (such as higher network bandwidth)
This guidance is also applicable for any Cloud Provider services such as AWS RDS.
{{< alert type="note" >}}
Any "burstable" instance types are not recommended due to inconsistent performance.
{{< /alert >}}
{{< alert type="note" >}}
For details about what machine types we test against and how, refer to [validation and test results](#validation-and-test-results).
{{< /alert >}}
### Supported disk types
Most standard disk types are expected to work for GitLab. However, be aware of the following specific call-outs:
- Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
- We don't recommend the use of any disk types that are "burstable" due to inconsistent performance.
Other disk types are expected to work with GitLab. Choose based on your requirements such as durability or cost.
### Supported infrastructure
GitLab should run on most infrastructures such as reputable cloud providers (AWS, GCP, Azure) and
their services, or self-managed (ESXi) that meet both:
- The specifications detailed in each architecture.
- Any requirements in this section.
However, this does not guarantee compatibility with every potential permutation.
See [Recommended cloud providers and services](#recommended-cloud-providers-and-services) for more information.
### Networking (High Availability)
Below are the network requirements for running GitLab in a High Availability fashion.
#### Network latency
Network latency should be as low as possible to allow for synchronous replication across the GitLab application, such as database replication. Generally this should be lower than 5 ms.
#### Availability zones (Cloud Providers)
Deploying across availability zones is supported and generally recommended for additional resilience. You should use an odd number of zones to align with GitLab application requirements, as some components use an odd number of nodes for quorum voting.
#### Data centers (Self Hosted)
Deploying across multiple self-hosted data centers is possible but requires careful consideration. This requires synchronous capable latency between centers, robust redundant network links to prevent split-brain scenarios, all centers located in the same geographic region, and deployment across an odd number of centers for proper quorum voting (like [availability zones](#availability-zones-cloud-providers)).
{{< alert type="note" >}}
It may not be possible for GitLab Support to assist with infrastructure-related issues stemming from multi-data center deployments.
Choosing to deploy across centers is generally at your own risk.
{{< /alert >}}
{{< alert type="warning" >}}
It is not supported to deploy a single [GitLab environment across different regions](#deploying-one-environment-over-multiple-regions). Data centers should be in the same region.
{{< /alert >}}
### Large Monorepos
The architectures were tested with repositories of varying sizes that follow best practices.
**However, [large monorepos](../../user/project/repository/monorepos/_index.md) (several gigabytes or more) can significantly impact the performance of Git and in turn the environment itself**.
Their presence and how they are used can put a significant strain on the entire system from Gitaly to the underlying infrastructure.
The performance implications are largely software in nature. Additional hardware resources lead to diminishing returns.
{{< alert type="warning" >}}
If this applies to you, we strongly recommend you follow the linked documentation and reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/) for further guidance.
{{< /alert >}}
Large monorepos come with notable cost. If you have such a repository,
follow these guidance to ensure good performance and to keep costs in check:
- [Optimize the large monorepo](../../user/project/repository/monorepos/_index.md). Using features such as
[LFS](../../user/project/repository/monorepos/_index.md#use-git-lfs-for-large-binary-files) to not store binaries, and other approaches for reducing repository size, can
dramatically improve performance and reduce costs.
- Depending on the monorepo, increased environment specifications may be required to compensate. Gitaly might require additional resources along with Praefect, GitLab Rails, and Load Balancers. This depends on the monorepo itself and its usage.
- When the monorepo is significantly large (20 gigabytes or more), further additional strategies may be required such as even further increased specifications or in some cases, a separate Gitaly backend for the monorepo alone.
- Network and disk bandwidth is another potential consideration with large monorepos. In very heavy cases, bandwidth saturation is possible if there's a high amount of concurrent clones (such as with CI). [Reduce full clones wherever possible](../../user/project/repository/monorepos/_index.md#reduce-concurrent-clones-in-cicd) in this scenario. Otherwise, additional environment specifications may be required to increase bandwidth. This differs based on cloud providers.
### Additional workloads
These architectures have been [designed and tested](#validation-and-test-results) for standard GitLab
setups based on real data.
However, additional workloads can multiply the impact of operations by triggering follow-up actions.
You might have to adjust the suggested specifications to compensate if you use:
- Security software on the nodes.
- Hundreds of concurrent CI jobs for [large repositories](../../user/project/repository/monorepos/_index.md).
- Custom scripts that [run at high frequency](../logs/log_parsing.md#print-top-api-user-agents).
- [Integrations](../../integration/_index.md) in many large projects.
- [Server hooks](../server_hooks.md).
- [System hooks](../system_hooks.md).
Generally, you should have robust monitoring in place to measure the impact of any additional workloads to
inform any changes needed to be made. Reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/)
for further guidance.
### Load Balancers
The architectures make use of up to two load balancers depending on the class:
- External load balancer - Serves traffic to any external facing components, primarily Rails.
- Internal load balancer - Serves traffic to select internal components that are deployed in an HA fashion such as Praefect or PgBouncer.
The specifics on which load balancer to use, or its exact configuration is beyond the scope of GitLab documentation. The most common options
are to set up load balancers on machine nodes or to use a service such as one offered by cloud providers. If deploying a Cloud Native Hybrid environment, the charts can handle the external load balancer setup by using Kubernetes Ingress.
Each architecture class includes a recommended base machine size to deploy directly on machines. However, they may need adjustment based on factors such as the chosen load balancer and expected workload. Of note machines can have varying [network bandwidth](#network-bandwidth) that should also be taken into consideration.
The following sections provide additional guidance for load balancers.
#### Balancing algorithm
To ensure equal spread of calls to the nodes and good performance, use a least-connection-based load balancing algorithm or equivalent wherever possible.
We don't recommend the use of round-robin algorithms as they are known to not spread connections equally in practice.
#### Network Bandwidth
The total network bandwidth available to a load balancer when deployed on a machine can vary notably across cloud providers. Some cloud providers, like [AWS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html), may operate on a burst system with credits to determine the bandwidth at any time.
The required network bandwidth for your load balancers depends on factors such as data shape and workload. The recommended base sizes for each architecture class have been selected based on real data. However, in some scenarios such as consistent clones of [large monorepos](#large-monorepos), you might have to adjust the sizes accordingly.
### No swap
Swap is not recommended in the reference architectures. It's a failsafe that impacts performance greatly. The
architectures are designed to have enough memory in most cases to avoid the need for swap.
### Praefect PostgreSQL
[Praefect requires its own database server](../gitaly/praefect/configure.md#postgresql). To achieve full HA, a third-party PostgreSQL database solution is required.
We hope to offer a built-in solution for these restrictions in the future. In the meantime, a non-HA PostgreSQL server
can be set up using the Linux package as the specifications reflect. For more details, see the following issues:
- [`omnibus-gitlab#7292`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
- [`gitaly#3398`](https://gitlab.com/gitlab-org/gitaly/-/issues/3398).
## Recommended cloud providers and services
{{< alert type="note" >}}
The following lists are non-exhaustive. Other cloud providers not listed
here may work with the same specifications, but they have not been validated.
For the cloud provider services not listed here,
use caution because each implementation can be notably different.
Test thoroughly before using them in production.
{{< /alert >}}
The following architectures are recommended for the following cloud providers based on testing and real life usage:
<table>
<thead>
<tr>
<th>Reference Architecture</th>
<th>GCP</th>
<th>AWS</th>
<th>Azure</th>
<th>Bare Metal</th>
</tr>
</thead>
<tbody>
<tr>
<td>Linux package</td>
<td>🟢</td>
<td>🟢</td>
<td>🟢<sup>1</sup></td>
<td>🟢</td>
</tr>
<tr>
<td>Cloud Native Hybrid</td>
<td>🟢</td>
<td>🟢</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Additionally, the following cloud provider services are recommended for use as part of the architectures:
<table>
<thead>
<tr>
<th>Cloud Service</th>
<th>GCP</th>
<th>AWS</th>
<th>Azure</th>
<th>Bare Metal</th>
</tr>
</thead>
<tbody>
<tr>
<td>Object Storage</td>
<td>🟢 <a href="https://cloud.google.com/storage" target="_blank">Cloud Storage</a></td>
<td>🟢 <a href="https://aws.amazon.com/s3/" target="_blank">S3</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/storage/blobs" target="_blank">Azure Blob Storage</a></td>
<td>🟢 <a href="https://min.io/" target="_blank">MinIO</a></td>
</tr>
<tr>
<td>Database</td>
<td>🟢 <a href="https://cloud.google.com/sql" target="_blank" rel="noopener noreferrer">Cloud SQL<sup>1</sup></a></td>
<td>🟢 <a href="https://aws.amazon.com/rds/" target="_blank" rel="noopener noreferrer">RDS</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/postgresql/" target="_blank" rel="noopener noreferrer">Azure Database for PostgreSQL Flexible Server</a></td>
<td></td>
</tr>
<tr>
<td>Redis</td>
<td>🟢 <a href="https://cloud.google.com/memorystore" target="_blank" rel="noopener noreferrer">Memorystore</a></td>
<td>🟢 <a href="https://aws.amazon.com/elasticache/" target="_blank" rel="noopener noreferrer">ElastiCache</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/cache" target="_blank" rel="noopener noreferrer">Azure Cache for Redis (Premium)</a></td>
<td></td>
</tr>
</tbody>
</table>
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. For optimal performance, especially in larger environments (500 RPS / 25k users or higher), use the [Enterprise Plus edition](https://cloud.google.com/sql/docs/editions-intro) for GCP Cloud SQL. You might have to adjust the maximum connections higher than the service's defaults, depending on your workload.
2. To ensure good performance, deploy the [Premium tier of Azure Cache for Redis](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-overview#service-tiers).
<!-- markdownlint-enable MD029 -->
### Best practices for the database services
If you choose to use a third-party external service, use an [external database service](../postgresql/external.md) that runs a standard, performant, and [supported PostgreSQL version](../../install/requirements.md#postgresql) and take note of the following considerations:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer, and Consul. All of these components are no longer required when using a third party external service.
1. For optimal performance, enable [Database Load Balancing](../postgresql/database_load_balancing.md) with Read Replicas. Match the node counts to those used in standard Linux package deployments. This approach is particularly important for larger environments (more than 200 requests per second or 10,000+ users).
1. Database Connection Poolers are not required for this setup as the options vary per service. As a result, you might have to adjust the connection count configuration, depending on the environment size. If Pooling is desired, a third party option must be explored as the GitLab Linux Package bundled PgBouncer is only compatible with the package bundled Postgres. [Database Load Balancing](../postgresql/database_load_balancing.md) can also be used to spread the load accordingly.
- Ensure that if a pooler is included in a Cloud Provider service, it can handle the total load without bottlenecks. For example, Azure Database for PostgreSQL flexible server can optionally deploy a PgBouncer pooler in front of the database. However, PgBouncer is single threaded, which may cause bottlenecks under heavy load. To mitigate this issue, you can use database load balancing to distribute the pooler across multiple nodes.
1. The number of nodes required for HA may vary depending on the service. The requirements for one deployment may vary from those for Linux package installations.
1. To use [GitLab Geo](../geo/_index.md), the service should support cross-region replication.
#### Unsupported database services
The following database cloud provider services are not recommended due to lack of support or known issues:
- [Amazon Aurora](https://aws.amazon.com/rds/aurora/) is incompatible and not supported. For more details, see [14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
- [Azure Database for PostgreSQL Single Server](https://azure.microsoft.com/en-gb/products/postgresql/#overview) is not supported as the service is now deprecated and runs on an unsupported version of PostgreSQL. It also has notable performance and stability issues.
- [Google AlloyDB](https://cloud.google.com/alloydb) and [Amazon RDS Multi-AZ DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/multi-az-db-clusters-concepts.html) are not tested and are not recommended. Both solutions are not expected to work with GitLab Geo.
- [Amazon RDS Multi-AZ DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZSingleStandby.html) is a separate product and is supported.
### Best practices for Redis services
Use an [external Redis service](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) that runs a standard, performant, and supported version. The service must support:
- Redis Standalone (Primary x Replica) mode - Redis Cluster mode is specifically not supported
- High availability through replication
- The ability to set the [Redis eviction policy](../redis/replication_and_failover_external.md#setting-the-eviction-policy)
Redis is primarily single threaded. For environments targeting the 200 RPS / 10,000 users class or larger, separate the instances into cache & persistent data to achieve optimum performance.
{{< alert type="note" >}}
Serverless variants of Redis services are not supported at this time.
{{< /alert >}}
### Best practices for object storage
GitLab has been tested against [various object storage providers](../object_storage.md#supported-object-storage-providers) that are expected to work.
Use a reputable solution that has full S3 compatibility.
## Deviating from the suggested reference architectures
The further away you move from the reference architectures,
the harder it is to get support. With each deviation, you introduce
a layer of complexity that complicates troubleshooting potential
issues.
These architectures use the official Linux packages or [Helm Charts](https://docs.gitlab.com/charts/) to
install and configure the various components. The components are
installed on separate machines (virtualized or Bare Metal). Machine hardware
requirements listed in the **Configuration** column. Equivalent VM standard sizes are listed
in the GCP/AWS/Azure columns of each [available architecture](#available-reference-architectures).
You can run GitLab components on Docker, including Docker Compose. Docker is well supported and provides consistent specifications across environments.
However, it is still an additional layer and might add some support complexities. For example, not being able to run `strace` in containers.
### Unsupported designs
While we try to have a good range of support for GitLab environment designs, certain approaches don't work effectively. The following sections detail these unsupported approaches.
#### Stateful components in Kubernetes
[Running stateful components in Kubernetes, such as Gitaly Cluster (Praefect), is not supported](https://docs.gitlab.com/charts/installation/#configure-the-helm-chart-to-use-external-stateful-data).
Gitaly Cluster (Praefect) is only supported on conventional virtual machines. Kubernetes strictly limits memory usage. However, the memory usage of Git is unpredictable, which
can cause sporadic out of memory (OOM) termination of Gitaly pods. The OOM termination leads to significant disruptions and potential data loss. Hence, Gitaly is not tested
or supported in Kubernetes. For more information, see [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127).
This applies to stateful components such as Postgres and Redis. You can use other supported cloud provider services, unless specifically called out as unsupported.
#### Autoscaling of stateful nodes
As a general guidance, only stateless components of GitLab can be run in autoscaling groups, namely GitLab Rails
and Sidekiq. Other components that have state, such as Gitaly, are not supported in this fashion. For more information, see [issue 2997](https://gitlab.com/gitlab-org/gitaly/-/issues/2997).
This applies to stateful components such as Postgres and Redis. You can use other supported cloud provider services, unless specifically called out as unsupported.
[Cloud Native Hybrid setups](#cloud-native-hybrid) are generally preferred over autoscaling groups. Kubernetes better handles components that can only run on one node,
such as database migrations and [Mailroom](../incoming_email.md).
#### Deploying one environment over multiple regions
GitLab does not support deploying a single environment across multiple regions. These setups can result in significant issues, such as excessive network latency or split-brain scenarios if connectivity between regions fails.
Several GitLab components perform synchronous replication or require an odd number of nodes to function correctly, such as Consul, Redis Sentinel, and Praefect. Distributing these components across multiple regions with high latency can severely impact their functionality and the overall system performance.
This limitation applies to all potential GitLab environment setups, including Cloud Native Hybrid alternatives.
For deploying GitLab over multiple data centers or regions, we offer [GitLab Geo](../geo/_index.md) as a comprehensive solution.
## Validation and test results
GitLab
does regular smoke and performance tests for these architectures to ensure they
remain compliant.
### How we perform the tests
Testing is conducted using specific coded workloads derived from sample customer data, utilizing both the [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) for environment deployment with Terraform and Ansible, and the [GitLab Performance Tool (GPT)](https://gitlab.com/gitlab-org/quality/performance) for performance testing with k6.
Testing is performed primarily on GCP and AWS using their standard compute offerings (n1 series for GCP, m5 series for AWS) as baseline configurations. These machine types were selected as a lowest common denominator target to ensure broad compatibility. Using different or newer machine types that meet the CPU and memory requirements is fully supported - see [Supported Machine Types](#supported-machine-types) for more information. The architectures are expected to perform similarly on any hardware meeting the specifications, whether on other cloud providers or on-premises.
### Performance targets
Each reference architecture is tested against specific throughput targets based on real customer data. For every 1,000 users, we test:
- API: 20 RPS
- Web: 2 RPS
- Git (Pull): 2 RPS
- Git (Push): 0.4 RPS (rounded to the nearest integer)
The listed RPS targets were selected based on real customer data of total environmental loads corresponding to the user count, including CI and other workloads.
{{< alert type="note" >}}
Network latency between components in test environments was observed at <5 ms but note this is not intended as a hard requirement.
{{< /alert >}}
### Test coverage and results
Testing is designed to be effective and provide good coverage for all reference architecture targets. Testing frequency varies by architecture type and size:
- Linux package environments: Daily or weekly of all sizes on GCP and AWS.
- Cloud Native environments: Weekly testing of select configurations on GCP and AWS.
Our testing also includes prototype variations of these architectures being explored for potential future inclusion. Test results are publicly available on the [Reference Architecture wiki](https://gitlab.com/gitlab-org/reference-architectures/-/wikis/Benchmarks/Latest).
## Maintaining a reference architecture environment
Maintaining a reference architecture environment is generally the same as any other GitLab environment.
In this section you can find links to documentation for relevant areas and specific architecture notes.
### Scaling an environment
The reference architectures are designed as a starting point, and are elastic and scalable throughout. You might want to adjust the environment for your specific needs after deployment for reasons such as additional performance capacity or reduced costs. This behavior is expected. Scaling can be done iteratively or wholesale to the next architecture size, if metrics suggest that a component is exhausted.
{{< alert type="note" >}}
If a component is continuously exhausting its given resources, reach out to our [Support team](https://about.gitlab.com/support/) before performing any significant scaling.
{{< /alert >}}
For most components, vertical and horizontal scaling can be applied as usual. However, before doing so, be aware of the following caveats:
- When scaling Puma or Sidekiq vertically, the amount of workers must be adjusted to use the additional specifications. Puma is scaled automatically on the next reconfigure. However, you might have to [change Sidekiq configuration beforehand](../sidekiq/extra_sidekiq_processes.md#start-multiple-processes).
- Redis and PgBouncer are primarily single threaded. If these components are seeing CPU exhaustion, they might have to be scaled out horizontally.
- The Consul, Redis Sentinel, and Praefect components require an odd number of nodes for a voting quorum when deployed in HA form.
- Scaling certain components significantly can result in notable knock on effects that affect the performance of the environment. For more guidance, see [Scaling knock on effects](#scaling-knock-on-effects).
Conversely, if you have robust metrics in place that show the environment is over-provisioned, you can scale downwards.
You should take an iterative approach when scaling downwards, to ensure there are no issues.
#### Scaling knock on effects
In some cases, scaling a component significantly may result in knock on effects for downstream components, impacting performance. The architectures are designed with balance in mind to ensure components that depend on each other are congruent in terms of specifications. Notably scaling a component may result in additional throughput being passed to the other components it depends on. As a result, you could have to scale these other dependent components as well.
{{< alert type="note" >}}
The architectures have been designed to have elasticity to accommodate an upstream component being scaled. However, reach out to our [Support team](https://about.gitlab.com/support/) before you make any significant changes to your environment to be safe.
{{< /alert >}}
The following components can impact others when they have been significantly scaled:
- Puma and Sidekiq - Notable scale ups of either Puma or Sidekiq workers will result in higher concurrent connections to the internal load balancer, PostgreSQL (via PgBouncer if present), Gitaly (via Praefect if present) and Redis.
- Redis is primarily single-threaded. In some cases, you might have to split Redis into separate instances (for example, cache and persistent) if the increased throughput causes CPU exhaustion in a combined cluster.
- PgBouncer is also single threaded but a scale out might result in a new pool being added that in turn might increase the total connections to Postgres. It's strongly recommended to only do this if you have experience in managing Postgres connections and to seek assistance if in doubt.
- Gitaly Cluster (Praefect)/PostgreSQL - A notable scale out of additional nodes can have a detrimental effect on the HA system and performance due to increased replication calls to the primary node.
#### Scaling from a non-HA to an HA architecture
In most cases, vertical scaling is only required to increase an environment's resources. However, if you are moving to an HA environment,
additional steps are required for the following components to switch over to their HA forms.
For more information, see the following documentation:
- [Redis to multi-node Redis w/ Redis Sentinel](../redis/replication_and_failover.md#switching-from-an-existing-single-machine-installation)
- [Postgres to multi-node Postgres w/ Consul + PgBouncer](../postgresql/moving.md)
- [Gitaly to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect)
### Upgrades
Upgrading a reference architecture environment is the same as any other GitLab environment. For more information, see
[upgrade GitLab](../../update/_index.md). [Zero-downtime upgrades](#zero-downtime-upgrades) are also available.
{{< alert type="note" >}}
You should upgrade a reference architecture in the same order as you created it.
{{< /alert >}}
### Monitoring
You can monitor your infrastructure and [GitLab](../monitoring/_index.md) using various options. See the selected monitoring solution's documentation for more information.
{{< alert type="note" >}}
GitLab application is bundled with [Prometheus and various Prometheus compatible exporters](../monitoring/prometheus/_index.md) that could be hooked into your solution.
{{< /alert >}}
## Update history
The following is a history of notable updates for reference architectures (2021-01-01 onward, ascending order). We aim to update it at least once per quarter.
You can find a full history of changes [on the GitLab project](https://gitlab.com/gitlab-org/gitlab/-/merge_requests?scope=all&state=merged&label_name%5B%5D=Reference%20Architecture&label_name%5B%5D=documentation).
**2025**:
- [2025-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/199549): Updated Gitaly configurations to use [Gitaly roles](https://docs.gitlab.com/omnibus/roles/#gitaly-roles).
- [2025-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181145): Added further clarity around supported machine types and that the listed examples are not intended as prescriptive defaults.
**2024**:
- [2024-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/175854): Added _Start Large_ section as further guidance for choosing initial sizing.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/164181): Updated Expected Load section with some more examples on how to calculate RPS.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/163478): Updated Redis configuration on 40 RPS or 2k User page to have correct Redis configuration.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/163506): Updated Sidekiq configuration for Prometheus in Monitoring node on 2k.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/162144): Added Next Steps breadcrumb section to the pages to help discoverability of additional features.
- [2024-05](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/153716): Updated the 60 RPS or 3k User and 100 RPS or 5k User pages to have latest Redis guidance on co-locating Redis Sentinel with Redis itself.
- [2024-05](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/153579): Renamed `Cost to run` section to `Cost calculator templates` to better reflect the calculators are only a starting point and need to be adjusted with specific usage to give more accurate cost estimates.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/149878): Updated recommended sizing for Webservice nodes for Cloud Native Hybrids on GCP. Also adjusted NGINX pod recommendation to be run on Webservice node pool as a DaemonSet.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/149528): Updated 20 RPS / 1,000 User architecture specs to follow recommended memory target of 16 GB.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148313): Updated Reference Architecture titles to include RPS for further clarity and to help right sizing.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145436): Updated recommended sizing for Load Balancer nodes if deployed on VMs. Also added notes on network bandwidth considerations.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/143539): Removed the Sidekiq Maximum Concurrency setting in examples as this is deprecated and no longer required to be set explicitly.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/143539): Adjusted the Sidekiq recommendations on 2k to disable Sidekiq on Rails nodes and updated architecture diagram.
- [2024-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/140465): Updated recommendations for Azure for all Reference Architecture sizes and latest cloud services.
**2023**:
- [2023-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/139557): Updated notes on Load Balancers to be more reflective that any reputable offering is expected to work.
- [2023-11-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133457): Expanded details on what each Reference Architecture is designed for, the testing methodology used and added details on how to scale environments.
- [2023-11-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/134632): Added expanded notes on disk types, object storage and monitoring.
- [2023-10-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/134518): Adjusted Sidekiq configuration example to use Linux Package role.
- [2023-10-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133835): Adjusted the Sidekiq recommendations to include a separate node for 2k and tweaks to instance type and counts for 3k and 5k.
- [2023-10-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132270): Added more expanded notes throughout to warn about the use of Large Monorepos and their impacts for increased awareness.
- [2023-10-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133258): Updated name of Task Runner pod to its new name of Toolbox.
- [2023-10-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132961): Expanded guidance on using an external service for Redis further, in particular for separated Cache and Persistent services with 10k and up.
- [2023-09-21](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132289): Expanded details on the challenges of running Gitaly in Kubernetes.
- [2023-09-20](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132275): Removed references to Grafana after deprecation and removal.
- [2023-08-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130470): Expanded section on Geo under the Decision Tree.
- [2023-08-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128529): Switched configuration example to use the Sidekiq role for Linux package.
- [2023-08-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128374): Fixed an AWS Machine type typo for the 50k architecture.
- [2023-06-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125017): Update PostgreSQL configuration examples to remove a now unneeded setting to instead use the Linux package default.
- [2023-06-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125017): Added explicit example on main page that reflects Google Memorystore is recommended.
- [2023-06-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/122063): Fixed IP examples for the 3k and 5k architectures.
- [2023-05-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/121545): Expanded notes on usage of external Cloud Provider Services and the recommendation of separated Redis servers for 10k environments and up.
- [2023-05-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/119224): Updated documentation to reflect correct requirement of Redis 6 instead of 5.
- [2023-04-28](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114877): Added a note that Azure Active Directory authentication method is not supported for use with Azure PostgreSQL Flexible service.
- [2023-03-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114877): Added more details about known unsupported designs.
- [2023-03-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114872): Updated Redis configuration examples for multi-node to have correct configuration to ensure all components can connect.
- [2023-03-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110784): Updated Gitaly configuration examples to the new format.
- [2023-03-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114495): Updated cost estimates to no longer include NFS VMs.
- [2023-02-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110379): Updated Praefect configuration examples to the new format.
- [2023-02-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/109798): Added examples of what automation may be considered additional workloads.
- [2023-02-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/111018): Added a new before you start section that gives more context about what's involved with running production software self-managed. Also added more details for Standalone setups and cloud provider services in the decision tree section.
- [2023-02-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110641): Switched to use more common complex terminology instead of the less known **involved**.
- [2023-01-31](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110328): Expanded and centralized the requirements section on the main page.
- [2023-01-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110183): Added notes on migrating Git data from NFS, that object data is still supported on NFS and handling SSH keys correctly across multiple Rails nodes.
**2022**:
- [2022-12-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105451): Removed guidance for using NFS for Git data as support for this is now ended with `15.6` or later.
- [2022-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106826): Added a note to clarify the difference between Amazon RDS Multi-AZ DB cluster and instance, with the latter being supported. Also, increase PostgreSQL maximum connections setting to new default of `500`.
- [2022-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106695): Updated Sidekiq maximum concurrency configuration to match new default of `20`.
- [2022-11-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/104236): Corrected guidance for Praefect and Gitaly in reduced 3k architecture section that an odd number quorum is required.
- [2022-11-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103623): Added guidance on how to handle GitLab Secrets in Cloud Native Hybrids and further links to the GitLab Charts documentation.
- [2022-11-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103767): Fixed a typo with Sidekiq configuration for the 10k architecture.
- [2022-11-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/102746): Added guidance on large monorepos and additional workloads impact on performance. Also, expanded Load Balancer guidance around SSL and a recommendation for least connection based routing methods.
- [2022-10-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100826): Adjusted Object Storage guidance to make it clearer that it's recommended over NFS.
- [2022-10-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100305): Updated guidance for Azure to recommend up to 2k only due to performance issues.
- [2022-09-27](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98204): Added the decision tree section to help users better decide what architecture to use.
- [2022-09-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98263): Added explicit step to enable Incremental Logging when only Object Storage is being used.
- [2022-09-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98184): Expanded guidance on recommended cloud providers and services.
- [2022-09-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/97245): Expanded Object Storage guidance and updated that NFS support for Git data ends with `15.6`.
- [2022-08-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96150): Added a clearer note about Gitaly Cluster not being supported in Kubernetes.
- [2022-08-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96021): Added a section on supported CPUs and types.
- [2022-08-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/95713): Updated architecture tables to be clearer for Object Storage support.
- [2022-08-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/95185): Increased Cloud Native Hybrid pool specifications for 2k architecture to ensure enough resources present for pods. Also, increased Sidekiq worker count.
- [2022-08-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93493): Added note to use newer Gitaly check command from GitLab `15.0` and later.
- [2022-07-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93141): Moved the troubleshooting section to a more general location.
- [2022-07-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/92144): Added guidance that Amazon Aurora is no longer compatible and not supported from GitLab `14.4.0` and later.
- [2022-07-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91943): Added call out note to remove the `default` section from Gitaly storages configuration as it's required.
- [2022-06-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/86812): Moved Incremental Logging guidance to a separate section.
- [2022-04-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85856): Expanded testing results' section with new regular pipelines.
- [2022-04-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85833): Updated Praefect configuration to reflect setting name changes.
- [2022-04-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85231): Added missing setting to enable Object Storage correctly.
- [2022-04-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85107): Expanded Cloud Native Hybrid guidance with AWS machine types.
- [2022-04-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/84389): Added cost estimates for AWS and Azure.
- [2022-04-06](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/84483): Updated configuration examples for most components to be correctly included for Prometheus monitoring auto discovery.
- [2022-03-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81538): Expanded validation and testing result's section with more clearly language and more detail.
- [2022-03-21](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/83019): Added a note saying additional specifications may be needed for Gitaly in some scenarios.
- [2022-03-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/82087): Added guidance for preventing the GitLab `kas` service running on nodes where not required.
- [2022-03-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81814): Fixed a typo for Praefect TLS port in configuration examples.
- [2022-02-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81247): Added guidance to enable the Gitaly Pack-objects cache.
- [2022-02-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80892): Added a general section on recommended Cloud Providers and services.
- [2022-02-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80521): Added link to a blog post about GPT testing added.
- [2022-01-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/78705): Merged testing process and cost estimates into one section with expanded details.
- [2022-01-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77968): Expanded guidance on recommended Kubernetes platforms.
**2021**:
- [2021-12-31](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77437): Fix typo for 25k Redis AWS machine size.
- [2021-12-28](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77243): Add Cloud Provider breakdowns to testing process & results section.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77039): Add more detail to testing process and results section.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77002): Add note on Database Load Balancing requirements when using a modified 3k architecture.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76236): Add diagram for 1k architecture (single node).
- [2021-12-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76748): Add sections on estimated costs (GCP), testing process and results and further Cloud Provider service details.
- [2021-12-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76226): Expanded external database service guidance for components and what cloud provider services are recommended.
- [2021-11-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/74612): Added recommendations for Database Load Balancing.
- [2021-11-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/73634): Added more details about testing targets used for the architectures.
- [2021-10-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/72052): Added guidance around optionally enabling Incremental Logging by using Redis.
- [2021-10-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71784): Updated Sidekiq configuration to include required `external_url` setting.
- [2021-10-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71576): Expanded guidance around Gitaly Cluster and Gitaly Sharded.
- [2021-09-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70625): Added a note on what Cloud Native Hybrid architecture to use with small user counts.
- [2021-09-27](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70602): Changed guidance to now co-locate Redis Sentinel beside Redis on the same node.
- [2021-08-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67778): Added 2k Cloud Native Hybrid architecture.
- [2021-08-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67463): Added links to performance test results for each architecture.
- [2021-07-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67231): Fixed the replication settings in PostgreSQL configuration examples to have correct values.
- [2021-07-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66185): Added 3k Cloud Native Hybrid architecture.
- [2021-07-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66278): Updated architecture diagrams to correctly reflect no direct connection between Rails and Sidekiq.
- [2021-07-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65373): Updated Patroni configuration to include Rest API authentication settings.
- [2021-07-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65992): Added 5k Cloud Native Hybrid architecture.
- [2021-07-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65154): Added 25k Cloud Native Hybrid architecture.
- [2021-06-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/64711): Added 50k Cloud Native Hybrid architecture.
- [2021-06-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/64612): Made additions to main page for Cloud Native Hybrid and reduce 3k architecture.
- [2021-06-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63580): Updated PostgreSQL steps and configuration to use the latest roles and prep for any Geo replication.
- [2021-06-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63857): Updated configuration examples for Monitoring node to follow latest.
- [2021-06-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/62316): Expanded notes on external services with more detail.
- [2021-06-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63504): Added additional guidance and expand on how to correctly manage GitLab secrets and database migrations.
- [2021-06-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63443): Updated Praefect configuration examples to follow the new storages format.
- [2021-06-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/61923): Removed references for the Unicorn webserver, which has been replaced by Puma.
- [2021-04-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59471): Updated Sidekiq configuration examples to show how to correctly configure multiple workers on each node.
- [2021-04-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59283): Added initial guidance on how to modify the 3k Reference Architecture for lower user counts.
- [2021-04-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59259): Added further clarification on using external services (PostgreSQL, Redis).
- [2021-04-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59139): Added additional guidance on using Load Balancers and their routing methods.
- [2021-04-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/58885): Added additional guidance on how to correctly configure only one node to do database migrations for Praefect.
- [2021-04-06](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/57476): Expanded 10k Cloud Native Hybrid documentation with more details and clear naming.
- [2021-03-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/54454): Expanded Gitaly Cluster documentation to all other applicable Reference Architecture sizes.
- [2021-02-19](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/54244): Added additional Object Storage guidance of using separated buckets for different data types as per recommendations.
- [2021-02-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/50852): Added documentation for setting up Object Storage with Rails and Sidekiq.
- [2021-02-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/51928): Added documentation for setting up Gitaly Cluster for the 10k Reference Architecture.
- [2021-02-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/52249): Added the first iteration of the 10k Cloud Native Hybrid reference architecture.
- [2021-01-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/50573): Added documentation for using Patroni as PostgreSQL replication manager.
<style>
table.ra-table td {
border-top: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
border-bottom: 1px solid #dbdbdb;
}
table.ra-table th {
border-top: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
border-bottom: 1px solid #dbdbdb;
}
</style>
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Recommended deployments at scale.
title: Reference architectures
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The GitLab reference architectures are validated, production-ready environment designs for deploying GitLab at scale. Each architecture provides detailed specifications that you can use or adapt based on your requirements.
## Available reference architectures
The following reference architectures are available as recommended starting points for your environment.
The architectures are named in terms of peak load, based on user count or requests per second (RPS). RPS is calculated based on average real data.
{{< alert type="note" >}}
Each architecture is designed to be [scalable and elastic](#scaling-an-environment). They can be adjusted accordingly based on your workload, upwards or downwards. For example, some known heavy scenarios such as using [large monorepos](#large-monorepos) or notable [additional workloads](#additional-workloads).
{{< /alert >}}
For details about what each reference architecture is tested against, see the **Testing Methodology** section of each page.
### GitLab package (Omnibus)
The following is the list of Linux package based reference architectures:
- [Up to 20 RPS or 1,000 users](1k_users.md) <span style="color: #74717A;">_API: 20 RPS, Web: 2 RPS, Git (Pull): 2 RPS, Git (Push): 1 RPS_</span>
- [Up to 40 RPS or 2,000 users](2k_users.md) <span style="color: #74717A;">_API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS_</span>
- [Up to 60 RPS or 3,000 users](3k_users.md) <span style="color: #74717A;">_API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS_</span>
- [Up to 100 RPS or 5,000 users](5k_users.md) <span style="color: #74717A;">_API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS_</span>
- [Up to 200 RPS or 10,000 users](10k_users.md) <span style="color: #74717A;">_API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS_</span>
- [Up to 500 RPS or 25,000 users](25k_users.md) <span style="color: #74717A;">_API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS_</span>
- [Up to 1000 RPS or 50,000 users](50k_users.md) <span style="color: #74717A;">_API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS_</span>
### Cloud native hybrid
The following is a list of Cloud Native Hybrid reference architectures, where select recommended components can be run in Kubernetes:
- [Up to 40 RPS or 2,000 users](2k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 40 RPS, Web: 4 RPS, Git (Pull): 4 RPS, Git (Push): 1 RPS_</span>
- [Up to 60 RPS or 3,000 users](3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 60 RPS, Web: 6 RPS, Git (Pull): 6 RPS, Git (Push): 1 RPS_</span>
- [Up to 100 RPS or 5,000 users](5k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS_</span>
- [Up to 200 RPS or 10,000 users](10k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS_</span>
- [Up to 500 RPS or 25,000 users](25k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 500 RPS, Web: 50 RPS, Git (Pull): 50 RPS, Git (Push): 10 RPS_</span>
- [Up to 1000 RPS or 50,000 users](50k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) <span style="color: #74717A;">_API: 1000 RPS, Web: 100 RPS, Git (Pull): 100 RPS, Git (Push): 20 RPS_</span>
## Before you start
First, consider whether a self-managed approach is the right choice for you and your requirements.
Running any application in production is complex, and the same applies for GitLab. While we aim to make this as smooth as possible, there are still the general complexities based on your design. Typically you have to manage all aspects such as hardware, operating systems, networking, storage, security, GitLab itself, and more. This includes both the initial setup of the environment and the longer term maintenance.
You must have a working knowledge of running and maintaining applications in production if you decide to go down this route. If you aren't in this position, our [Professional Services](https://about.gitlab.com/services/#implementation-services) team offers implementation services. Those who want a more managed solution long term, can explore our other offerings such as [GitLab SaaS](../../subscriptions/gitlab_com/_index.md) or [GitLab Dedicated](../../subscriptions/gitlab_dedicated/_index.md).
If you are considering using the GitLab Self-Managed approach, we encourage you to read through this page in full, specifically the following sections:
- [Deciding which architecture to use](#deciding-which-architecture-to-start-with)
- [Large monorepos](#large-monorepos)
- [Additional workloads](#additional-workloads)
## Deciding which architecture to start with
The reference architectures are designed to strike a balance between three important factors: performance, resilience, and cost. They are designed to make it easier to set up GitLab at scale. However, it can still be a challenge to know which one meets your requirements and where to start accordingly.
As a general guide, **the more performant and/or resilient you want your environment to be, the more complex it is**.
This section explains the things to consider when picking a reference architecture.
### Expected load (RPS or user count)
The right architecture size depends primarily on your environment's expected peak load. The most objective measure of this load is through peak Requests per Second (RPS) coming into the environment.
Each architecture is designed to handle specific RPS targets for different types of requests (API, Web, Git). These details are described in the **Testing Methodology** section on each page.
Finding out the RPS can depend notably on the specific environment setup and monitoring stack. Some potential options include:
- [GitLab Prometheus](../monitoring/prometheus/_index.md#sample-prometheus-queries) with queries like `sum(irate(gitlab_transaction_duration_seconds_count{controller!~'HealthController|MetricsController'}[1m])) by (controller, action)`.
- [`get-rps` script](https://gitlab.com/gitlab-com/support/toolbox/dotfiles/-/blob/main/scripts/get-rps.rb?ref_type=heads) from GitLab Support.
- Other monitoring solutions.
- Load Balancer statistics.
If you can't determine your RPS, we provide an alternative sizing method based on equivalent User Count by Load Category. This count is mapped to typical RPS values, considering both manual and automated usage.
#### Initial sizing guide
To determine which architecture to pick for the expected load, see the following initial sizing guide table:
<table class="ra-table">
<col>
<tr>
<th style="text-align: center" rowspan="2"><br/>Load Category</th>
<th style="text-align: center" colspan="4" scope="colgroup">Requests per Second (RPS)</th>
<th rowspan="2" style="text-align: center"><br/>Typical User Count</th>
<th rowspan="2" style="text-align: center"><br/>Reference Architecture</th>
</tr>
<tr>
<th scope="col" style="text-align: center">API</th>
<th scope="col" style="text-align: center">Web</th>
<th scope="col" style="text-align: center">Git Pull</th>
<th scope="col" style="text-align: center">Git Push</th>
</tr>
<tr>
<td>X Small</td>
<td>20</td>
<td>2</td>
<td>2</td>
<td>1</td>
<td>1,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/1k_users.html">Up to 20 RPS or 1,000 users</a></th>
</tr>
<tr>
<td>Small</td>
<td>40</td>
<td>4</td>
<td>4</td>
<td>1</td>
<td>2,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/2k_users.html">Up to 40 RPS or 2,000 users</a></th>
</tr>
<tr>
<td>Medium</td>
<td>60</td>
<td>6</td>
<td>6</td>
<td>1</td>
<td>3,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/3k_users.html">Up to 60 RPS or 3,000 users</a></th>
</tr>
<tr>
<td>Large</td>
<td>100</td>
<td>10</td>
<td>10</td>
<td>2</td>
<td>5,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/5k_users.html">Up to 100 RPS or 5,000 users</a></th>
</tr>
<tr>
<td>X Large</td>
<td>200</td>
<td>20</td>
<td>20</td>
<td>4</td>
<td>10,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/10k_users.html">Up to 200 RPS or 10,000 users</a></th>
</tr>
<tr>
<td>2X Large</td>
<td>500</td>
<td>50</td>
<td>50</td>
<td>10</td>
<td>25,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/25k_users.html">Up to 500 RPS or 25,000 users</a></th>
</tr>
<tr>
<td>3X Large</td>
<td>1000</td>
<td>100</td>
<td>100</td>
<td>20</td>
<td>50,000</td>
<th scope="row"><a href="https://docs.gitlab.com/ee/administration/reference_architectures/50k_users.html">Up to 1000 RPS or 50,000 users</a></th>
</tr>
</table>
{{< alert type="note" >}}
Before you select an initial architecture, review this section thoroughly. Consider other factors such as High Availability (HA) or use of large monorepos because they may impact the choice beyond just RPS or user count.
{{< /alert >}}
#### If in doubt, start large, monitor, and then scale down
If you're uncertain about the required environment size, consider starting with a larger size, [monitoring](#monitoring) it, and then [scaling down](#scaling-an-environment) accordingly if the metrics support your situation.
Starting large and then scaling down is a prudent approach when:
- You can't determine RPS
- The environment load could be atypically higher than expected
- You have [large monorepos](#large-monorepos) or notable [additional workloads](#additional-workloads)
For example, if you have 3,000 users but also know that there's automation at play that would significantly increase the concurrent load, then you could start with a 100 RPS / 5k User class environment, monitor it, and if the metrics support it, scale down all components at once, or one by one.
### Standalone (non-HA)
For environments serving 2,000 or fewer users, it's generally recommended to follow a standalone approach by deploying a non-HA, single, or multi-node environment. With this approach, you can employ strategies such as [automated backups](../backup_restore/backup_gitlab.md#configuring-cron-to-make-daily-backups) for recovery. These strategies provide a good level of recovery time objective (RTO) or recovery point objective (RPO) while avoiding the complexities that come with HA.
With standalone setups, especially single node environments, various options are available for [installation](../../install/_index.md) and management. The options include [the ability to deploy directly by using select cloud provider marketplaces](https://page.gitlab.com/cloud-partner-marketplaces.html) that reduce the complexity a little further.
### High Availability (HA)
High Availability ensures every component in the GitLab setup can handle failures through various mechanisms. However, to achieve this is complex, and the environments required can be sizable.
For environments serving 3,000 or more users, we generally recommend using an HA strategy. At this level, outages have a bigger impact against more users. All the architectures in this range have HA built in by design for this reason.
#### Do you need High Availability (HA)?
As mentioned previously, achieving HA comes at a cost. The environment requirements are sizable as each component needs to be multiplied, which comes with additional actual and maintenance costs.
For a lot of our customers with fewer than 3,000 users, we've found that a backup strategy is sufficient and even preferable. While this does have a slower recovery time, it also means you have a much smaller architecture and less maintenance costs as a result.
As a general guideline, employ HA only in the following scenarios:
- When you have 3,000 or more users.
- When GitLab being down would critically impact your workflow.
#### Scaled-down High Availability (HA) approach
If you still need HA for fewer users, you can achieve it with an adjusted [3K architecture](3k_users.md#supported-modifications-for-lower-user-counts-ha).
#### Zero-downtime upgrades
[Zero-downtime upgrades](../../update/zero_downtime.md) are available for standard environments with HA (Cloud Native Hybrid is [not supported](https://gitlab.com/groups/gitlab-org/cloud-native/-/epics/52)). This allows for an environment to stay up during an upgrade. However, this process is more complex as a result and has some limitations as detailed in the documentation.
When going through this process, it's worth noting that there may still be brief moments of downtime when the HA mechanisms take effect.
In most cases, the downtime required for doing an upgrade shouldn't be substantial. Use this approach only if it's a key requirement for you.
### Cloud Native Hybrid (Kubernetes HA)
As an additional layer of HA resilience, you can deploy select components in Kubernetes, known as a Cloud Native Hybrid reference architecture. For stability
reasons, stateful components such as Gitaly [cannot be deployed in Kubernetes](#stateful-components-in-kubernetes).
Cloud Native Hybrid is an alternative and more **advanced** setup compared to a standard reference architecture. Running services in Kubernetes is complex. **Use this setup** only if you have strong working knowledge and experience in Kubernetes.
### GitLab Geo (Cross Regional Distribution / Disaster Recovery)
With [GitLab Geo](../geo/_index.md), you can achieve distributed environments in
different regions with a full Disaster Recovery (DR) setup in place. GitLab Geo
requires at least two separate environments:
- One primary site.
- One or more secondary sites that serve as replicas.
If the primary site becomes unavailable, you can fail over to one of the secondary sites.
Use this **advanced and complex** setup only if DR is
a key requirement for your environment. You must also make additional decisions
on how each site is configured. For example, if each secondary site would be the
same architecture as the primary or if each site is configured for HA.
### Large monorepos / Additional workloads
[Large monorepos](#large-monorepos) or significant [additional workloads](#additional-workloads) can affect the performance of the environment notably. Some adjustments may be required depending on the context.
If this situation applies to you, reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/)
for further guidance.
### Cloud provider services
For all the previously described strategies, you can run select GitLab components on equivalent cloud provider services such as the PostgreSQL database or Redis.
For more information, see the [recommended cloud providers and services](#recommended-cloud-providers-and-services).
### Decision Tree
Read through the guidance documented previously in full first before you refer to the following decision tree.
```mermaid
%%{init: { 'theme': 'base' } }%%
graph TD
L0A(<b>What Reference Architecture should I use?</b>)
L1A(<b>What is your <a href=#expected-load-rps--user-count>expected load</a>?</b>)
L2A("60 RPS / 3,000 users or more?")
L2B("40 RPS / 2,000 users or less?")
L3A("<a href=#do-you-need-high-availability-ha>Do you need HA?</a><br>(or zero-downtime upgrades)")
L3B[Do you have experience with<br/>and want additional resilience<br/>with select components in Kubernetes?]
L4A><b>Recommendation</b><br><br>60 RPS / 3,000 user architecture with HA<br>and supported reductions]
L4B><b>Recommendation</b><br><br>Architecture closest to <a href=#expected-load-rps--user-count>expected load</a> with HA]
L4C><b>Recommendation</b><br><br>Cloud Native Hybrid architecture<br>closest to <a href=#expected-load-rps--user-count>expected load</a>]
L4D>"<b>Recommendation</b><br><br>Standalone 20 RPS / 1,000 user or 40 RPS / 2,000 user<br/>architecture with Backups"]
L0A --> L1A
L1A --> L2A
L1A --> L2B
L2A -->|Yes| L3B
L3B -->|Yes| L4C
L3B -->|No| L4B
L2B --> L3A
L3A -->|Yes| L4A
L3A -->|No| L4D
L5A("<a href=#gitlab-geo-cross-regional-distribution--disaster-recovery>Do you need cross regional distribution</br> or disaster recovery?"</a>) --> |Yes| L6A><b>Additional Recommendation</b><br><br> GitLab Geo]
L4A ~~~ L5A
L4B ~~~ L5A
L4C ~~~ L5A
L4D ~~~ L5A
L5B("Do you have <a href=#large-monorepos>Large Monorepos</a> or expect</br> to have substantial <a href=#additional-workloads>additional workloads</a>?") --> |Yes| L6B><b>Additional Recommendations</b><br><br><a href=#if-in-doubt---start-large-monitor-and-scale-down>Start large, monitor and scale down</a><br><br> Contact GitLab representative or Support]
L4A ~~~ L5B
L4B ~~~ L5B
L4C ~~~ L5B
L4D ~~~ L5B
classDef default fill:#FCA326
linkStyle default fill:none,stroke:#7759C2
```
## Requirements
Before implementing a reference architecture, see the following requirements and guidance.
### Supported machine types
The architectures are designed to be flexible in terms of machine type selection while ensuring consistent performance. While we provide specific machine type examples in each reference architecture, these are not intended to be prescriptive defaults.
You can use any machine types that meet or exceed the specified requirements for each component, such as:
- Newer generation machine types (like GCP `n2` series or AWS `m6` series)
- Different architectures like ARM-based instances (such as AWS Graviton)
- Alternative machine type families that better match your specific workload characteristics (such as higher network bandwidth)
This guidance is also applicable for any Cloud Provider services such as AWS RDS.
{{< alert type="note" >}}
Any "burstable" instance types are not recommended due to inconsistent performance.
{{< /alert >}}
{{< alert type="note" >}}
For details about what machine types we test against and how, refer to [validation and test results](#validation-and-test-results).
{{< /alert >}}
### Supported disk types
Most standard disk types are expected to work for GitLab. However, be aware of the following specific call-outs:
- Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
- We don't recommend the use of any disk types that are "burstable" due to inconsistent performance.
Other disk types are expected to work with GitLab. Choose based on your requirements such as durability or cost.
### Supported infrastructure
GitLab should run on most infrastructures such as reputable cloud providers (AWS, GCP, Azure) and
their services, or self-managed (ESXi) that meet both:
- The specifications detailed in each architecture.
- Any requirements in this section.
However, this does not guarantee compatibility with every potential permutation.
See [Recommended cloud providers and services](#recommended-cloud-providers-and-services) for more information.
### Networking (High Availability)
Below are the network requirements for running GitLab in a High Availability fashion.
#### Network latency
Network latency should be as low as possible to allow for synchronous replication across the GitLab application, such as database replication. Generally this should be lower than 5 ms.
#### Availability zones (Cloud Providers)
Deploying across availability zones is supported and generally recommended for additional resilience. You should use an odd number of zones to align with GitLab application requirements, as some components use an odd number of nodes for quorum voting.
#### Data centers (Self Hosted)
Deploying across multiple self-hosted data centers is possible but requires careful consideration. This requires synchronous capable latency between centers, robust redundant network links to prevent split-brain scenarios, all centers located in the same geographic region, and deployment across an odd number of centers for proper quorum voting (like [availability zones](#availability-zones-cloud-providers)).
{{< alert type="note" >}}
It may not be possible for GitLab Support to assist with infrastructure-related issues stemming from multi-data center deployments.
Choosing to deploy across centers is generally at your own risk.
{{< /alert >}}
{{< alert type="warning" >}}
It is not supported to deploy a single [GitLab environment across different regions](#deploying-one-environment-over-multiple-regions). Data centers should be in the same region.
{{< /alert >}}
### Large Monorepos
The architectures were tested with repositories of varying sizes that follow best practices.
**However, [large monorepos](../../user/project/repository/monorepos/_index.md) (several gigabytes or more) can significantly impact the performance of Git and in turn the environment itself**.
Their presence and how they are used can put a significant strain on the entire system from Gitaly to the underlying infrastructure.
The performance implications are largely software in nature. Additional hardware resources lead to diminishing returns.
{{< alert type="warning" >}}
If this applies to you, we strongly recommend you follow the linked documentation and reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/) for further guidance.
{{< /alert >}}
Large monorepos come with notable cost. If you have such a repository,
follow these guidance to ensure good performance and to keep costs in check:
- [Optimize the large monorepo](../../user/project/repository/monorepos/_index.md). Using features such as
[LFS](../../user/project/repository/monorepos/_index.md#use-git-lfs-for-large-binary-files) to not store binaries, and other approaches for reducing repository size, can
dramatically improve performance and reduce costs.
- Depending on the monorepo, increased environment specifications may be required to compensate. Gitaly might require additional resources along with Praefect, GitLab Rails, and Load Balancers. This depends on the monorepo itself and its usage.
- When the monorepo is significantly large (20 gigabytes or more), further additional strategies may be required such as even further increased specifications or in some cases, a separate Gitaly backend for the monorepo alone.
- Network and disk bandwidth is another potential consideration with large monorepos. In very heavy cases, bandwidth saturation is possible if there's a high amount of concurrent clones (such as with CI). [Reduce full clones wherever possible](../../user/project/repository/monorepos/_index.md#reduce-concurrent-clones-in-cicd) in this scenario. Otherwise, additional environment specifications may be required to increase bandwidth. This differs based on cloud providers.
### Additional workloads
These architectures have been [designed and tested](#validation-and-test-results) for standard GitLab
setups based on real data.
However, additional workloads can multiply the impact of operations by triggering follow-up actions.
You might have to adjust the suggested specifications to compensate if you use:
- Security software on the nodes.
- Hundreds of concurrent CI jobs for [large repositories](../../user/project/repository/monorepos/_index.md).
- Custom scripts that [run at high frequency](../logs/log_parsing.md#print-top-api-user-agents).
- [Integrations](../../integration/_index.md) in many large projects.
- [Server hooks](../server_hooks.md).
- [System hooks](../system_hooks.md).
Generally, you should have robust monitoring in place to measure the impact of any additional workloads to
inform any changes needed to be made. Reach out to your GitLab representative or our [Support team](https://about.gitlab.com/support/)
for further guidance.
### Load Balancers
The architectures make use of up to two load balancers depending on the class:
- External load balancer - Serves traffic to any external facing components, primarily Rails.
- Internal load balancer - Serves traffic to select internal components that are deployed in an HA fashion such as Praefect or PgBouncer.
The specifics on which load balancer to use, or its exact configuration is beyond the scope of GitLab documentation. The most common options
are to set up load balancers on machine nodes or to use a service such as one offered by cloud providers. If deploying a Cloud Native Hybrid environment, the charts can handle the external load balancer setup by using Kubernetes Ingress.
Each architecture class includes a recommended base machine size to deploy directly on machines. However, they may need adjustment based on factors such as the chosen load balancer and expected workload. Of note machines can have varying [network bandwidth](#network-bandwidth) that should also be taken into consideration.
The following sections provide additional guidance for load balancers.
#### Balancing algorithm
To ensure equal spread of calls to the nodes and good performance, use a least-connection-based load balancing algorithm or equivalent wherever possible.
We don't recommend the use of round-robin algorithms as they are known to not spread connections equally in practice.
#### Network Bandwidth
The total network bandwidth available to a load balancer when deployed on a machine can vary notably across cloud providers. Some cloud providers, like [AWS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html), may operate on a burst system with credits to determine the bandwidth at any time.
The required network bandwidth for your load balancers depends on factors such as data shape and workload. The recommended base sizes for each architecture class have been selected based on real data. However, in some scenarios such as consistent clones of [large monorepos](#large-monorepos), you might have to adjust the sizes accordingly.
### No swap
Swap is not recommended in the reference architectures. It's a failsafe that impacts performance greatly. The
architectures are designed to have enough memory in most cases to avoid the need for swap.
### Praefect PostgreSQL
[Praefect requires its own database server](../gitaly/praefect/configure.md#postgresql). To achieve full HA, a third-party PostgreSQL database solution is required.
We hope to offer a built-in solution for these restrictions in the future. In the meantime, a non-HA PostgreSQL server
can be set up using the Linux package as the specifications reflect. For more details, see the following issues:
- [`omnibus-gitlab#7292`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
- [`gitaly#3398`](https://gitlab.com/gitlab-org/gitaly/-/issues/3398).
## Recommended cloud providers and services
{{< alert type="note" >}}
The following lists are non-exhaustive. Other cloud providers not listed
here may work with the same specifications, but they have not been validated.
For the cloud provider services not listed here,
use caution because each implementation can be notably different.
Test thoroughly before using them in production.
{{< /alert >}}
The following architectures are recommended for the following cloud providers based on testing and real life usage:
<table>
<thead>
<tr>
<th>Reference Architecture</th>
<th>GCP</th>
<th>AWS</th>
<th>Azure</th>
<th>Bare Metal</th>
</tr>
</thead>
<tbody>
<tr>
<td>Linux package</td>
<td>🟢</td>
<td>🟢</td>
<td>🟢<sup>1</sup></td>
<td>🟢</td>
</tr>
<tr>
<td>Cloud Native Hybrid</td>
<td>🟢</td>
<td>🟢</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Additionally, the following cloud provider services are recommended for use as part of the architectures:
<table>
<thead>
<tr>
<th>Cloud Service</th>
<th>GCP</th>
<th>AWS</th>
<th>Azure</th>
<th>Bare Metal</th>
</tr>
</thead>
<tbody>
<tr>
<td>Object Storage</td>
<td>🟢 <a href="https://cloud.google.com/storage" target="_blank">Cloud Storage</a></td>
<td>🟢 <a href="https://aws.amazon.com/s3/" target="_blank">S3</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/storage/blobs" target="_blank">Azure Blob Storage</a></td>
<td>🟢 <a href="https://min.io/" target="_blank">MinIO</a></td>
</tr>
<tr>
<td>Database</td>
<td>🟢 <a href="https://cloud.google.com/sql" target="_blank" rel="noopener noreferrer">Cloud SQL<sup>1</sup></a></td>
<td>🟢 <a href="https://aws.amazon.com/rds/" target="_blank" rel="noopener noreferrer">RDS</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/postgresql/" target="_blank" rel="noopener noreferrer">Azure Database for PostgreSQL Flexible Server</a></td>
<td></td>
</tr>
<tr>
<td>Redis</td>
<td>🟢 <a href="https://cloud.google.com/memorystore" target="_blank" rel="noopener noreferrer">Memorystore</a></td>
<td>🟢 <a href="https://aws.amazon.com/elasticache/" target="_blank" rel="noopener noreferrer">ElastiCache</a></td>
<td>🟢 <a href="https://azure.microsoft.com/en-gb/products/cache" target="_blank" rel="noopener noreferrer">Azure Cache for Redis (Premium)</a></td>
<td></td>
</tr>
</tbody>
</table>
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. For optimal performance, especially in larger environments (500 RPS / 25k users or higher), use the [Enterprise Plus edition](https://cloud.google.com/sql/docs/editions-intro) for GCP Cloud SQL. You might have to adjust the maximum connections higher than the service's defaults, depending on your workload.
2. To ensure good performance, deploy the [Premium tier of Azure Cache for Redis](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-overview#service-tiers).
<!-- markdownlint-enable MD029 -->
### Best practices for the database services
If you choose to use a third-party external service, use an [external database service](../postgresql/external.md) that runs a standard, performant, and [supported PostgreSQL version](../../install/requirements.md#postgresql) and take note of the following considerations:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer, and Consul. All of these components are no longer required when using a third party external service.
1. For optimal performance, enable [Database Load Balancing](../postgresql/database_load_balancing.md) with Read Replicas. Match the node counts to those used in standard Linux package deployments. This approach is particularly important for larger environments (more than 200 requests per second or 10,000+ users).
1. Database Connection Poolers are not required for this setup as the options vary per service. As a result, you might have to adjust the connection count configuration, depending on the environment size. If Pooling is desired, a third party option must be explored as the GitLab Linux Package bundled PgBouncer is only compatible with the package bundled Postgres. [Database Load Balancing](../postgresql/database_load_balancing.md) can also be used to spread the load accordingly.
- Ensure that if a pooler is included in a Cloud Provider service, it can handle the total load without bottlenecks. For example, Azure Database for PostgreSQL flexible server can optionally deploy a PgBouncer pooler in front of the database. However, PgBouncer is single threaded, which may cause bottlenecks under heavy load. To mitigate this issue, you can use database load balancing to distribute the pooler across multiple nodes.
1. The number of nodes required for HA may vary depending on the service. The requirements for one deployment may vary from those for Linux package installations.
1. To use [GitLab Geo](../geo/_index.md), the service should support cross-region replication.
#### Unsupported database services
The following database cloud provider services are not recommended due to lack of support or known issues:
- [Amazon Aurora](https://aws.amazon.com/rds/aurora/) is incompatible and not supported. For more details, see [14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
- [Azure Database for PostgreSQL Single Server](https://azure.microsoft.com/en-gb/products/postgresql/#overview) is not supported as the service is now deprecated and runs on an unsupported version of PostgreSQL. It also has notable performance and stability issues.
- [Google AlloyDB](https://cloud.google.com/alloydb) and [Amazon RDS Multi-AZ DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/multi-az-db-clusters-concepts.html) are not tested and are not recommended. Both solutions are not expected to work with GitLab Geo.
- [Amazon RDS Multi-AZ DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZSingleStandby.html) is a separate product and is supported.
### Best practices for Redis services
Use an [external Redis service](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) that runs a standard, performant, and supported version. The service must support:
- Redis Standalone (Primary x Replica) mode - Redis Cluster mode is specifically not supported
- High availability through replication
- The ability to set the [Redis eviction policy](../redis/replication_and_failover_external.md#setting-the-eviction-policy)
Redis is primarily single threaded. For environments targeting the 200 RPS / 10,000 users class or larger, separate the instances into cache & persistent data to achieve optimum performance.
{{< alert type="note" >}}
Serverless variants of Redis services are not supported at this time.
{{< /alert >}}
### Best practices for object storage
GitLab has been tested against [various object storage providers](../object_storage.md#supported-object-storage-providers) that are expected to work.
Use a reputable solution that has full S3 compatibility.
## Deviating from the suggested reference architectures
The further away you move from the reference architectures,
the harder it is to get support. With each deviation, you introduce
a layer of complexity that complicates troubleshooting potential
issues.
These architectures use the official Linux packages or [Helm Charts](https://docs.gitlab.com/charts/) to
install and configure the various components. The components are
installed on separate machines (virtualized or Bare Metal). Machine hardware
requirements listed in the **Configuration** column. Equivalent VM standard sizes are listed
in the GCP/AWS/Azure columns of each [available architecture](#available-reference-architectures).
You can run GitLab components on Docker, including Docker Compose. Docker is well supported and provides consistent specifications across environments.
However, it is still an additional layer and might add some support complexities. For example, not being able to run `strace` in containers.
### Unsupported designs
While we try to have a good range of support for GitLab environment designs, certain approaches don't work effectively. The following sections detail these unsupported approaches.
#### Stateful components in Kubernetes
[Running stateful components in Kubernetes, such as Gitaly Cluster (Praefect), is not supported](https://docs.gitlab.com/charts/installation/#configure-the-helm-chart-to-use-external-stateful-data).
Gitaly Cluster (Praefect) is only supported on conventional virtual machines. Kubernetes strictly limits memory usage. However, the memory usage of Git is unpredictable, which
can cause sporadic out of memory (OOM) termination of Gitaly pods. The OOM termination leads to significant disruptions and potential data loss. Hence, Gitaly is not tested
or supported in Kubernetes. For more information, see [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127).
This applies to stateful components such as Postgres and Redis. You can use other supported cloud provider services, unless specifically called out as unsupported.
#### Autoscaling of stateful nodes
As a general guidance, only stateless components of GitLab can be run in autoscaling groups, namely GitLab Rails
and Sidekiq. Other components that have state, such as Gitaly, are not supported in this fashion. For more information, see [issue 2997](https://gitlab.com/gitlab-org/gitaly/-/issues/2997).
This applies to stateful components such as Postgres and Redis. You can use other supported cloud provider services, unless specifically called out as unsupported.
[Cloud Native Hybrid setups](#cloud-native-hybrid) are generally preferred over autoscaling groups. Kubernetes better handles components that can only run on one node,
such as database migrations and [Mailroom](../incoming_email.md).
#### Deploying one environment over multiple regions
GitLab does not support deploying a single environment across multiple regions. These setups can result in significant issues, such as excessive network latency or split-brain scenarios if connectivity between regions fails.
Several GitLab components perform synchronous replication or require an odd number of nodes to function correctly, such as Consul, Redis Sentinel, and Praefect. Distributing these components across multiple regions with high latency can severely impact their functionality and the overall system performance.
This limitation applies to all potential GitLab environment setups, including Cloud Native Hybrid alternatives.
For deploying GitLab over multiple data centers or regions, we offer [GitLab Geo](../geo/_index.md) as a comprehensive solution.
## Validation and test results
GitLab
does regular smoke and performance tests for these architectures to ensure they
remain compliant.
### How we perform the tests
Testing is conducted using specific coded workloads derived from sample customer data, utilizing both the [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) for environment deployment with Terraform and Ansible, and the [GitLab Performance Tool (GPT)](https://gitlab.com/gitlab-org/quality/performance) for performance testing with k6.
Testing is performed primarily on GCP and AWS using their standard compute offerings (n1 series for GCP, m5 series for AWS) as baseline configurations. These machine types were selected as a lowest common denominator target to ensure broad compatibility. Using different or newer machine types that meet the CPU and memory requirements is fully supported - see [Supported Machine Types](#supported-machine-types) for more information. The architectures are expected to perform similarly on any hardware meeting the specifications, whether on other cloud providers or on-premises.
### Performance targets
Each reference architecture is tested against specific throughput targets based on real customer data. For every 1,000 users, we test:
- API: 20 RPS
- Web: 2 RPS
- Git (Pull): 2 RPS
- Git (Push): 0.4 RPS (rounded to the nearest integer)
The listed RPS targets were selected based on real customer data of total environmental loads corresponding to the user count, including CI and other workloads.
{{< alert type="note" >}}
Network latency between components in test environments was observed at <5 ms but note this is not intended as a hard requirement.
{{< /alert >}}
### Test coverage and results
Testing is designed to be effective and provide good coverage for all reference architecture targets. Testing frequency varies by architecture type and size:
- Linux package environments: Daily or weekly of all sizes on GCP and AWS.
- Cloud Native environments: Weekly testing of select configurations on GCP and AWS.
Our testing also includes prototype variations of these architectures being explored for potential future inclusion. Test results are publicly available on the [Reference Architecture wiki](https://gitlab.com/gitlab-org/reference-architectures/-/wikis/Benchmarks/Latest).
## Maintaining a reference architecture environment
Maintaining a reference architecture environment is generally the same as any other GitLab environment.
In this section you can find links to documentation for relevant areas and specific architecture notes.
### Scaling an environment
The reference architectures are designed as a starting point, and are elastic and scalable throughout. You might want to adjust the environment for your specific needs after deployment for reasons such as additional performance capacity or reduced costs. This behavior is expected. Scaling can be done iteratively or wholesale to the next architecture size, if metrics suggest that a component is exhausted.
{{< alert type="note" >}}
If a component is continuously exhausting its given resources, reach out to our [Support team](https://about.gitlab.com/support/) before performing any significant scaling.
{{< /alert >}}
For most components, vertical and horizontal scaling can be applied as usual. However, before doing so, be aware of the following caveats:
- When scaling Puma or Sidekiq vertically, the amount of workers must be adjusted to use the additional specifications. Puma is scaled automatically on the next reconfigure. However, you might have to [change Sidekiq configuration beforehand](../sidekiq/extra_sidekiq_processes.md#start-multiple-processes).
- Redis and PgBouncer are primarily single threaded. If these components are seeing CPU exhaustion, they might have to be scaled out horizontally.
- The Consul, Redis Sentinel, and Praefect components require an odd number of nodes for a voting quorum when deployed in HA form.
- Scaling certain components significantly can result in notable knock on effects that affect the performance of the environment. For more guidance, see [Scaling knock on effects](#scaling-knock-on-effects).
Conversely, if you have robust metrics in place that show the environment is over-provisioned, you can scale downwards.
You should take an iterative approach when scaling downwards, to ensure there are no issues.
#### Scaling knock on effects
In some cases, scaling a component significantly may result in knock on effects for downstream components, impacting performance. The architectures are designed with balance in mind to ensure components that depend on each other are congruent in terms of specifications. Notably scaling a component may result in additional throughput being passed to the other components it depends on. As a result, you could have to scale these other dependent components as well.
{{< alert type="note" >}}
The architectures have been designed to have elasticity to accommodate an upstream component being scaled. However, reach out to our [Support team](https://about.gitlab.com/support/) before you make any significant changes to your environment to be safe.
{{< /alert >}}
The following components can impact others when they have been significantly scaled:
- Puma and Sidekiq - Notable scale ups of either Puma or Sidekiq workers will result in higher concurrent connections to the internal load balancer, PostgreSQL (via PgBouncer if present), Gitaly (via Praefect if present) and Redis.
- Redis is primarily single-threaded. In some cases, you might have to split Redis into separate instances (for example, cache and persistent) if the increased throughput causes CPU exhaustion in a combined cluster.
- PgBouncer is also single threaded but a scale out might result in a new pool being added that in turn might increase the total connections to Postgres. It's strongly recommended to only do this if you have experience in managing Postgres connections and to seek assistance if in doubt.
- Gitaly Cluster (Praefect)/PostgreSQL - A notable scale out of additional nodes can have a detrimental effect on the HA system and performance due to increased replication calls to the primary node.
#### Scaling from a non-HA to an HA architecture
In most cases, vertical scaling is only required to increase an environment's resources. However, if you are moving to an HA environment,
additional steps are required for the following components to switch over to their HA forms.
For more information, see the following documentation:
- [Redis to multi-node Redis w/ Redis Sentinel](../redis/replication_and_failover.md#switching-from-an-existing-single-machine-installation)
- [Postgres to multi-node Postgres w/ Consul + PgBouncer](../postgresql/moving.md)
- [Gitaly to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect)
### Upgrades
Upgrading a reference architecture environment is the same as any other GitLab environment. For more information, see
[upgrade GitLab](../../update/_index.md). [Zero-downtime upgrades](#zero-downtime-upgrades) are also available.
{{< alert type="note" >}}
You should upgrade a reference architecture in the same order as you created it.
{{< /alert >}}
### Monitoring
You can monitor your infrastructure and [GitLab](../monitoring/_index.md) using various options. See the selected monitoring solution's documentation for more information.
{{< alert type="note" >}}
GitLab application is bundled with [Prometheus and various Prometheus compatible exporters](../monitoring/prometheus/_index.md) that could be hooked into your solution.
{{< /alert >}}
## Update history
The following is a history of notable updates for reference architectures (2021-01-01 onward, ascending order). We aim to update it at least once per quarter.
You can find a full history of changes [on the GitLab project](https://gitlab.com/gitlab-org/gitlab/-/merge_requests?scope=all&state=merged&label_name%5B%5D=Reference%20Architecture&label_name%5B%5D=documentation).
**2025**:
- [2025-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/199549): Updated Gitaly configurations to use [Gitaly roles](https://docs.gitlab.com/omnibus/roles/#gitaly-roles).
- [2025-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181145): Added further clarity around supported machine types and that the listed examples are not intended as prescriptive defaults.
**2024**:
- [2024-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/175854): Added _Start Large_ section as further guidance for choosing initial sizing.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/164181): Updated Expected Load section with some more examples on how to calculate RPS.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/163478): Updated Redis configuration on 40 RPS or 2k User page to have correct Redis configuration.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/163506): Updated Sidekiq configuration for Prometheus in Monitoring node on 2k.
- [2024-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/162144): Added Next Steps breadcrumb section to the pages to help discoverability of additional features.
- [2024-05](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/153716): Updated the 60 RPS or 3k User and 100 RPS or 5k User pages to have latest Redis guidance on co-locating Redis Sentinel with Redis itself.
- [2024-05](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/153579): Renamed `Cost to run` section to `Cost calculator templates` to better reflect the calculators are only a starting point and need to be adjusted with specific usage to give more accurate cost estimates.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/149878): Updated recommended sizing for Webservice nodes for Cloud Native Hybrids on GCP. Also adjusted NGINX pod recommendation to be run on Webservice node pool as a DaemonSet.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/149528): Updated 20 RPS / 1,000 User architecture specs to follow recommended memory target of 16 GB.
- [2024-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148313): Updated Reference Architecture titles to include RPS for further clarity and to help right sizing.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145436): Updated recommended sizing for Load Balancer nodes if deployed on VMs. Also added notes on network bandwidth considerations.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/143539): Removed the Sidekiq Maximum Concurrency setting in examples as this is deprecated and no longer required to be set explicitly.
- [2024-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/143539): Adjusted the Sidekiq recommendations on 2k to disable Sidekiq on Rails nodes and updated architecture diagram.
- [2024-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/140465): Updated recommendations for Azure for all Reference Architecture sizes and latest cloud services.
**2023**:
- [2023-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/139557): Updated notes on Load Balancers to be more reflective that any reputable offering is expected to work.
- [2023-11-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133457): Expanded details on what each Reference Architecture is designed for, the testing methodology used and added details on how to scale environments.
- [2023-11-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/134632): Added expanded notes on disk types, object storage and monitoring.
- [2023-10-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/134518): Adjusted Sidekiq configuration example to use Linux Package role.
- [2023-10-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133835): Adjusted the Sidekiq recommendations to include a separate node for 2k and tweaks to instance type and counts for 3k and 5k.
- [2023-10-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132270): Added more expanded notes throughout to warn about the use of Large Monorepos and their impacts for increased awareness.
- [2023-10-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/133258): Updated name of Task Runner pod to its new name of Toolbox.
- [2023-10-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132961): Expanded guidance on using an external service for Redis further, in particular for separated Cache and Persistent services with 10k and up.
- [2023-09-21](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132289): Expanded details on the challenges of running Gitaly in Kubernetes.
- [2023-09-20](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132275): Removed references to Grafana after deprecation and removal.
- [2023-08-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130470): Expanded section on Geo under the Decision Tree.
- [2023-08-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128529): Switched configuration example to use the Sidekiq role for Linux package.
- [2023-08-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128374): Fixed an AWS Machine type typo for the 50k architecture.
- [2023-06-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125017): Update PostgreSQL configuration examples to remove a now unneeded setting to instead use the Linux package default.
- [2023-06-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125017): Added explicit example on main page that reflects Google Memorystore is recommended.
- [2023-06-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/122063): Fixed IP examples for the 3k and 5k architectures.
- [2023-05-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/121545): Expanded notes on usage of external Cloud Provider Services and the recommendation of separated Redis servers for 10k environments and up.
- [2023-05-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/119224): Updated documentation to reflect correct requirement of Redis 6 instead of 5.
- [2023-04-28](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114877): Added a note that Azure Active Directory authentication method is not supported for use with Azure PostgreSQL Flexible service.
- [2023-03-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114877): Added more details about known unsupported designs.
- [2023-03-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114872): Updated Redis configuration examples for multi-node to have correct configuration to ensure all components can connect.
- [2023-03-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110784): Updated Gitaly configuration examples to the new format.
- [2023-03-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114495): Updated cost estimates to no longer include NFS VMs.
- [2023-02-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110379): Updated Praefect configuration examples to the new format.
- [2023-02-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/109798): Added examples of what automation may be considered additional workloads.
- [2023-02-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/111018): Added a new before you start section that gives more context about what's involved with running production software self-managed. Also added more details for Standalone setups and cloud provider services in the decision tree section.
- [2023-02-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110641): Switched to use more common complex terminology instead of the less known **involved**.
- [2023-01-31](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110328): Expanded and centralized the requirements section on the main page.
- [2023-01-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110183): Added notes on migrating Git data from NFS, that object data is still supported on NFS and handling SSH keys correctly across multiple Rails nodes.
**2022**:
- [2022-12-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105451): Removed guidance for using NFS for Git data as support for this is now ended with `15.6` or later.
- [2022-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106826): Added a note to clarify the difference between Amazon RDS Multi-AZ DB cluster and instance, with the latter being supported. Also, increase PostgreSQL maximum connections setting to new default of `500`.
- [2022-12-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106695): Updated Sidekiq maximum concurrency configuration to match new default of `20`.
- [2022-11-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/104236): Corrected guidance for Praefect and Gitaly in reduced 3k architecture section that an odd number quorum is required.
- [2022-11-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103623): Added guidance on how to handle GitLab Secrets in Cloud Native Hybrids and further links to the GitLab Charts documentation.
- [2022-11-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/103767): Fixed a typo with Sidekiq configuration for the 10k architecture.
- [2022-11-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/102746): Added guidance on large monorepos and additional workloads impact on performance. Also, expanded Load Balancer guidance around SSL and a recommendation for least connection based routing methods.
- [2022-10-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100826): Adjusted Object Storage guidance to make it clearer that it's recommended over NFS.
- [2022-10-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100305): Updated guidance for Azure to recommend up to 2k only due to performance issues.
- [2022-09-27](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98204): Added the decision tree section to help users better decide what architecture to use.
- [2022-09-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98263): Added explicit step to enable Incremental Logging when only Object Storage is being used.
- [2022-09-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/98184): Expanded guidance on recommended cloud providers and services.
- [2022-09-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/97245): Expanded Object Storage guidance and updated that NFS support for Git data ends with `15.6`.
- [2022-08-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96150): Added a clearer note about Gitaly Cluster not being supported in Kubernetes.
- [2022-08-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96021): Added a section on supported CPUs and types.
- [2022-08-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/95713): Updated architecture tables to be clearer for Object Storage support.
- [2022-08-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/95185): Increased Cloud Native Hybrid pool specifications for 2k architecture to ensure enough resources present for pods. Also, increased Sidekiq worker count.
- [2022-08-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93493): Added note to use newer Gitaly check command from GitLab `15.0` and later.
- [2022-07-25](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/93141): Moved the troubleshooting section to a more general location.
- [2022-07-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/92144): Added guidance that Amazon Aurora is no longer compatible and not supported from GitLab `14.4.0` and later.
- [2022-07-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/91943): Added call out note to remove the `default` section from Gitaly storages configuration as it's required.
- [2022-06-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/86812): Moved Incremental Logging guidance to a separate section.
- [2022-04-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85856): Expanded testing results' section with new regular pipelines.
- [2022-04-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85833): Updated Praefect configuration to reflect setting name changes.
- [2022-04-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85231): Added missing setting to enable Object Storage correctly.
- [2022-04-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/85107): Expanded Cloud Native Hybrid guidance with AWS machine types.
- [2022-04-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/84389): Added cost estimates for AWS and Azure.
- [2022-04-06](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/84483): Updated configuration examples for most components to be correctly included for Prometheus monitoring auto discovery.
- [2022-03-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81538): Expanded validation and testing result's section with more clearly language and more detail.
- [2022-03-21](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/83019): Added a note saying additional specifications may be needed for Gitaly in some scenarios.
- [2022-03-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/82087): Added guidance for preventing the GitLab `kas` service running on nodes where not required.
- [2022-03-01](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81814): Fixed a typo for Praefect TLS port in configuration examples.
- [2022-02-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/81247): Added guidance to enable the Gitaly Pack-objects cache.
- [2022-02-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80892): Added a general section on recommended Cloud Providers and services.
- [2022-02-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80521): Added link to a blog post about GPT testing added.
- [2022-01-26](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/78705): Merged testing process and cost estimates into one section with expanded details.
- [2022-01-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77968): Expanded guidance on recommended Kubernetes platforms.
**2021**:
- [2021-12-31](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77437): Fix typo for 25k Redis AWS machine size.
- [2021-12-28](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77243): Add Cloud Provider breakdowns to testing process & results section.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77039): Add more detail to testing process and results section.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/77002): Add note on Database Load Balancing requirements when using a modified 3k architecture.
- [2021-12-17](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76236): Add diagram for 1k architecture (single node).
- [2021-12-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76748): Add sections on estimated costs (GCP), testing process and results and further Cloud Provider service details.
- [2021-12-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/76226): Expanded external database service guidance for components and what cloud provider services are recommended.
- [2021-11-24](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/74612): Added recommendations for Database Load Balancing.
- [2021-11-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/73634): Added more details about testing targets used for the architectures.
- [2021-10-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/72052): Added guidance around optionally enabling Incremental Logging by using Redis.
- [2021-10-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71784): Updated Sidekiq configuration to include required `external_url` setting.
- [2021-10-02](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/71576): Expanded guidance around Gitaly Cluster and Gitaly Sharded.
- [2021-09-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70625): Added a note on what Cloud Native Hybrid architecture to use with small user counts.
- [2021-09-27](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70602): Changed guidance to now co-locate Redis Sentinel beside Redis on the same node.
- [2021-08-18](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67778): Added 2k Cloud Native Hybrid architecture.
- [2021-08-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67463): Added links to performance test results for each architecture.
- [2021-07-30](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67231): Fixed the replication settings in PostgreSQL configuration examples to have correct values.
- [2021-07-22](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66185): Added 3k Cloud Native Hybrid architecture.
- [2021-07-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66278): Updated architecture diagrams to correctly reflect no direct connection between Rails and Sidekiq.
- [2021-07-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65373): Updated Patroni configuration to include Rest API authentication settings.
- [2021-07-15](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65992): Added 5k Cloud Native Hybrid architecture.
- [2021-07-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65154): Added 25k Cloud Native Hybrid architecture.
- [2021-06-29](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/64711): Added 50k Cloud Native Hybrid architecture.
- [2021-06-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/64612): Made additions to main page for Cloud Native Hybrid and reduce 3k architecture.
- [2021-06-16](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63580): Updated PostgreSQL steps and configuration to use the latest roles and prep for any Geo replication.
- [2021-06-14](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63857): Updated configuration examples for Monitoring node to follow latest.
- [2021-06-11](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/62316): Expanded notes on external services with more detail.
- [2021-06-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63504): Added additional guidance and expand on how to correctly manage GitLab secrets and database migrations.
- [2021-06-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63443): Updated Praefect configuration examples to follow the new storages format.
- [2021-06-03](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/61923): Removed references for the Unicorn webserver, which has been replaced by Puma.
- [2021-04-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59471): Updated Sidekiq configuration examples to show how to correctly configure multiple workers on each node.
- [2021-04-23](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59283): Added initial guidance on how to modify the 3k Reference Architecture for lower user counts.
- [2021-04-13](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59259): Added further clarification on using external services (PostgreSQL, Redis).
- [2021-04-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/59139): Added additional guidance on using Load Balancers and their routing methods.
- [2021-04-08](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/58885): Added additional guidance on how to correctly configure only one node to do database migrations for Praefect.
- [2021-04-06](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/57476): Expanded 10k Cloud Native Hybrid documentation with more details and clear naming.
- [2021-03-04](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/54454): Expanded Gitaly Cluster documentation to all other applicable Reference Architecture sizes.
- [2021-02-19](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/54244): Added additional Object Storage guidance of using separated buckets for different data types as per recommendations.
- [2021-02-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/50852): Added documentation for setting up Object Storage with Rails and Sidekiq.
- [2021-02-12](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/51928): Added documentation for setting up Gitaly Cluster for the 10k Reference Architecture.
- [2021-02-09](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/52249): Added the first iteration of the 10k Cloud Native Hybrid reference architecture.
- [2021-01-07](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/50573): Added documentation for using Patroni as PostgreSQL replication manager.
<style>
table.ra-table td {
border-top: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
border-bottom: 1px solid #dbdbdb;
}
table.ra-table th {
border-top: 1px solid #dbdbdb;
border-left: 1px solid #dbdbdb;
border-right: 1px solid #dbdbdb;
border-bottom: 1px solid #dbdbdb;
}
</style>
|
https://docs.gitlab.com/administration/10k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/10k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
10k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 200 RPS or 10,000 users
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 200 requests per second (RPS), the typical peak load of up to 10,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|----------------|-----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` | `D8s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` | `D16s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 3 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
The sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 10k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 200 RPS / 10k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 200 RPS |
| Web | 20 RPS |
| Git (Pull) | 20 RPS |
| Git (Push) | 4 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 200 RPS or 10,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. These components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs will be used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux GitLab package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add same contents as the primary node in the previous section replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Persistent instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store cluster status data.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup do not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system, but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS pass-through.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 80 vCPU<br/>100 GB memory (request)<br/>140 GB memory (limit) | 3 x `n1-standard-32` | 3 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|-----------------------|------------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 10k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 200 RPS or 10,000 users we recommend a total Puma worker count of around 80 so in turn it's recommended to run at
least 20 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve as well as take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 200 RPS or 10,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/10k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 200 RPS or 10,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 200 requests per second (RPS), the typical peak load of up to 10,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 200 RPS, Web: 20 RPS, Git (Pull): 20 RPS, Git (Push): 4 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|------------------------------------------|-------|-------------------------|------------------|----------------|-----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` | `D8s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` | `D16s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 4 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| GitLab Rails<sup>8</sup> | 3 | 32 vCPU, 28.8 GB memory | `n1-highcpu-32` | `c5.9xlarge` | `F32s v2` |
| Monitoring node | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5.xlarge` | `F4s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
The sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 10k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x4" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 200 RPS / 10k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 200 RPS |
| Web | 20 RPS |
| Git (Pull) | 20 RPS |
| Git (Push) | 4 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 200 RPS or 10,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.40`: Internal Load Balancer
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
- `10.6.0.151`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP will be used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you'll be guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. These components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs will be used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux GitLab package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you will use the default
username of `gitlab` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you will use the default
username of `pgbouncer` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you will use the default
username of `gitlab_replicator` (recommended). The command will request a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you will use the default
username of `gitlab-consul` (recommended). The command will request a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, will default to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
If an error `execute[generate databases.ini]` occurs, this is due to an existing
[known issue](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/4713).
It will be resolved when you run a second `reconfigure` after the next step.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) once again
to resolve any potential errors from the previous steps.
1. Ensure each node is talking to the current primary:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.51`: Redis - Cache Primary
- `10.6.0.52`: Redis - Cache Replica 1
- `10.6.0.53`: Redis - Cache Replica 2
- `10.6.0.61`: Redis - Persistent Primary
- `10.6.0.62`: Redis - Persistent Replica 1
- `10.6.0.63`: Redis - Persistent Replica 2
### Provide your own Redis instances
You can optionally use a [third party external service for the Redis Cache and Persistence instances](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis Cache cluster
This is the section where we install and set up the new Redis Cache instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Cache node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.51'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.51:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Cache nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add same contents as the primary node in the previous section replacing `redis_master_node` with `redis_replica_node`:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.52'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-cache'
## The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.51'
# Set the Redis Cache instance as an LRU
# 90% of available RAM in MB
redis['maxmemory'] = '13500mb'
redis['maxmemory_policy'] = "allkeys-lru"
redis['maxmemory_samples'] = 5
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
redis_exporter['flags'] = {
'redis.addr' => 'redis://10.6.0.52:6379',
'redis.password' => 'redis-password-goes-here',
}
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure the Redis Persistent cluster
This is the section where we install and set up the new Redis Persistent instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis Persistent node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis Persistent nodes
1. SSH in to the **replica** Redis Persistent server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis-persistent'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store cluster status data.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs will be used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you will use the default
username of `praefect` (recommended). The command will request the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup do not have to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage will be
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Gitaly Cluster (Praefect) documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs will be used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs will be used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system, but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS pass-through.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connection to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues
you can scale it accordingly. Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.101`: Sidekiq 1
- `10.6.0.102`: Sidekiq 2
- `10.6.0.103`: Sidekiq 3
- `10.6.0.104`: Sidekiq 4
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.111`: GitLab application 1
- `10.6.0.112`: GitLab application 2
- `10.6.0.113`: GitLab application 3
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users will use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which will route traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## First cluster that will host the cache data
gitlab_rails['redis_cache_instance'] = 'redis://:<REDIS_PRIMARY_PASSWORD_OF_FIRST_CLUSTER>@gitlab-redis-cache'
gitlab_rails['redis_cache_sentinels'] = [
{host: '10.6.0.51', port: 26379},
{host: '10.6.0.52', port: 26379},
{host: '10.6.0.53', port: 26379},
]
## Second cluster that hosts all other persistent data
redis['master_name'] = 'gitlab-redis-persistent'
redis['master_password'] = '<REDIS_PRIMARY_PASSWORD_OF_SECOND_CLUSTER>'
gitlab_rails['redis_sentinels'] = [
{host: '10.6.0.61', port: 26379},
{host: '10.6.0.62', port: 26379},
{host: '10.6.0.63', port: 26379},
]
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
puma['listen'] = '0.0.0.0'
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.151/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.151/32', '127.0.0.0/8']
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Confirm the node can connect to Gitaly:
```shell
sudo gitlab-rake gitlab:gitaly:check
```
Then, tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Optionally, from the Gitaly servers, confirm that Gitaly can perform callbacks to the internal API:
- For GitLab 15.3 and later, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly check /var/opt/gitlab/gitaly/config.toml`.
- For GitLab 15.2 and earlier, run `sudo -u git -- /opt/gitlab/embedded/bin/gitaly-hooks check /var/opt/gitlab/gitaly/config.toml`.
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX will fail to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Designate one application node for running database migrations during
installation and updates. Initialize the GitLab database and ensure all
migrations ran:
```shell
sudo gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md).
The following IP will be used as an example:
- `10.6.0.151`: Prometheus
To configure the Monitoring node:
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 80 vCPU<br/>100 GB memory (request)<br/>140 GB memory (limit) | 3 x `n1-standard-32` | 3 x `c5.9xlarge` |
| Sidekiq | 12.6 vCPU<br/>28 GB memory (request)<br/>56 GB memory (limit) | 4 x `n1-standard-4` | 4 x `m5.xlarge` |
| Supporting services | 8 vCPU<br/>30 GB memory | 2 x `n1-standard-4` | 2 x `m5.xlarge` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|------------------------------------------|-------|-----------------------|------------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel - Cache<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Redis/Sentinel - Persistent<sup>3</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 16 vCPU, 60 GB memory | `n1-standard-16` | `m5.4xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instances](#provide-your-own-redis-instances) and [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
- Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores. For this size of architecture it's strongly recommended having separate Cache and Persistent instances as specified to achieve optimum performance.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 10k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis Persistent** x3" as redis_persistent #FF6347
collections "**Redis Cache** x3" as redis_cache #FF6347
redis_cache -[hidden]-> redis_persistent
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 200 RPS or 10,000 users we recommend a total Puma worker count of around 80 so in turn it's recommended to run at
least 20 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. This is to allow the controllers to scale dynamically with the Webservice pods they serve as well as take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 14 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 200 RPS or 10,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/10k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/5k_users
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/5k_users.md
|
2025-08-13
|
doc/administration/reference_architectures
|
[
"doc",
"administration",
"reference_architectures"
] |
5k_users.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Reference architecture: Up to 100 RPS or 5,000 users
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 100 requests per second (RPS) - The typical peak load of up to 5,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|-------------------------------------------|-------|-------------------------|-----------------|--------------|----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` | `D8s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 2 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D2s v3` |
| GitLab Rails<sup>8</sup> | 3 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2`|
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 5k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x2" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "Redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 100 RPS / 5k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 100 RPS |
| Web | 10 RPS |
| Git (Pull) | 10 RPS |
| Git (Push) | 2 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 100 RPS or 5,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul/Sentinel 1
- `10.6.0.12`: Consul/Sentinel 2
- `10.6.0.13`: Consul/Sentinel 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.20`: Internal Load Balancer
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
- `10.6.0.51`: Gitaly 1
- `10.6.0.52`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
- `10.6.0.41`: GitLab application 1
- `10.6.0.42`: GitLab application 2
- `10.6.0.43`: GitLab application 3
- `10.6.0.81`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP is used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you are guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you use the default
username of `gitlab` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you use the default
username of `pgbouncer` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you use the default
username of `gitlab_replicator` (recommended). The command requests a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you use the default
username of `gitlab-consul` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, defaults to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs are used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
pgbouncer_exporter['listen_address'] = '0.0.0.0:9188'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. Ensure each node is talking to the current master:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
If there is an error `psql: ERROR: Auth failed` after typing in the
password, ensure you previously generated the MD5 password hashes with the correct
format. The correct format is to concatenate the password and the username:
`PASSWORDUSERNAME`. For example, `Sup3rS3cr3tpgbouncer` would be the text
needed to generate an MD5 password hash for the `pgbouncer` user.
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31530) 77150s; run: log: (pid 31106) 77182s
run: logrotate: (pid 32613) 3357s; run: log: (pid 30107) 77500s
run: node-exporter: (pid 31550) 77149s; run: log: (pid 30138) 77493s
run: pgbouncer: (pid 32033) 75593s; run: log: (pid 31117) 77175s
run: pgbouncer-exporter: (pid 31558) 77148s; run: log: (pid 31498) 77156s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis cluster
This is the section where we install and set up the new Redis instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store cluster status data.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs are used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you use the default
username of `praefect` (recommended). The command requests the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup aren't required to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or later. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage is
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Praefect documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs are used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs are used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues,
more nodes can be added as required. You can also tune your Sidekiq nodes to
run [multiple Sidekiq processes](../sidekiq/extra_sidekiq_processes.md).
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the master node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30114) 77353s; run: log: (pid 29756) 77367s
run: logrotate: (pid 9898) 3561s; run: log: (pid 29653) 77380s
run: node-exporter: (pid 30134) 77353s; run: log: (pid 29706) 77372s
run: sidekiq: (pid 30142) 77351s; run: log: (pid 29638) 77386s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which routes traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the Redis primary node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379}
]
## Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
sidekiq['listen_address'] = "0.0.0.0"
puma['listen'] = '0.0.0.0'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 4890) 8647s; run: log: (pid 29962) 79128s
run: gitlab-exporter: (pid 4902) 8647s; run: log: (pid 29913) 79134s
run: gitlab-workhorse: (pid 4904) 8646s; run: log: (pid 29713) 79155s
run: logrotate: (pid 12425) 1446s; run: log: (pid 29798) 79146s
run: nginx: (pid 4925) 8646s; run: log: (pid 29726) 79152s
run: node-exporter: (pid 4931) 8645s; run: log: (pid 29855) 79140s
run: puma: (pid 4936) 8645s; run: log: (pid 29656) 79161s
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX fails to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Ensure that all migrations ran:
```shell
gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31637) 17337s; run: log: (pid 29748) 78432s
run: logrotate: (pid 31809) 2936s; run: log: (pid 29581) 78462s
run: nginx: (pid 31665) 17335s; run: log: (pid 29556) 78468s
run: prometheus: (pid 31672) 17335s; run: log: (pid 29633) 78456s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 36 vCPU<br/>45 GB memory (request)<br/>63 GB memory (limit) | 3 x `n1-standard-16` | 3 x `c5.4xlarge` |
| Sidekiq | 7.2 vCPU<br/>16 GB memory (request)<br/>32 GB memory (limit) | 3 x `n1-standard-4` | 3 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| PgBouncer<sup>3</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS).
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 5k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 100 RPS or 5,000 users we recommend a total Puma worker count of around 36 so in turn it's recommended to run at
least 9 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. It allows the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 8 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 100 RPS or 5,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/5k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Reference architecture: Up to 100 RPS or 5,000 users'
breadcrumbs:
- doc
- administration
- reference_architectures
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page describes the GitLab reference architecture designed to target a peak load of 100 requests per second (RPS) - The typical peak load of up to 5,000 users, both manual and automated, based on real data.
For a full list of reference architectures, see
[Available reference architectures](_index.md#available-reference-architectures).
{{< alert type="note" >}}
Before deploying this architecture it's recommended to read through the [main documentation](_index.md) first,
specifically the [Before you start](_index.md#before-you-start) and [Deciding which architecture to use](_index.md#deciding-which-architecture-to-start-with) sections.
{{< /alert >}}
- **Target load**: API: 100 RPS, Web: 10 RPS, Git (Pull): 10 RPS, Git (Push): 2 RPS
- **High Availability**: Yes ([Praefect](#configure-praefect-postgresql) needs a third-party PostgreSQL solution for HA)
- **Cloud Native Hybrid Alternative**: [Yes](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative)
- **Unsure which Reference Architecture to use?** [Go to this guide for more info](_index.md#deciding-which-architecture-to-start-with)
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> | Azure example<sup>1</sup> |
|-------------------------------------------|-------|-------------------------|-----------------|--------------|----------|
| External load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| PostgreSQL<sup>2</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D4s v3` |
| PgBouncer<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` | `F4s v2` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` | `D2s v3` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` | `D8s v3` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Sidekiq<sup>8</sup> | 2 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` | `D2s v3` |
| GitLab Rails<sup>8</sup> | 3 | 16 vCPU, 14.4 GB memory | `n1-highcpu-16` | `c5.4xlarge` | `F16s v2`|
| Monitoring node | 1 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` | `F2s v2` |
| Object storage<sup>5</sup> | - | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported machine types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS) which can provide HA capabilities.
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
8. Can be placed in Auto Scaling Groups (ASGs) as the component doesn't store any [stateful data](_index.md#autoscaling-of-stateful-nodes).
However, [Cloud Native Hybrid setups](#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) are generally preferred as certain components
such as like [migrations](#gitlab-rails-post-configuration) and [Mailroom](../incoming_email.md) can only be run on one node, which is handled better in Kubernetes.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 5k
skinparam linetype ortho
card "**External Load Balancer**" as elb #6a9be7
card "**Internal Load Balancer**" as ilb #9370DB
together {
collections "**GitLab Rails** x3" as gitlab #32CD32
collections "**Sidekiq** x2" as sidekiq #ff8dd1
}
together {
card "**Prometheus**" as monitor #7FFFD4
collections "**Consul** x3" as consul #e76a9b
}
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** //Primary//" as postgres_primary #4EA7FF
collections "**PostgreSQL** //Secondary// x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "Redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[#6a9be7,norank]--> monitor
gitlab -[#32CD32,norank]--> ilb
gitlab -[#32CD32]r-> object_storage
gitlab -[#32CD32]----> redis
gitlab .[#32CD32]----> database
gitlab -[hidden]-> monitor
gitlab -[hidden]-> consul
sidekiq -[#ff8dd1,norank]--> ilb
sidekiq -[#ff8dd1]r-> object_storage
sidekiq -[#ff8dd1]----> redis
sidekiq .[#ff8dd1]----> database
sidekiq -[hidden]-> monitor
sidekiq -[hidden]-> consul
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden]--> redis
ilb -[hidden]u-> consul
ilb -[hidden]u-> monitor
consul .[#e76a9b]u-> gitlab
consul .[#e76a9b]u-> sidekiq
consul .[#e76a9b]r-> monitor
consul .[#e76a9b]-> database
consul .[#e76a9b]-> gitaly_cluster
consul .[#e76a9b,norank]--> redis
monitor .[#7FFFD4]u-> gitlab
monitor .[#7FFFD4]u-> sidekiq
monitor .[#7FFFD4]> consul
monitor .[#7FFFD4]-> database
monitor .[#7FFFD4]-> gitaly_cluster
monitor .[#7FFFD4,norank]--> redis
monitor .[#7FFFD4]> ilb
monitor .[#7FFFD4,norank]u--> elb
@enduml
```
## Requirements
Before proceeding, review the [requirements](_index.md#requirements) for the reference architectures.
## Testing methodology
The 100 RPS / 5k user reference architecture is designed to accommodate most common workflows. GitLab regularly conducts smoke and performance testing against the following endpoint throughput targets:
| Endpoint Type | Target Throughput |
| ------------- | ----------------- |
| API | 100 RPS |
| Web | 10 RPS |
| Git (Pull) | 10 RPS |
| Git (Push) | 2 RPS |
These targets are based on actual customer data reflecting total environmental loads for the specified user count, including CI pipelines and other workloads.
For more information about our testing methodology, see the [validation and test results](_index.md#validation-and-test-results) section.
### Performance considerations
You may need additional adjustments if your environment has:
- Consistently higher throughput than the listed targets
- [Large monorepos](_index.md#large-monorepos)
- Significant [additional workloads](_index.md#additional-workloads)
In these cases, refer to [scaling an environment](_index.md#scaling-an-environment) for more information. If you believe these considerations may apply to you, contact us for additional guidance as required.
### Load Balancer configuration
Our testing environment uses:
- HAProxy for Linux package environments
- Cloud Provider equivalents with NGINX Ingress for Cloud Native Hybrids
## Set up components
To set up GitLab and its components to accommodate up to 100 RPS or 5,000 users:
1. [Configure the external load balancer](#configure-the-external-load-balancer)
to handle the load balancing of the GitLab application services nodes.
1. [Configure the internal load balancer](#configure-the-internal-load-balancer)
to handle the load balancing of GitLab application internal connections.
1. [Configure Consul](#configure-consul) for service discovery and health checking.
1. [Configure PostgreSQL](#configure-postgresql), the database for GitLab.
1. [Configure PgBouncer](#configure-pgbouncer) for database connection pooling and management.
1. [Configure Redis](#configure-redis), which stores session data, temporary
cache information, and background job queues.
1. [Configure Gitaly Cluster (Praefect)](#configure-gitaly-cluster-praefect),
provides access to the Git repositories.
1. [Configure Sidekiq](#configure-sidekiq) for background job processing.
1. [Configure the main GitLab Rails application](#configure-gitlab-rails)
to run Puma, Workhorse, GitLab Shell, and to serve all frontend
requests (which include UI, API, and Git over HTTP/SSH).
1. [Configure Prometheus](#configure-prometheus) to monitor your GitLab
environment.
1. [Configure the object storage](#configure-the-object-storage)
used for shared data objects.
1. [Configure advanced search](#configure-advanced-search) (optional) for faster,
more advanced code search across your entire GitLab instance.
The servers start on the same 10.6.0.0/24 private network range, and can
connect to each other freely on these addresses.
The following list includes descriptions of each server and its assigned IP:
- `10.6.0.10`: External Load Balancer
- `10.6.0.11`: Consul/Sentinel 1
- `10.6.0.12`: Consul/Sentinel 2
- `10.6.0.13`: Consul/Sentinel 3
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
- `10.6.0.20`: Internal Load Balancer
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
- `10.6.0.51`: Gitaly 1
- `10.6.0.52`: Gitaly 2
- `10.6.0.93`: Gitaly 3
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
- `10.6.0.141`: Praefect PostgreSQL 1 (non HA)
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
- `10.6.0.41`: GitLab application 1
- `10.6.0.42`: GitLab application 2
- `10.6.0.43`: GitLab application 3
- `10.6.0.81`: Prometheus
## Configure the external load balancer
In a multi-node GitLab configuration, you'll need an external load balancer to route
traffic to the application servers.
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
### Readiness checks
Ensure the external load balancer only routes to working services with built
in monitoring endpoints. The [readiness checks](../monitoring/health_check.md)
all require [additional configuration](../monitoring/ip_allowlist.md)
on the nodes being checked, otherwise, the external load balancer will not be able to
connect.
### Ports
The basic ports to be used are shown in the table below.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | ------------------------ |
| 80 | 80 | HTTP (*1*) |
| 443 | 443 | TCP or HTTPS (*1*) (*2*) |
| 22 | 22 | TCP |
- (*1*): [Web terminal](../../ci/environments/_index.md#web-terminals-deprecated) support requires
your load balancer to correctly handle WebSocket connections. When using
HTTP or HTTPS proxying, this means your load balancer must be configured
to pass through the `Connection` and `Upgrade` hop-by-hop headers. See the
[web terminal](../integration/terminal.md) integration guide for
more details.
- (*2*): When using HTTPS protocol for port 443, you must add an SSL
certificate to the load balancers. If you wish to terminate SSL at the
GitLab application server instead, use TCP protocol.
If you're using GitLab Pages with custom domain support you will need some
additional port configurations.
GitLab Pages requires a separate virtual IP address. Configure DNS to point the
`pages_external_url` from `/etc/gitlab/gitlab.rb` at the new virtual IP address. See the
[GitLab Pages documentation](../pages/_index.md) for more information.
| LB Port | Backend Port | Protocol |
| ------- | ------------- | --------- |
| 80 | Varies (*1*) | HTTP |
| 443 | Varies (*1*) | TCP (*2*) |
- (*1*): The backend port for GitLab Pages depends on the
`gitlab_pages['external_http']` and `gitlab_pages['external_https']`
setting. See [GitLab Pages documentation](../pages/_index.md) for more details.
- (*2*): Port 443 for GitLab Pages should always use the TCP protocol. Users can
configure custom domains with custom SSL, which would not be possible
if SSL was terminated at the load balancer.
#### Alternate SSH Port
Some organizations have policies against opening SSH port 22. In this case,
it may be helpful to configure an alternate SSH hostname that allows users
to use SSH on port 443. An alternate SSH hostname will require a new virtual IP address
compared to the other GitLab HTTP configuration documented previously.
Configure DNS for an alternate SSH hostname such as `altssh.gitlab.example.com`.
| LB Port | Backend Port | Protocol |
| ------- | ------------ | -------- |
| 443 | 22 | TCP |
### SSL
The next question is how you will handle SSL in your environment.
There are several different options:
- [The application node terminates SSL](#application-node-terminates-ssl).
- [The load balancer terminates SSL without backend SSL](#load-balancer-terminates-ssl-without-backend-ssl)
and communication is not secure between the load balancer and the application node.
- [The load balancer terminates SSL with backend SSL](#load-balancer-terminates-ssl-with-backend-ssl)
and communication is secure between the load balancer and the application node.
#### Application node terminates SSL
Configure your load balancer to pass connections on port 443 as `TCP` rather
than `HTTP(S)` protocol. This will pass the connection to the application node's
NGINX service untouched. NGINX will have the SSL certificate and listen on port 443.
See the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
#### Load balancer terminates SSL without backend SSL
Configure your load balancer to use the `HTTP(S)` protocol rather than `TCP`.
The load balancer will then be responsible for managing SSL certificates and
terminating SSL.
Because communication between the load balancer and GitLab will not be secure,
there is some additional configuration needed. See the
[proxied SSL documentation](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination)
for details.
#### Load balancer terminates SSL with backend SSL
Configure your load balancers to use the 'HTTP(S)' protocol rather than 'TCP'.
The load balancers will be responsible for managing SSL certificates that
end users will see.
Traffic will also be secure between the load balancers and NGINX in this
scenario. There is no requirement to add configuration for proxied SSL because the
connection will be secure all the way. However, configuration must be
added to GitLab to configure SSL certificates. See
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/)
for details on managing SSL certificates and configuring NGINX.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the internal load balancer
In a multi-node GitLab configuration, you'll need an internal load balancer to route
traffic for select internal components if configured
such as connections to [PgBouncer](#configure-pgbouncer) and [Gitaly Cluster (Praefect)](#configure-praefect).
The specifics on which load balancer to use, or its exact configuration
is beyond the scope of GitLab documentation but refer to [Load Balancers](_index.md) for more information around
general requirements. This section will focus on the specifics of
what to configure for your load balancer of choice.
The following IP is used as an example:
- `10.6.0.40`: Internal Load Balancer
Here's how you could do it with [HAProxy](https://www.haproxy.org/):
```plaintext
global
log /dev/log local0
log localhost local1 notice
log stdout format raw local0
defaults
log global
default-server inter 10s fall 3 rise 2
balance leastconn
frontend internal-pgbouncer-tcp-in
bind *:6432
mode tcp
option tcplog
default_backend pgbouncer
frontend internal-praefect-tcp-in
bind *:2305
mode tcp
option tcplog
option clitcpka
default_backend praefect
backend pgbouncer
mode tcp
option tcp-check
server pgbouncer1 10.6.0.31:6432 check
server pgbouncer2 10.6.0.32:6432 check
server pgbouncer3 10.6.0.33:6432 check
backend praefect
mode tcp
option tcp-check
option srvtcpka
server praefect1 10.6.0.131:2305 check
server praefect2 10.6.0.132:2305 check
server praefect3 10.6.0.133:2305 check
```
Refer to your preferred Load Balancer's documentation for further guidance.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Consul
Next, we set up the Consul servers.
{{< alert type="note" >}}
Consul must be deployed in an odd number of 3 nodes or more. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
The following IPs will be used as an example:
- `10.6.0.11`: Consul 1
- `10.6.0.12`: Consul 2
- `10.6.0.13`: Consul 3
To configure Consul:
1. SSH in to the server that will host Consul.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['consul_role'])
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
server: true,
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Consul nodes, and
make sure you set up the correct IPs.
A Consul leader is elected when the provisioning of the third Consul server is
complete. Viewing the Consul logs `sudo gitlab-ctl tail consul` displays
`...[INFO] consul: New leader elected: ...`.
You can list the current Consul members (server, client):
```shell
sudo /opt/gitlab/embedded/bin/consul members
```
You can verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30074) 76834s; run: log: (pid 29740) 76844s
run: logrotate: (pid 30925) 3041s; run: log: (pid 29649) 76861s
run: node-exporter: (pid 30093) 76833s; run: log: (pid 29663) 76855s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure PostgreSQL
In this section, you are guided through configuring a highly available PostgreSQL
cluster to be used with GitLab.
### Provide your own PostgreSQL instance
You can optionally use a [third party external service for PostgreSQL](../postgresql/external.md).
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
If you use a third party external service:
1. The HA Linux package PostgreSQL setup encompasses PostgreSQL, PgBouncer and Consul. All of these components would no longer be required when using a third party external service.
1. Set up PostgreSQL according to the
[database requirements document](../../install/requirements.md#postgresql).
1. Set up a `gitlab` username with a password of your choice. The `gitlab` user
needs privileges to create the `gitlabhq_production` database.
1. Configure the GitLab application servers with the appropriate details.
This step is covered in [Configuring the GitLab Rails application](#configure-gitlab-rails).
1. The number of nodes required to achieve HA can differ, depending on the service, and can differ from the Linux package.
1. However, if [Database Load Balancing](../postgresql/database_load_balancing.md) via Read Replicas is desired for further improved performance it's recommended to follow the node count for the Reference Architecture.
### Standalone PostgreSQL using the Linux package
The recommended Linux package configuration for a PostgreSQL cluster with
replication and failover requires:
- A minimum of three PostgreSQL nodes.
- A minimum of three Consul server nodes.
- A minimum of three PgBouncer nodes that track and handle primary database reads and writes.
- An [internal load balancer](#configure-the-internal-load-balancer) (TCP) to balance requests between the PgBouncer nodes.
- [Database Load Balancing](../postgresql/database_load_balancing.md) enabled.
A local PgBouncer service to be configured on each PostgreSQL node. This is separate from the main PgBouncer cluster that tracks the primary.
The following IPs are used as an example:
- `10.6.0.21`: PostgreSQL primary
- `10.6.0.22`: PostgreSQL secondary 1
- `10.6.0.23`: PostgreSQL secondary 2
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package **on each node**. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
#### PostgreSQL nodes
1. SSH in to one of the PostgreSQL nodes.
1. Generate a password hash for the PostgreSQL username/password pair. This assumes you use the default
username of `gitlab` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab
```
1. Generate a password hash for the PgBouncer username/password pair. This assumes you use the default
username of `pgbouncer` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<pgbouncer_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 pgbouncer
```
1. Generate a password hash for the PostgreSQL replication username/password pair. This assumes you use the default
username of `gitlab_replicator` (recommended). The command requests a password
and a confirmation. Use the value that is output by this command in the next step
as the value of `<postgresql_replication_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab_replicator
```
1. Generate a password hash for the Consul database username/password pair. This assumes you use the default
username of `gitlab-consul` (recommended). The command requests a password
and confirmation. Use the value that is output by this command in the next
step as the value of `<consul_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 gitlab-consul
```
1. On every database node, edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except Patroni, PgBouncer and Consul
roles(['patroni_role', 'pgbouncer_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Sets `max_replication_slots` to double the number of database nodes.
# Patroni uses one extra slot per node when initiating the replication.
patroni['postgresql']['max_replication_slots'] = 6
# Set `max_wal_senders` to one more than the number of replication slots in the cluster.
# This is used to prevent replication from using up all of the
# available database connections.
patroni['postgresql']['max_wal_senders'] = 7
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['services'] = %w(postgresql)
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PGBOUNCER_PASSWORD_HASH with a generated md5 value
postgresql['pgbouncer_user_password'] = '<pgbouncer_password_hash>'
# Replace POSTGRESQL_REPLICATION_PASSWORD_HASH with a generated md5 value
postgresql['sql_replication_password'] = '<postgresql_replication_password_hash>'
# Replace POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = '<postgresql_password_hash>'
# Set up basic authentication for the Patroni API (use the same username/password in all nodes).
patroni['username'] = '<patroni_api_username>'
patroni['password'] = '<patroni_api_password>'
# Replace 10.6.0.0/24 with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Local PgBouncer service for Database Load Balancing
pgbouncer['databases'] = {
gitlabhq_production: {
host: "127.0.0.1",
user: "pgbouncer",
password: '<pgbouncer_password_hash>'
}
}
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
PostgreSQL, with Patroni managing its failover, defaults to use `pg_rewind` by default to handle conflicts.
Like most failover handling methods, this has a small chance of leading to data loss.
For more information, see the various [Patroni replication methods](../postgresql/replication_and_failover.md#selecting-the-appropriate-patroni-replication-method).
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/database.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### PostgreSQL post-configuration
SSH in to any of the Patroni nodes on the **primary site**:
1. Check the status of the leader and cluster:
```shell
gitlab-ctl patroni members
```
The output should be similar to the following:
```plaintext
| Cluster | Member | Host | Role | State | TL | Lag in MB | Pending restart |
|---------------|-----------------------------------|-----------|--------|---------|-----|-----------|-----------------|
| postgresql-ha | <PostgreSQL primary hostname> | 10.6.0.21 | Leader | running | 175 | | * |
| postgresql-ha | <PostgreSQL secondary 1 hostname> | 10.6.0.22 | | running | 175 | 0 | * |
| postgresql-ha | <PostgreSQL secondary 2 hostname> | 10.6.0.23 | | running | 175 | 0 | * |
```
If the 'State' column for any node doesn't say "running", check the
[PostgreSQL replication and failover troubleshooting section](../postgresql/replication_and_failover_troubleshooting.md#pgbouncer-error-error-pgbouncer-cannot-connect-to-server)
before proceeding.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure PgBouncer
Now that the PostgreSQL servers are all set up, let's configure PgBouncer
for tracking and handling reads/writes to the primary database.
{{< alert type="note" >}}
PgBouncer is single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
The following IPs are used as an example:
- `10.6.0.31`: PgBouncer 1
- `10.6.0.32`: PgBouncer 2
- `10.6.0.33`: PgBouncer 3
1. On each PgBouncer node, edit `/etc/gitlab/gitlab.rb`, and replace
`<consul_password_hash>` and `<pgbouncer_password_hash>` with the
password hashes you [set up previously](#postgresql-nodes):
```ruby
# Disable all components except Pgbouncer and Consul agent
roles(['pgbouncer_role'])
# Configure PgBouncer
pgbouncer['admin_users'] = %w(pgbouncer gitlab-consul)
pgbouncer['users'] = {
'gitlab-consul': {
password: '<consul_password_hash>'
},
'pgbouncer': {
password: '<pgbouncer_password_hash>'
}
}
# Configure Consul agent
consul['watchers'] = %w(postgresql)
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
pgbouncer_exporter['listen_address'] = '0.0.0.0:9188'
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Create a `.pgpass` file so Consul is able to
reload PgBouncer. Enter the PgBouncer password twice when asked:
```shell
gitlab-ctl write-pgpass --host 127.0.0.1 --database pgbouncer --user pgbouncer --hostuser gitlab-consul
```
1. Ensure each node is talking to the current master:
```shell
gitlab-ctl pgb-console # You will be prompted for PGBOUNCER_PASSWORD
```
If there is an error `psql: ERROR: Auth failed` after typing in the
password, ensure you previously generated the MD5 password hashes with the correct
format. The correct format is to concatenate the password and the username:
`PASSWORDUSERNAME`. For example, `Sup3rS3cr3tpgbouncer` would be the text
needed to generate an MD5 password hash for the `pgbouncer` user.
1. Once the console prompt is available, run the following queries:
```shell
show databases ; show clients ;
```
The output should be similar to the following:
```plaintext
name | host | port | database | force_user | pool_size | reserve_pool | pool_mode | max_connections | current_connections
---------------------+-------------+------+---------------------+------------+-----------+--------------+-----------+-----------------+---------------------
gitlabhq_production | MASTER_HOST | 5432 | gitlabhq_production | | 20 | 0 | | 0 | 0
pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 | statement | 0 | 0
(2 rows)
type | user | database | state | addr | port | local_addr | local_port | connect_time | request_time | ptr | link | remote_pid | tls
------+-----------+---------------------+---------+----------------+-------+------------+------------+---------------------+---------------------+-----------+------+------------+-----
C | pgbouncer | pgbouncer | active | 127.0.0.1 | 56846 | 127.0.0.1 | 6432 | 2017-08-21 18:09:59 | 2017-08-21 18:10:48 | 0x22b3880 | | 0 |
(2 rows)
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31530) 77150s; run: log: (pid 31106) 77182s
run: logrotate: (pid 32613) 3357s; run: log: (pid 30107) 77500s
run: node-exporter: (pid 31550) 77149s; run: log: (pid 30138) 77493s
run: pgbouncer: (pid 32033) 75593s; run: log: (pid 31117) 77175s
run: pgbouncer-exporter: (pid 31558) 77148s; run: log: (pid 31498) 77156s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Redis
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
{{< alert type="note" >}}
Redis clusters must each be deployed in an odd number of 3 nodes or more. This is to ensure Redis Sentinel can take votes as part of a quorum. This does not apply when configuring Redis externally, such as a cloud provider service.
{{< /alert >}}
{{< alert type="note" >}}
Redis is primarily single threaded and doesn't significantly benefit from an increase in CPU cores.
Refer to the [scaling documentation](_index.md#scaling-an-environment) for more information.
{{< /alert >}}
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
The requirements for a Redis setup are the following:
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks (Internet), using options such as a firewall.
In this section, you'll be guided through configuring two external Redis clusters
to be used with GitLab. The following IPs will be used as an example:
- `10.6.0.61`: Redis Primary
- `10.6.0.62`: Redis Replica 1
- `10.6.0.63`: Redis Replica 2
### Provide your own Redis instance
You can optionally use a [third party external service for the Redis instance](../redis/replication_and_failover_external.md#redis-as-a-managed-service-in-a-cloud-provider) with the following guidance:
- A reputable provider or solution should be used for this. [Google Memorystore](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) and [AWS ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/WhatIs.html) are known to work.
- Redis Cluster mode is specifically not supported, but Redis Standalone with HA is.
- You must set the [Redis eviction mode](../redis/replication_and_failover_external.md#setting-the-eviction-policy) according to your setup.
For more information, see [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services).
### Configure the Redis cluster
This is the section where we install and set up the new Redis instances.
Both the primary and replica Redis nodes need the same password defined in
`redis['password']`. At any time during a failover, the Sentinels can reconfigure
a node and change its status from primary to replica (and vice versa).
#### Configure the primary Redis node
1. SSH in to the **Primary** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_master_role' with Sentinel and the Consul agent
roles ['redis_sentinel_role', 'redis_master_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.61'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# Set up password authentication for Redis and replicas (use the same password in all nodes).
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
## The IP of this primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
#### Configure the replica Redis nodes
1. SSH in to the **replica** Redis server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system. Select the same version
and type (Community or Enterprise editions) as your current install.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server roles as 'redis_sentinel_role' and 'redis_replica_role'
roles ['redis_sentinel_role', 'redis_replica_role', 'consul_role']
# Set IP bind address and Quorum number for Redis Sentinel service
sentinel['bind'] = '0.0.0.0'
sentinel['quorum'] = 2
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you must bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.6.0.62'
# Define a port so Redis can listen for TCP requests which will allow other
# machines to connect to it.
redis['port'] = 6379
## Port of primary Redis server for Sentinel, uncomment to change to non default. Defaults
## to `6379`.
#redis['master_port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'REDIS_PRIMARY_PASSWORD'
redis['master_password'] = 'REDIS_PRIMARY_PASSWORD'
## Must be the same in every Redis node
redis['master_name'] = 'gitlab-redis'
# The IP of the primary Redis node.
redis['master_ip'] = '10.6.0.61'
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes, and
make sure to set up the IPs correctly.
Advanced [configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Gitaly Cluster (Praefect)
[Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md) is a GitLab-provided and recommended fault tolerant solution for storing Git
repositories. In this configuration, every Git repository is stored on every Gitaly node in the cluster, with one being
designated the primary, and failover occurs automatically if the primary node goes down.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect).
For guidance on:
- Implementing sharded Gitaly instead, follow the [separate Gitaly documentation](../gitaly/configure_gitaly.md)
instead of this section. Use the same Gitaly specs.
- Migrating existing repositories that aren't managed by Gitaly Cluster (Praefect), see
[migrate to Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#migrate-to-gitaly-cluster-praefect).
The recommended cluster setup includes the following components:
- 3 Gitaly nodes: Replicated storage of Git repositories.
- 3 Praefect nodes: Router and transaction manager for Gitaly Cluster (Praefect).
- 1 Praefect PostgreSQL node: Database server for Praefect. A third-party solution
is required for Praefect database connections to be made highly available.
- 1 load balancer: A load balancer is required for Praefect. The
[internal load balancer](#configure-the-internal-load-balancer) is used.
This section details how to configure the recommended standard setup in order.
For more advanced setups refer to the [standalone Gitaly Cluster (Praefect) documentation](../gitaly/praefect/_index.md).
### Configure Praefect PostgreSQL
Praefect, the routing and transaction manager for Gitaly Cluster (Praefect), requires its own database server to store cluster status data.
If you want to have a highly available setup, Praefect requires a third-party PostgreSQL database.
A built-in solution is being [worked on](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/7292).
#### Praefect non-HA PostgreSQL standalone using the Linux package
The following IPs are used as an example:
- `10.6.0.141`: Praefect PostgreSQL
First, make sure to [install](../../install/package/_index.md#supported-platforms)
the Linux package on the Praefect PostgreSQL node. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. SSH in to the Praefect PostgreSQL node.
1. Create a strong password to be used for the Praefect PostgreSQL user. Take note of this password as `<praefect_postgresql_password>`.
1. Generate the password hash for the Praefect PostgreSQL username/password pair. This assumes you use the default
username of `praefect` (recommended). The command requests the password `<praefect_postgresql_password>`
and confirmation. Use the value that is output by this command in the next
step as the value of `<praefect_postgresql_password_hash>`:
```shell
sudo gitlab-ctl pg-password-md5 praefect
```
1. Edit `/etc/gitlab/gitlab.rb` replacing values noted in the `# START user configuration` section:
```ruby
# Disable all components except PostgreSQL and Consul
roles(['postgres_role', 'consul_role'])
# PostgreSQL configuration
postgresql['listen_address'] = '0.0.0.0'
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
# Replace PRAEFECT_POSTGRESQL_PASSWORD_HASH with a generated md5 value
postgresql['sql_user_password'] = "<praefect_postgresql_password_hash>"
# Replace XXX.XXX.XXX.XXX/YY with Network Address
postgresql['trust_auth_cidr_addresses'] = %w(10.6.0.0/24 127.0.0.1/32)
# Set the network addresses that the exporters will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
postgres_exporter['listen_address'] = '0.0.0.0:9187'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Follow the [post configuration](#praefect-postgresql-post-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
#### Praefect HA PostgreSQL third-party solution
[As noted](#configure-praefect-postgresql), a third-party PostgreSQL solution for
Praefect's database is recommended if aiming for full High Availability.
There are many third-party solutions for PostgreSQL HA. The solution selected must have the following to work with Praefect:
- A static IP for all connections that doesn't change on failover.
- [`LISTEN`](https://www.postgresql.org/docs/16/sql-listen.html) SQL functionality must be supported.
{{< alert type="note" >}}
With a third-party setup, it's possible to colocate Praefect's database on the same server as
the main [GitLab](#provide-your-own-postgresql-instance) database as a convenience unless
you are using Geo, where separate database instances are required for handling replication correctly.
In this setup, the specs of the main database setup aren't required to be changed because the impact should be
minimal.
{{< /alert >}}
A reputable provider or solution should be used for this. [Google Cloud SQL](https://cloud.google.com/sql/docs/postgres/high-availability#normal)
and [Amazon RDS](https://aws.amazon.com/rds/) are known to work. However, Amazon Aurora is **incompatible** with load balancing enabled by default from
[14.4.0](https://archives.docs.gitlab.com/17.3/ee/update/versions/gitlab_14_changes/#1440).
See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
Once the database is set up, follow the [post configuration](#praefect-postgresql-post-configuration).
#### Praefect PostgreSQL post-configuration
After the Praefect PostgreSQL server has been set up, you must configure the user and database for Praefect to use.
We recommend the user be named `praefect` and the database `praefect_production`, and these can be configured as standard in PostgreSQL.
The password for the user is the same as the one you configured earlier as `<praefect_postgresql_password>`.
This is how this would work with a Linux package PostgreSQL setup:
1. SSH in to the Praefect PostgreSQL node.
1. Connect to the PostgreSQL server with administrative access.
The `gitlab-psql` user should be used here for this as it's added by default in the Linux package.
The database `template1` is used because it is created by default on all PostgreSQL servers.
```shell
/opt/gitlab/embedded/bin/psql -U gitlab-psql -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create the new user `praefect`, replacing `<praefect_postgresql_password>`:
```shell
CREATE ROLE praefect WITH LOGIN CREATEDB PASSWORD '<praefect_postgresql_password>';
```
1. Reconnect to the PostgreSQL server, this time as the `praefect` user:
```shell
/opt/gitlab/embedded/bin/psql -U praefect -d template1 -h POSTGRESQL_SERVER_ADDRESS
```
1. Create a new database `praefect_production`:
```shell
CREATE DATABASE praefect_production WITH ENCODING=UTF8;
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Configure Praefect
Praefect is the router and transaction manager for Gitaly Cluster (Praefect) and all connections to Gitaly go through
it. This section details how to configure it.
{{< alert type="note" >}}
Praefect must be deployed in an odd number of 3 nodes or later. This is to ensure the nodes can take votes as part of a quorum.
{{< /alert >}}
Praefect requires several secret tokens to secure communications across the cluster:
- `<praefect_external_token>`: Used for repositories hosted on Gitaly Cluster (Praefect) and can only be accessed by Gitaly clients that carry this token.
- `<praefect_internal_token>`: Used for replication traffic inside Gitaly Cluster (Praefect). This is distinct from `praefect_external_token`
because Gitaly clients must not be able to access internal nodes of Gitaly Cluster (Praefect) directly; that could lead to data loss.
- `<praefect_postgresql_password>`: The Praefect PostgreSQL password defined in the previous section is also required as part of this setup.
Gitaly Cluster (Praefect) nodes are configured in Praefect with a `virtual storage`. Each storage contains
the details of each Gitaly node that makes up the cluster. Each storage is also given a name
and this name is used in several areas of the configuration. In this guide, the name of the storage is
`default`. Also, this guide is geared towards new installs, if upgrading an existing environment
to use Gitaly Cluster (Praefect), you might have to use a different name.
Refer to the [Praefect documentation](../gitaly/praefect/configure.md#praefect) for more information.
The following IPs are used as an example:
- `10.6.0.131`: Praefect 1
- `10.6.0.132`: Praefect 2
- `10.6.0.133`: Praefect 3
To configure the Praefect nodes, on each one:
1. SSH in to the Praefect server.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit the `/etc/gitlab/gitlab.rb` file to configure Praefect:
{{< alert type="note" >}}
You can't remove the `default` entry from `virtual_storages` because [GitLab requires it](../gitaly/configure_gitaly.md#gitlab-requires-a-default-repository-storage).
{{< /alert >}}
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/gitaly/praefect/_index.md
- all reference architecture pages
-->
```ruby
# Avoid running unnecessary services on the Praefect server
gitaly['enable'] = false
postgresql['enable'] = false
redis['enable'] = false
nginx['enable'] = false
puma['enable'] = false
sidekiq['enable'] = false
gitlab_workhorse['enable'] = false
prometheus['enable'] = false
alertmanager['enable'] = false
gitlab_exporter['enable'] = false
gitlab_kas['enable'] = false
# Praefect Configuration
praefect['enable'] = true
# Prevent database migrations from running on upgrade automatically
praefect['auto_migrate'] = false
gitlab_rails['auto_migrate'] = false
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
praefect['configuration'] = {
# ...
listen_addr: '0.0.0.0:2305',
auth: {
# ...
#
# Praefect External Token
# This is needed by clients outside the cluster (like GitLab Shell) to communicate with the Praefect cluster
token: '<praefect_external_token>',
},
# Praefect Database Settings
database: {
# ...
host: '10.6.0.141',
port: 5432,
dbname: 'praefect_production',
user: 'praefect',
password: '<praefect_postgresql_password>',
},
# Praefect Virtual Storage config
# Name of storage hash must match storage name in gitlab_rails['repositories_storages'] on GitLab
# server ('praefect') and in gitaly['configuration'][:storage] on Gitaly nodes ('gitaly-1')
virtual_storage: [
{
# ...
name: 'default',
node: [
{
storage: 'gitaly-1',
address: 'tcp://10.6.0.91:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-2',
address: 'tcp://10.6.0.92:8075',
token: '<praefect_internal_token>'
},
{
storage: 'gitaly-3',
address: 'tcp://10.6.0.93:8075',
token: '<praefect_internal_token>'
},
],
},
],
# Set the network address Praefect will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9652',
}
# Set the network address the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
#
# END user configuration
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Praefect requires to run some database migrations, much like the main GitLab application. For this
you should select **one Praefect node only to run the migrations**, AKA the _Deploy Node_. This node
must be configured first before the others as follows:
1. In the `/etc/gitlab/gitlab.rb` file, change the `praefect['auto_migrate']` setting value from `false` to `true`
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect and
to run the Praefect database migrations.
1. On all other Praefect nodes, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Configure Gitaly
The [Gitaly](../gitaly/_index.md) server nodes that make up the cluster have
requirements that are dependent on data and load.
{{< alert type="warning" >}}
**Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health**.
**However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact the performance of the environment and further adjustments may be required**.
If you believe this applies to you, contact us for additional guidance as required.
{{< /alert >}}
Gitaly has certain [disk requirements](../gitaly/_index.md#disk-requirements) for Gitaly storages.
Gitaly servers must not be exposed to the public internet because network traffic
on Gitaly is unencrypted by default. The use of a firewall is highly recommended
to restrict access to the Gitaly server. Another option is to
[use TLS](#gitaly-cluster-praefect-tls-support).
For configuring Gitaly you should note the following:
- `gitaly['configuration'][:storage]` should be configured to reflect the storage path for the specific Gitaly node
- `auth_token` should be the same as `praefect_internal_token`
The following IPs are used as an example:
- `10.6.0.91`: Gitaly 1
- `10.6.0.92`: Gitaly 2
- `10.6.0.93`: Gitaly 3
On each node:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab
package repository and install GitLab for your chosen operating system,
but do **not** provide the `EXTERNAL_URL` value.
1. Edit the Gitaly server node's `/etc/gitlab/gitlab.rb` file to configure
storage paths, enable the network listener, and to configure the token:
<!--
Updates to example must be made at:
- https://gitlab.com/gitlab-org/charts/gitlab/blob/master/doc/advanced/external-gitaly/external-omnibus-gitaly.md#configure-omnibus-gitlab
- https://gitlab.com/gitlab-org/gitlab/blob/master/doc/administration/gitaly/index.md#gitaly-server-configuration
- all reference architecture pages
-->
```ruby
# https://docs.gitlab.com/omnibus/roles/#gitaly-roles
roles(["gitaly_role"])
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Configure the gitlab-shell API callback URL. Without this, `git push` will
# fail. This can be your 'front door' GitLab URL or an internal load
# balancer.
gitlab_rails['internal_api_url'] = 'https://gitlab.example.com'
# Configure the Consul agent
consul['enable'] = true
## Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
# START user configuration
# Please set the real values as explained in Required Information section
#
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Set the network address that the node exporter will listen on for monitoring
node_exporter['listen_address'] = '0.0.0.0:9100'
gitaly['configuration'] = {
# Make Gitaly accept connections on all network interfaces. You must use
# firewalls to restrict access to this address/port.
# Comment out following line if you only want to support TLS connections
listen_addr: '0.0.0.0:8075',
# Set the network address that Gitaly will listen on for monitoring
prometheus_listen_addr: '0.0.0.0:9236',
auth: {
# Gitaly Auth Token
# Should be the same as praefect_internal_token
token: '<praefect_internal_token>',
},
pack_objects_cache: {
# Gitaly Pack-objects cache
# Recommended to be enabled for improved performance but can notably increase disk I/O
# Refer to https://docs.gitlab.com/ee/administration/gitaly/configure_gitaly.html#pack-objects-cache for more info
enabled: true,
},
}
#
# END user configuration
```
1. Append the following to `/etc/gitlab/gitlab.rb` for each respective server:
- On Gitaly node 1:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-1',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 2:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-2',
path: '/var/opt/gitlab/git-data',
},
],
}
```
- On Gitaly node 3:
```ruby
gitaly['configuration'] = {
# ...
storage: [
{
name: 'gitaly-3',
path: '/var/opt/gitlab/git-data',
},
],
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Save the file, and then [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
### Gitaly Cluster (Praefect) TLS support
Praefect supports TLS encryption. To communicate with a Praefect instance that listens
for secure connections, you must:
- Use a `tls://` URL scheme in the `gitaly_address` of the corresponding storage entry
in the GitLab configuration.
- Bring your own certificates because this isn't provided automatically. The certificate
corresponding to each Praefect server must be installed on that Praefect server.
Additionally the certificate, or its certificate authority, must be installed on all Gitaly servers
and on all Praefect clients that communicate with it following the procedure described in
[GitLab custom certificate configuration](https://docs.gitlab.com/omnibus/settings/ssl/#install-custom-public-certificates) (and repeated below).
Note the following:
- The certificate must specify the address you use to access the Praefect server. You must add the hostname or IP
address as a Subject Alternative Name to the certificate.
- You can configure Praefect servers with both an unencrypted listening address
`listen_addr` and an encrypted listening address `tls_listen_addr` at the same time.
This allows you to do a gradual transition from unencrypted to encrypted traffic, if
necessary. To disable the unencrypted listener, set `praefect['configuration'][:listen_addr] = nil`.
- The Internal Load Balancer will also access to the certificates and must be configured
to allow for TLS passthrough.
Refer to the load balancers documentation on how to configure this.
To configure Praefect with TLS:
1. Create certificates for Praefect servers.
1. On the Praefect servers, create the `/etc/gitlab/ssl` directory and copy your key
and certificate there:
```shell
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
sudo cp key.pem cert.pem /etc/gitlab/ssl/
sudo chmod 644 key.pem cert.pem
```
1. Edit `/etc/gitlab/gitlab.rb` and add:
```ruby
praefect['configuration'] = {
# ...
tls_listen_addr: '0.0.0.0:3305',
tls: {
# ...
certificate_path: '/etc/gitlab/ssl/cert.pem',
key_path: '/etc/gitlab/ssl/key.pem',
},
}
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. On the Praefect clients (including each Gitaly server), copy the certificates,
or their certificate authority, into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. On the Praefect clients (except Gitaly servers), edit `gitlab_rails['repositories_storages']` in
`/etc/gitlab/gitlab.rb` as follows:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => 'tls://LOAD_BALANCER_SERVER_ADDRESS:3305',
"gitaly_token" => 'PRAEFECT_EXTERNAL_TOKEN'
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Sidekiq
Sidekiq requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
{{< alert type="note" >}}
If you find that the environment's Sidekiq job processing is slow with long queues,
more nodes can be added as required. You can also tune your Sidekiq nodes to
run [multiple Sidekiq processes](../sidekiq/extra_sidekiq_processes.md).
{{< /alert >}}
{{< alert type="note" >}}
When configuring additional GitLab functionality such as Container Registry, SAML, or LDAP,
update the Sidekiq configuration in addition to the Rails configuration.
Refer to the [external Sidekiq documentation](../sidekiq/_index.md) for more information.
{{< /alert >}}
- `10.6.0.71`: Sidekiq 1
- `10.6.0.72`: Sidekiq 2
To configure the Sidekiq nodes, on each one:
1. SSH in to the Sidekiq server.
1. Confirm that you can access the PostgreSQL, Gitaly, and Redis ports:
```shell
telnet <GitLab host> 5432 # PostgreSQL
telnet <GitLab host> 8075 # Gitaly
telnet <GitLab host> 6379 # Redis
```
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux package
of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration:
```ruby
# https://docs.gitlab.com/omnibus/roles/#sidekiq-roles
roles(["sidekiq_role"])
# External URL
## This should match the URL of the external load balancer
external_url 'https://gitlab.example.com'
# Redis
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the master node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379},
]
# Gitaly Cluster
## gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
## Address is the Internal Load Balancer for Praefect
## Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
# PostgreSQL
gitlab_rails['db_host'] = '10.6.0.40' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
## Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
# Sidekiq
sidekiq['listen_address'] = "0.0.0.0"
## Set number of Sidekiq queue processes to the same number as available CPUs
sidekiq['queue_groups'] = ['*'] * 4
# Monitoring
consul['enable'] = true
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
## Set the network addresses that the exporters will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
## Add the monitoring node's IP address to the monitoring whitelist
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
# Object Storage
## This is an example for configuring Object Storage on GCP
## Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 30114) 77353s; run: log: (pid 29756) 77367s
run: logrotate: (pid 9898) 3561s; run: log: (pid 29653) 77380s
run: node-exporter: (pid 30134) 77353s; run: log: (pid 29706) 77372s
run: sidekiq: (pid 30142) 77351s; run: log: (pid 29638) 77386s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure GitLab Rails
This section describes how to configure the GitLab application (Rails) component.
Rails requires connections to the [Redis](#configure-redis),
[PostgreSQL](#configure-postgresql) and [Gitaly](#configure-gitaly) instances.
It also requires a connection to [Object Storage](#configure-the-object-storage) as recommended.
{{< alert type="note" >}}
[Because it's recommended to use Object storage](../object_storage.md) instead of NFS for data objects, the following
examples include the Object storage configuration.
{{< /alert >}}
On each node perform the following:
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Create or edit `/etc/gitlab/gitlab.rb` and use the following configuration.
To maintain uniformity of links across nodes, the `external_url`
on the application server should point to the external URL that users use
to access GitLab. This would be the URL of the [external load balancer](#configure-the-external-load-balancer)
which routes traffic to the GitLab application server:
```ruby
external_url 'https://gitlab.example.com'
# gitlab_rails['repositories_storages'] gets configured for the Praefect virtual storage
# Address is the Internal Load Balancer for Praefect
# Token is the praefect_external_token
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tcp://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
## Disable components that will not be on the GitLab application server
roles(['application_role'])
gitaly['enable'] = false
sidekiq['enable'] = false
## PostgreSQL connection details
# Disable PostgreSQL on the application node
postgresql['enable'] = false
gitlab_rails['db_host'] = '10.6.0.20' # internal load balancer IP
gitlab_rails['db_port'] = 6432
gitlab_rails['db_password'] = '<postgresql_user_password>'
gitlab_rails['db_load_balancing'] = { 'hosts' => ['10.6.0.21', '10.6.0.22', '10.6.0.23'] } # PostgreSQL IPs
# Prevent database migrations from running on upgrade automatically
gitlab_rails['auto_migrate'] = false
## Redis connection details
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the Redis primary node.
redis['master_password'] = '<redis_primary_password>'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.6.0.11', 'port' => 26379},
{'host' => '10.6.0.12', 'port' => 26379},
{'host' => '10.6.0.13', 'port' => 26379}
]
## Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Set the network addresses that the exporters used for monitoring will listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_workhorse['prometheus_listen_addr'] = '0.0.0.0:9229'
sidekiq['listen_address'] = "0.0.0.0"
puma['listen'] = '0.0.0.0'
## The IPs of the Consul server nodes
## You can also use FQDNs and intermix them with IPs
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13),
}
# Add the monitoring node's IP address to the monitoring whitelist and allow it to
# scrape the NGINX metrics
gitlab_rails['monitoring_whitelist'] = ['10.6.0.81/32', '127.0.0.0/8']
nginx['status']['options']['allow'] = ['10.6.0.81/32', '127.0.0.0/8']
gitlab_rails['prometheus_address'] = '10.6.0.81:9090'
#############################
### Object storage ###
#############################
# This is an example for configuring Object Storage on GCP
# Replace this config with your chosen Object Storage provider as desired
gitlab_rails['object_store']['enabled'] = true
gitlab_rails['object_store']['connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['object_store']['objects']['artifacts']['bucket'] = "<gcp-artifacts-bucket-name>"
gitlab_rails['object_store']['objects']['external_diffs']['bucket'] = "<gcp-external-diffs-bucket-name>"
gitlab_rails['object_store']['objects']['lfs']['bucket'] = "<gcp-lfs-bucket-name>"
gitlab_rails['object_store']['objects']['uploads']['bucket'] = "<gcp-uploads-bucket-name>"
gitlab_rails['object_store']['objects']['packages']['bucket'] = "<gcp-packages-bucket-name>"
gitlab_rails['object_store']['objects']['dependency_proxy']['bucket'] = "<gcp-dependency-proxy-bucket-name>"
gitlab_rails['object_store']['objects']['terraform_state']['bucket'] = "<gcp-terraform-state-bucket-name>"
gitlab_rails['backup_upload_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
gitlab_rails['backup_upload_remote_directory'] = "<gcp-backups-state-bucket-name>"
gitlab_rails['ci_secure_files_object_store_enabled'] = true
gitlab_rails['ci_secure_files_object_store_remote_directory'] = "gcp-ci_secure_files-bucket-name"
gitlab_rails['ci_secure_files_object_store_connection'] = {
'provider' => 'Google',
'google_project' => '<gcp-project-name>',
'google_json_key_location' => '<path-to-gcp-service-account-key>'
}
## Uncomment and edit the following options if you have set up NFS
##
## Prevent GitLab from starting if NFS data mounts are not available
##
#high_availability['mountpoint'] = '/var/opt/gitlab/git-data'
##
## Ensure UIDs and GIDs match between servers for permissions via NFS
##
#user['uid'] = 9000
#user['gid'] = 9000
#web_server['uid'] = 9001
#web_server['gid'] = 9001
#registry['uid'] = 9002
#registry['gid'] = 9002
```
1. If you're using [Gitaly with TLS support](#gitaly-cluster-praefect-tls-support), make sure the
`gitlab_rails['repositories_storages']` entry is configured with `tls` instead of `tcp`:
```ruby
gitlab_rails['repositories_storages'] = {
"default" => {
"gitaly_address" => "tls://10.6.0.40:2305", # internal load balancer IP
"gitaly_token" => '<praefect_external_token>'
}
}
```
1. Copy the cert into `/etc/gitlab/trusted-certs`:
```shell
sudo cp cert.pem /etc/gitlab/trusted-certs/
```
1. Copy the `/etc/gitlab/gitlab-secrets.json` file from the first Linux package node you configured and add or replace
the file of the same name on this server. If this is the first Linux package node you are configuring then you can skip this step.
1. Copy the SSH host keys (all in the name format `/etc/ssh/ssh_host_*_key*`) from the first Rails node you configured and
add or replace the files of the same name on this server. This ensures host mismatch errors aren't thrown
for your users as they hit the load balanced Rails nodes. If this is the first Linux package node you are configuring,
then you can skip this step.
1. To ensure database migrations are only run during reconfigure and not automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only a single designated node should handle migrations as detailed in the
[GitLab Rails post-configuration](#gitlab-rails-post-configuration) section.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. [Enable incremental logging](#enable-incremental-logging).
1. Run `sudo gitlab-rake gitlab:gitaly:check` to confirm the node can connect to Gitaly.
1. Tail the logs to see the requests:
```shell
sudo gitlab-ctl tail gitaly
```
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 4890) 8647s; run: log: (pid 29962) 79128s
run: gitlab-exporter: (pid 4902) 8647s; run: log: (pid 29913) 79134s
run: gitlab-workhorse: (pid 4904) 8646s; run: log: (pid 29713) 79155s
run: logrotate: (pid 12425) 1446s; run: log: (pid 29798) 79146s
run: nginx: (pid 4925) 8646s; run: log: (pid 29726) 79152s
run: node-exporter: (pid 4931) 8645s; run: log: (pid 29855) 79140s
run: puma: (pid 4936) 8645s; run: log: (pid 29656) 79161s
```
When you specify `https` in the `external_url`, as in the previous example,
GitLab expects that the SSL certificates are in `/etc/gitlab/ssl/`. If the
certificates aren't present, NGINX fails to start. For more information, see
the [HTTPS documentation](https://docs.gitlab.com/omnibus/settings/ssl/).
### GitLab Rails post-configuration
1. Ensure that all migrations ran:
```shell
gitlab-rake gitlab:db:configure
```
This operation requires configuring the Rails node to connect to the primary database
directly, [bypassing PgBouncer](../postgresql/pgbouncer.md#procedure-for-bypassing-pgbouncer).
After migrations have completed, you must configure the node to pass through PgBouncer again.
1. [Configure fast lookup of authorized SSH keys in the database](../operations/fast_ssh_key_lookup.md).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure Prometheus
The Linux package can be used to configure a standalone Monitoring node
running [Prometheus](../monitoring/prometheus/_index.md):
1. SSH in to the Monitoring node.
1. [Download and install](../../install/package/_index.md#supported-platforms) the Linux
package of your choice. Be sure to only add the GitLab package repository and install GitLab
for your chosen operating system.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
roles(['monitoring_role', 'consul_role'])
external_url 'http://gitlab.example.com'
# Prometheus
prometheus['listen_address'] = '0.0.0.0:9090'
prometheus['monitor_kubernetes'] = false
# Enable service discovery for Prometheus
consul['monitoring_service_discovery'] = true
consul['configuration'] = {
retry_join: %w(10.6.0.11 10.6.0.12 10.6.0.13)
}
# Configure Prometheus to scrape services not covered by discovery
prometheus['scrape_configs'] = [
{
'job_name': 'pgbouncer',
'static_configs' => [
'targets' => [
"10.6.0.31:9188",
"10.6.0.32:9188",
"10.6.0.33:9188",
],
],
},
{
'job_name': 'praefect',
'static_configs' => [
'targets' => [
"10.6.0.131:9652",
"10.6.0.132:9652",
"10.6.0.133:9652",
],
],
},
]
nginx['enable'] = false
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Verify the GitLab services are running:
```shell
sudo gitlab-ctl status
```
The output should be similar to the following:
```plaintext
run: consul: (pid 31637) 17337s; run: log: (pid 29748) 78432s
run: logrotate: (pid 31809) 2936s; run: log: (pid 29581) 78462s
run: nginx: (pid 31665) 17335s; run: log: (pid 29556) 78468s
run: prometheus: (pid 31672) 17335s; run: log: (pid 29633) 78456s
```
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Configure the object storage
GitLab supports using an [object storage](../object_storage.md) service for holding numerous types of data.
It's recommended over [NFS](../nfs.md) for data objects and in general it's better
in larger setups as object storage is typically much more performant, reliable,
and scalable. See [Recommended cloud providers and services](_index.md#recommended-cloud-providers-and-services) for more information.
There are two ways of specifying object storage configuration in GitLab:
- [Consolidated form](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form): A single credential is
shared by all supported object types.
- [Storage-specific form](../object_storage.md#configure-each-object-type-to-define-its-own-storage-connection-storage-specific-form): Every object defines its
own object storage [connection and configuration](../object_storage.md#configure-the-connection-settings).
The consolidated form is used in the following examples when available.
Using separate buckets for each data type is the recommended approach for GitLab.
This ensures there are no collisions across the various types of data GitLab stores.
There are plans to [enable the use of a single bucket](https://gitlab.com/gitlab-org/gitlab/-/issues/292958)
in the future.
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
### Enable incremental logging
GitLab Runner returns job logs in chunks which the Linux package caches temporarily on disk in `/var/opt/gitlab/gitlab-ci/builds` by default, even when using consolidated object storage. With default configuration, this directory needs to be shared through NFS on any GitLab Rails and Sidekiq nodes.
While sharing the job logs through NFS is supported, avoid the requirement to use NFS by enabling [incremental logging](../cicd/job_logs.md#incremental-logging) (required when no NFS node has been deployed). Incremental logging uses Redis instead of disk space for temporary caching of job logs.
## Configure advanced search
You can leverage Elasticsearch and [enable advanced search](../../integration/advanced_search/elasticsearch.md)
for faster, more advanced code search across your entire GitLab instance.
Elasticsearch cluster design and requirements are dependent on your specific
data. For recommended best practices about how to set up your Elasticsearch
cluster alongside your instance, read how to
[choose the optimal cluster configuration](../../integration/advanced_search/elasticsearch.md#guidance-on-choosing-optimal-cluster-configuration).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Cloud Native Hybrid reference architecture with Helm Charts (alternative)
An alternative approach is to run specific GitLab components in Kubernetes.
The following services are supported:
- GitLab Rails
- Sidekiq
- NGINX
- Toolbox
- Migrations
- Prometheus
Hybrid installations leverage the benefits of both cloud native and traditional
compute deployments. With this, stateless components can benefit from cloud native
workload management benefits while stateful components are deployed in compute VMs
with Linux package installations to benefit from increased permanence.
Refer to the Helm charts [Advanced configuration](https://docs.gitlab.com/charts/advanced/)
documentation for setup instructions including guidance on what GitLab secrets to sync
between Kubernetes and the backend components.
{{< alert type="note" >}}
This is an **advanced** setup. Running services in Kubernetes is well known
to be complex. **This setup is only recommended** if you have strong working
knowledge and experience in Kubernetes. The rest of this
section assumes this.
{{< /alert >}}
{{< alert type="warning" >}}
**Gitaly Cluster (Praefect) is not supported to be run in Kubernetes**.
Refer to [epic 6127](https://gitlab.com/groups/gitlab-org/-/epics/6127) for more details.
{{< /alert >}}
### Cluster topology
The following tables and diagram detail the hybrid environment using the same formats
as the typical environment documented previously.
First are the components that run in Kubernetes. These run across several node groups, although you can change
the overall makeup as desired as long as the minimum CPU and Memory requirements are observed.
| Component Node Group | Target Node Pool Totals | GCP Example | AWS Example |
|----------------------|-------------------------|-----------------|--------------|
| Webservice | 36 vCPU<br/>45 GB memory (request)<br/>63 GB memory (limit) | 3 x `n1-standard-16` | 3 x `c5.4xlarge` |
| Sidekiq | 7.2 vCPU<br/>16 GB memory (request)<br/>32 GB memory (limit) | 3 x `n1-standard-4` | 3 x `m5.xlarge` |
| Supporting services | 4 vCPU<br/>15 GB memory | 2 x `n1-standard-2` | 2 x `m5.large` |
- For this setup, we regularly [test](_index.md#validation-and-test-results) and recommended [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) and [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/). Other Kubernetes services may also work, but your mileage may vary.
- Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
- The [Webservice](#webservice) and [Sidekiq](#sidekiq) target node pool totals are given for GitLab components only. Additional resources are required for the chosen Kubernetes provider's system processes. The given examples take this into account.
- The [Supporting](#supporting) target node pool total is given generally to accommodate several resources for supporting the GitLab deployment as well as any additional deployments you may wish to make depending on your requirements. Similar to the other node pools, the chosen Kubernetes provider's system processes also require resources. The given examples take this into account.
- In production deployments, it's not required to assign pods to specific nodes. However, it is recommended to have several nodes in each pool spread across different availability zones to align with resilient cloud architecture practices.
- Enabling autoscaling, such as Cluster Autoscaler, for efficiency reasons is encouraged, but it's generally recommended targeting a floor of 75% for Webservice and Sidekiq pods to ensure ongoing performance.
Next are the backend components that run on static compute VMs using the Linux package (or External PaaS
services where applicable):
| Service | Nodes | Configuration | GCP example<sup>1</sup> | AWS example<sup>1</sup> |
|-------------------------------------------|-------|-----------------------|-----------------|--------------|
| Consul<sup>2</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| PostgreSQL<sup>2</sup> | 3 | 4 vCPU, 15 GB memory | `n1-standard-4` | `m5.xlarge` |
| PgBouncer<sup>3</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Internal load balancer<sup>4</sup> | 1 | 4 vCPU, 3.6 GB memory | `n1-highcpu-4` | `c5n.xlarge` |
| Redis/Sentinel<sup>3</sup> | 3 | 2 vCPU, 7.5 GB memory | `n1-standard-2` | `m5.large` |
| Gitaly<sup>6</sup><sup>7</sup> | 3 | 8 vCPU, 30 GB memory | `n1-standard-8` | `m5.2xlarge` |
| Praefect<sup>6</sup> | 3 | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Praefect PostgreSQL<sup>2</sup> | 1+ | 2 vCPU, 1.8 GB memory | `n1-highcpu-2` | `c5.large` |
| Object storage<sup>5</sup> | - | - | - | - |
**Footnotes**:
<!-- Disable ordered list rule https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md#md029---ordered-list-item-prefix -->
<!-- markdownlint-disable MD029 -->
1. Machine type examples are given for illustration purposes. These types are used in [validation and testing](_index.md#validation-and-test-results) but are not intended as prescriptive defaults. Switching to other machine types that meet the requirements as listed is supported, including ARM variants if available. See [Supported Machine Types](_index.md#supported-machine-types) for more information.
2. Can be optionally run on reputable third-party external PaaS PostgreSQL solutions. See [Provide your own PostgreSQL instance](#provide-your-own-postgresql-instance) for more information.
3. Can be optionally run on reputable third-party external PaaS Redis solutions. See [Provide your own Redis instance](#provide-your-own-redis-instance) for more information.
4. Recommended to be run with a reputable third-party load balancer or service (LB PaaS).
Also, the sizing depends on selected Load Balancer and additional factors such as Network Bandwidth. Refer to [Load Balancers](_index.md#load-balancers) for more information.
5. Should be run on reputable Cloud Provider or Self Managed solutions. See [Configure the object storage](#configure-the-object-storage) for more information.
6. Gitaly Cluster (Praefect) provides the benefits of fault tolerance, but comes with additional complexity of setup and management.
Review the existing [technical limitations and considerations before deploying Gitaly Cluster (Praefect)](../gitaly/praefect/_index.md#before-deploying-gitaly-cluster-praefect). If you want sharded Gitaly, use the same specs listed in the previous table for `Gitaly`.
7. Gitaly specifications are based on high percentiles of both usage patterns and repository sizes in good health.
However, if you have [large monorepos](_index.md#large-monorepos) (larger than several gigabytes) or [additional workloads](_index.md#additional-workloads) these can significantly impact Git and Gitaly performance and further adjustments will likely be required.
<!-- markdownlint-enable MD029 -->
{{< alert type="note" >}}
For all PaaS solutions that involve configuring instances, it's recommended to implement a minimum of three nodes in three different availability zones to align with resilient cloud architecture practices.
{{< /alert >}}
```plantuml
@startuml 5k
skinparam linetype ortho
card "Kubernetes via Helm Charts" as kubernetes {
card "**External Load Balancer**" as elb #6a9be7
together {
collections "**Webservice**" as gitlab #32CD32
collections "**Sidekiq**" as sidekiq #ff8dd1
}
card "**Supporting Services**" as support
}
card "**Internal Load Balancer**" as ilb #9370DB
collections "**Consul** x3" as consul #e76a9b
card "Gitaly Cluster" as gitaly_cluster {
collections "**Praefect** x3" as praefect #FF8C00
collections "**Gitaly** x3" as gitaly #FF8C00
card "**Praefect PostgreSQL***\n//Non fault-tolerant//" as praefect_postgres #FF8C00
praefect -[#FF8C00]-> gitaly
praefect -[#FF8C00]> praefect_postgres
}
card "Database" as database {
collections "**PGBouncer** x3" as pgbouncer #4EA7FF
card "**PostgreSQL** (Primary)" as postgres_primary #4EA7FF
collections "**PostgreSQL** (Secondary) x2" as postgres_secondary #4EA7FF
pgbouncer -[#4EA7FF]-> postgres_primary
postgres_primary .[#4EA7FF]> postgres_secondary
}
card "redis" as redis {
collections "**Redis** x3" as redis_nodes #FF6347
}
cloud "**Object Storage**" as object_storage #white
elb -[#6a9be7]-> gitlab
elb -[hidden]-> sidekiq
elb -[hidden]-> support
gitlab -[#32CD32]--> ilb
gitlab -[#32CD32]r--> object_storage
gitlab -[#32CD32,norank]----> redis
gitlab -[#32CD32]----> database
sidekiq -[#ff8dd1]--> ilb
sidekiq -[#ff8dd1]r--> object_storage
sidekiq -[#ff8dd1,norank]----> redis
sidekiq .[#ff8dd1]----> database
ilb -[#9370DB]--> gitaly_cluster
ilb -[#9370DB]--> database
ilb -[hidden,norank]--> redis
consul .[#e76a9b]--> database
consul .[#e76a9b,norank]--> gitaly_cluster
consul .[#e76a9b]--> redis
@enduml
```
### Kubernetes component targets
The following section details the targets used for the GitLab components deployed in Kubernetes.
#### Webservice
Each Webservice pod (Puma and Workhorse) is recommended to be run with the following configuration:
- 4 Puma Workers
- 4 vCPU
- 5 GB memory (request)
- 7 GB memory (limit)
For 100 RPS or 5,000 users we recommend a total Puma worker count of around 36 so in turn it's recommended to run at
least 9 Webservice pods.
For further information on Webservice resource usage, see the Charts documentation on [Webservice resources](https://docs.gitlab.com/charts/charts/gitlab/webservice/#resources).
##### NGINX
It's also recommended deploying the NGINX controller pods across the Webservice nodes as a DaemonSet. It allows the controllers to scale dynamically with the Webservice pods they serve and take advantage of the higher network bandwidth larger machine types typically have.
This isn't a strict requirement. The NGINX controller pods can be deployed as desired as long as they have enough resources to handle the web traffic.
#### Sidekiq
Each Sidekiq pod is recommended to be run with the following configuration:
- 1 Sidekiq worker
- 900m vCPU
- 2 GB memory (request)
- 4 GB memory (limit)
Similar to the standard deployment documented previously, an initial target of 8 Sidekiq workers has been used here.
Additional workers may be required depending on your specific workflow.
For further information on Sidekiq resource usage, see the Charts documentation on [Sidekiq resources](https://docs.gitlab.com/charts/charts/gitlab/sidekiq/#resources).
### Supporting
The Supporting Node Pool is designed to house all supporting deployments that are not required on the Webservice and Sidekiq pools.
This includes various deployments related to the Cloud Provider's implementation and supporting
GitLab deployments such as [GitLab Shell](https://docs.gitlab.com/charts/charts/gitlab/gitlab-shell/).
To make any additional deployments such as Container Registry, Pages, or Monitoring, deploy these in the Supporting Node Pool where possible and not in the Webservice or Sidekiq pools. The Supporting Node Pool has been designed
to accommodate several additional deployments. However, if your deployments don't fit into the
pool as given, you can increase the node pool accordingly. Conversely, if the pool in your use case is over-provisioned you can reduce accordingly.
### Example config file
An example for the GitLab Helm Charts targeting the 100 RPS or 5,000 users reference architecture configuration [can be found in the Charts project](https://gitlab.com/gitlab-org/charts/gitlab/-/blob/master/examples/ref/5k.yaml).
<div align="right">
<a type="button" class="btn btn-default" href="#set-up-components">
Back to set up components <i class="fa fa-angle-double-up" aria-hidden="true"></i>
</a>
</div>
## Next steps
After following this guide you should now have a fresh GitLab environment with core functionality configured accordingly.
You may want to configure additional optional features of GitLab depending on your requirements. See [Steps after installing GitLab](../../install/next_steps.md) for more information.
{{< alert type="note" >}}
Depending on your environment and requirements, additional hardware requirements or adjustments may be required to set up additional features as desired. Refer to the individual pages for more information.
{{< /alert >}}
|
https://docs.gitlab.com/administration/configuration_types
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/configuration_types.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
configuration_types.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Duo Self-Hosted configuration and authentication
|
Get started with GitLab Duo Self-Hosted.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
There are two configuration options for self-managed customers:
- **GitLab.com AI gateway**: This is the default configuration for GitLab Self-Managed customers. Use the GitLab-managed AI gateway with external large language model (LLM) providers selected by GitLab (for example, Google Vertex or Anthropic).
- **Self-hosted AI gateway**: Deploy and manage your own AI gateway and language models in your infrastructure, without depending on GitLab-provided external language providers.
## GitLab.com AI gateway
In this configuration, your GitLab instance depends on and sends requests to the external GitLab AI gateway, which communicates with external AI vendors such as Google Vertex or Anthropic. The response is then forwarded back to your GitLab instance.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
actor User as User
participant SelfHostedGitLab as Self-hosted GitLab (Your Instance)
participant GitLabAIGateway as GitLab AI gateway (External)
participant GitLabAIVendor as GitLab AI Vendor (External)
User ->> SelfHostedGitLab: Send request
SelfHostedGitLab ->> SelfHostedGitLab: Check if self-hosted model is configured
SelfHostedGitLab ->> GitLabAIGateway: Forward request for AI processing
GitLabAIGateway ->> GitLabAIVendor: Create prompt and send request to AI model server
GitLabAIVendor -->> GitLabAIGateway: Respond to the prompt
GitLabAIGateway -->> SelfHostedGitLab: Forward AI response
SelfHostedGitLab -->> User: Forward AI response
```
## Self-hosted AI gateway
In this configuration, the entire system is isolated within the enterprise, ensuring a fully self-hosted environment that safeguards data privacy.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
actor User as User
participant SelfHostedGitLab as Self-hosted GitLab
participant SelfHostedAIGateway as Self-hosted AI gateway
participant SelfHostedModel as Self-hosted model
User ->> SelfHostedGitLab: Send request
SelfHostedGitLab ->> SelfHostedGitLab: Check if self-hosted model is configured
SelfHostedGitLab ->> SelfHostedAIGateway: Forward request for AI processing
SelfHostedAIGateway ->> SelfHostedModel: Create prompt and perform request to AI model server
SelfHostedModel -->> SelfHostedAIGateway: Respond to the prompt
SelfHostedAIGateway -->> SelfHostedGitLab: Forward AI response
SelfHostedGitLab -->> User: Forward AI response
```
## Authentication for GitLab Duo Self-Hosted
The authentication process for GitLab Duo Self-Hosted is secure, efficient, and made up of the following key components:
- **Self-issued tokens**: In this architecture, access credentials are not synchronized with `cloud.gitlab.com`. Instead, tokens are self-issued dynamically, similar to the functionality on GitLab.com. This method provides users with immediate access while maintaining a high level of security.
- **Offline environments**: In offline setups, there are no connections to `cloud.gitlab.com`. All requests are routed exclusively to the self-hosted AI gateway.
- **Token minting and verification**: The instance mints the token, which is then verified by the AI gateway against the GitLab instance.
- **Model configuration and security**: When an administrator configures a model, they can incorporate an API key to authenticate requests. Additionally, you can enhance security by specifying connection IP addresses within your network, ensuring that only trusted IPs can interact with the model.
As illustrated in the following diagram:
1. The authentication flow begins when the user configures the model through the GitLab instance and submits a request to access the GitLab Duo feature.
1. The GitLab instance mints an access token, which the user forwards to GitLab and then to the AI gateway for verification.
1. Upon confirming the token's validity, the AI gateway sends a request to the AI model, which uses the API key to authenticate the request and process it.
1. The results are then relayed back to the GitLab instance, completing the flow by sending the response to the user, which is designed to be secure and efficient.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
participant User as User
participant GitLab as GitLab Instance
participant AI gateway as AI gateway
participant AIModel as AI Model
User->>GitLab: Configure Model
User->>GitLab: Request Access
GitLab->>GitLab: Mint Token
GitLab->>User: Send Token
User->>GitLab: Forward Minted Token
GitLab->>AI gateway: Verify Token
AI gateway->>GitLab: Token Validated
GitLab->>AI gateway: Send Request to Model
AI gateway->>AIModel: Send Request to Model
AIModel->>AIModel: Authenticate using API Key
AIModel->>AI gateway: Process Request
AI gateway->>GitLab: Send Result to GitLab
GitLab->>User: Send Response
```
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Get started with GitLab Duo Self-Hosted.
title: GitLab Duo Self-Hosted configuration and authentication
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
There are two configuration options for self-managed customers:
- **GitLab.com AI gateway**: This is the default configuration for GitLab Self-Managed customers. Use the GitLab-managed AI gateway with external large language model (LLM) providers selected by GitLab (for example, Google Vertex or Anthropic).
- **Self-hosted AI gateway**: Deploy and manage your own AI gateway and language models in your infrastructure, without depending on GitLab-provided external language providers.
## GitLab.com AI gateway
In this configuration, your GitLab instance depends on and sends requests to the external GitLab AI gateway, which communicates with external AI vendors such as Google Vertex or Anthropic. The response is then forwarded back to your GitLab instance.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
actor User as User
participant SelfHostedGitLab as Self-hosted GitLab (Your Instance)
participant GitLabAIGateway as GitLab AI gateway (External)
participant GitLabAIVendor as GitLab AI Vendor (External)
User ->> SelfHostedGitLab: Send request
SelfHostedGitLab ->> SelfHostedGitLab: Check if self-hosted model is configured
SelfHostedGitLab ->> GitLabAIGateway: Forward request for AI processing
GitLabAIGateway ->> GitLabAIVendor: Create prompt and send request to AI model server
GitLabAIVendor -->> GitLabAIGateway: Respond to the prompt
GitLabAIGateway -->> SelfHostedGitLab: Forward AI response
SelfHostedGitLab -->> User: Forward AI response
```
## Self-hosted AI gateway
In this configuration, the entire system is isolated within the enterprise, ensuring a fully self-hosted environment that safeguards data privacy.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
actor User as User
participant SelfHostedGitLab as Self-hosted GitLab
participant SelfHostedAIGateway as Self-hosted AI gateway
participant SelfHostedModel as Self-hosted model
User ->> SelfHostedGitLab: Send request
SelfHostedGitLab ->> SelfHostedGitLab: Check if self-hosted model is configured
SelfHostedGitLab ->> SelfHostedAIGateway: Forward request for AI processing
SelfHostedAIGateway ->> SelfHostedModel: Create prompt and perform request to AI model server
SelfHostedModel -->> SelfHostedAIGateway: Respond to the prompt
SelfHostedAIGateway -->> SelfHostedGitLab: Forward AI response
SelfHostedGitLab -->> User: Forward AI response
```
## Authentication for GitLab Duo Self-Hosted
The authentication process for GitLab Duo Self-Hosted is secure, efficient, and made up of the following key components:
- **Self-issued tokens**: In this architecture, access credentials are not synchronized with `cloud.gitlab.com`. Instead, tokens are self-issued dynamically, similar to the functionality on GitLab.com. This method provides users with immediate access while maintaining a high level of security.
- **Offline environments**: In offline setups, there are no connections to `cloud.gitlab.com`. All requests are routed exclusively to the self-hosted AI gateway.
- **Token minting and verification**: The instance mints the token, which is then verified by the AI gateway against the GitLab instance.
- **Model configuration and security**: When an administrator configures a model, they can incorporate an API key to authenticate requests. Additionally, you can enhance security by specifying connection IP addresses within your network, ensuring that only trusted IPs can interact with the model.
As illustrated in the following diagram:
1. The authentication flow begins when the user configures the model through the GitLab instance and submits a request to access the GitLab Duo feature.
1. The GitLab instance mints an access token, which the user forwards to GitLab and then to the AI gateway for verification.
1. Upon confirming the token's validity, the AI gateway sends a request to the AI model, which uses the API key to authenticate the request and process it.
1. The results are then relayed back to the GitLab instance, completing the flow by sending the response to the user, which is designed to be secure and efficient.
```mermaid
%%{init: { "theme": "default", "fontFamily": "GitLab Sans", "sequence": { "actorFontSize": 12, "participantFontSize": 12, "messageFontSize": 12 } }}%%
sequenceDiagram
participant User as User
participant GitLab as GitLab Instance
participant AI gateway as AI gateway
participant AIModel as AI Model
User->>GitLab: Configure Model
User->>GitLab: Request Access
GitLab->>GitLab: Mint Token
GitLab->>User: Send Token
User->>GitLab: Forward Minted Token
GitLab->>AI gateway: Verify Token
AI gateway->>GitLab: Token Validated
GitLab->>AI gateway: Send Request to Model
AI gateway->>AIModel: Send Request to Model
AIModel->>AIModel: Authenticate using API Key
AIModel->>AI gateway: Process Request
AI gateway->>GitLab: Send Result to GitLab
GitLab->>User: Send Response
```
|
https://docs.gitlab.com/administration/supported_llm_serving_platforms
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/supported_llm_serving_platforms.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
supported_llm_serving_platforms.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Duo Self-Hosted supported platforms
|
Supported LLM Serving Platforms.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
There are multiple platforms available to host your self-hosted Large Language Models (LLMs). Each platform has unique features and benefits that can cater to different needs. The following documentation summarises the currently supported options. If the platform you want to use is not in this documentation, provide feedback in the [platform request issue (issue 526144)](https://gitlab.com/gitlab-org/gitlab/-/issues/526144).
## For self-hosted model deployments
### vLLM
[vLLM](https://docs.vllm.ai/en/latest/index.html) is a high-performance inference server optimized for serving LLMs with memory efficiency. It supports model parallelism and integrates easily with existing workflows.
To install vLLM, see the [vLLM Installation Guide](https://docs.vllm.ai/en/latest/getting_started/installation.html). You should install [version v0.6.4.post1](https://github.com/vllm-project/vllm/releases/tag/v0.6.4.post1) or later.
#### Endpoint Configuration
When configuring the endpoint URL for any OpenAI API compatible platforms (such as vLLM) in GitLab:
- The URL must be suffixed with `/v1`
- If using the default vLLM configuration, the endpoint URL would be `https://<hostname>:8000/v1`
- If your server is configured behind a proxy or load balancer, you might not need to specify the port, in which case the URL would be `https://<hostname>/v1`
#### Find the model name
After the model has been deployed, to get the model name for the model identifier field in GitLab, query the vLLM server's `/v1/models` endpoint:
```shell
curl \
--header "Authorization: Bearer API_KEY" \
--header "Content-Type: application/json" \
http://your-vllm-server:8000/v1/models
```
The model name is the value of the `data.id` field in the response.
Example response:
```json
{
"object": "list",
"data": [
{
"id": "Mixtral-8x22B-Instruct-v0.1",
"object": "model",
"created": 1739421415,
"owned_by": "vllm",
"root": "mistralai/Mixtral-8x22B-Instruct-v0.1",
// Additional fields removed for readability
}
]
}
```
In this example, if the model's `id` is `Mixtral-8x22B-Instruct-v0.1`, you would set the model identifier in GitLab as `custom_openai/Mixtral-8x22B-Instruct-v0.1`.
For more information on:
- vLLM supported models, see the [vLLM Supported Models documentation](https://docs.vllm.ai/en/latest/models/supported_models.html).
- Available options when using vLLM to run a model, see the [vLLM documentation on engine arguments](https://docs.vllm.ai/en/stable/usage/engine_args.html).
- The hardware needed for the models, see the [Supported models and Hardware requirements documentation](supported_models_and_hardware_requirements.md).
Examples:
#### Mistral-7B-Instruct-v0.2
1. Download the model from HuggingFace:
```shell
git clone https://<your-hugging-face-username>:<your-hugging-face-token>@huggingface.co/mistralai/Mistral-7B-Instruct-v0.3
```
1. Run the server:
```shell
vllm serve <path-to-model>/Mistral-7B-Instruct-v0.3 \
--served_model_name <choose-a-name-for-the-model> \
--tokenizer_mode mistral \
--tensor_parallel_size <number-of-gpus> \
--load_format mistral \
--config_format mistral \
--tokenizer <path-to-model>/Mistral-7B-Instruct-v0.3
```
#### Mixtral-8x7B-Instruct-v0.1
1. Download the model from HuggingFace:
```shell
git clone https://<your-hugging-face-username>:<your-hugging-face-token>@huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1
```
1. Rename the token config:
```shell
cd <path-to-model>/Mixtral-8x7B-Instruct-v0.1
cp tokenizer.model tokenizer.model.v3
```
1. Run the model:
```shell
vllm serve <path-to-model>/Mixtral-8x7B-Instruct-v0.1 \
--tensor_parallel_size 4 \
--served_model_name <choose-a-name-for-the-model> \
--tokenizer_mode mistral \
--load_format safetensors \
--tokenizer <path-to-model>/Mixtral-8x7B-Instruct-v0.1
```
#### Disable request logging to reduce latency
When running vLLM in production, you can significantly reduce latency by using the `--disable-log-requests` flag to disable request logging.
{{< alert type="note" >}}
Use this flag only when you do not need detailed request logging.
{{< /alert >}}
Disabling request logging minimizes the overhead introduced by verbose logs, especially under high load, and can help improve performance levels.
```shell
vllm serve <path-to-model>/<model-version> \
--served_model_name <choose-a-name-for-the-model> \
--disable-log-requests
```
This change has been observed to notably improve response times in internal benchmarks.
## For cloud-hosted model deployments
### AWS Bedrock
[AWS Bedrock](https://aws.amazon.com/bedrock/) is a fully managed service that
allows developers to build and scale generative AI applications using pre-trained
models from leading AI companies. It seamlessly integrates with other AWS services
and offers a pay-as-you-go pricing model.
To access AWS Bedrock models:
1. Configure IAM credentials to access Bedrock with the appropriate AWS IAM
permissions:
- Make sure that the IAM role has the `AmazonBedrockFullAccess` policy to allow
[access to Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonBedrockFullAccess). You cannot do this in
the GitLab Duo Self-Hosted UI.
- [Use the AWS console to request access to the models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html) that you want to use.
1. Authenticate your AI gateway instance by exporting the appropriate AWS SDK
environment variables such as [`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_REGION_NAME`](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) when starting
the Docker container.
For more information, see the [AWS Identity and Access Management (IAM) Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).
{{< alert type="note" >}}
Temporary credentials are not supported by AI gateway at this time. For more information on adding support for Bedrock to use instance profile or temporary credentials, see [issue 542389](https://gitlab.com/gitlab-org/gitlab/-/issues/542389).
{{</alert>}}
1. Optional. To set up a private Bedrock endpoint operating in a virtual private cloud (VPC),
make sure the `AWS_BEDROCK_RUNTIME_ENDPOINT` environment variable is configured
with your internal URL when launching the AI gateway container.
An example configuration: `AWS_BEDROCK_RUNTIME_ENDPOINT = https://bedrock-runtime.{aws_region_name}.amazonaws.com`
For VPC endpoints, the URL format may be different, such as `https://vpce-{vpc-endpoint-id}-{service-name}.{aws_region_name}.vpce.amazonaws.com`
For more information, see [supported foundation models in Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html).
### Azure OpenAI
[Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/) provides
access to OpenAI's powerful models, enabling developers to integrate advanced AI
capabilities into their applications with robust security and scalable infrastructure.
For more information, see:
- [Working with Azure OpenAI models](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/working-with-models?tabs=powershell)
- [Azure OpenAI Service models](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure%2Cglobal-standard%2Cstandard-chat-completions)
## Use multiple models and platforms
With GitLab Duo Self-Hosted, you can use multiple models and platforms in the same GitLab instance.
For example, you can configure one feature to use Azure OpenAI, and another feature to use AWS Bedrock or self-hosted models served with vLLM.
This setup gives you flexibility to choose the best model and platform for each use case. Models must be supported and served through a compatible platform.
For more information on setting up different providers, see:
- [Configure GitLab Duo Self-Hosted features](configure_duo_features.md)
- [Supported GitLab Duo Self-Hosted models and hardware requirements](supported_models_and_hardware_requirements.md)
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Supported LLM Serving Platforms.
title: GitLab Duo Self-Hosted supported platforms
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
There are multiple platforms available to host your self-hosted Large Language Models (LLMs). Each platform has unique features and benefits that can cater to different needs. The following documentation summarises the currently supported options. If the platform you want to use is not in this documentation, provide feedback in the [platform request issue (issue 526144)](https://gitlab.com/gitlab-org/gitlab/-/issues/526144).
## For self-hosted model deployments
### vLLM
[vLLM](https://docs.vllm.ai/en/latest/index.html) is a high-performance inference server optimized for serving LLMs with memory efficiency. It supports model parallelism and integrates easily with existing workflows.
To install vLLM, see the [vLLM Installation Guide](https://docs.vllm.ai/en/latest/getting_started/installation.html). You should install [version v0.6.4.post1](https://github.com/vllm-project/vllm/releases/tag/v0.6.4.post1) or later.
#### Endpoint Configuration
When configuring the endpoint URL for any OpenAI API compatible platforms (such as vLLM) in GitLab:
- The URL must be suffixed with `/v1`
- If using the default vLLM configuration, the endpoint URL would be `https://<hostname>:8000/v1`
- If your server is configured behind a proxy or load balancer, you might not need to specify the port, in which case the URL would be `https://<hostname>/v1`
#### Find the model name
After the model has been deployed, to get the model name for the model identifier field in GitLab, query the vLLM server's `/v1/models` endpoint:
```shell
curl \
--header "Authorization: Bearer API_KEY" \
--header "Content-Type: application/json" \
http://your-vllm-server:8000/v1/models
```
The model name is the value of the `data.id` field in the response.
Example response:
```json
{
"object": "list",
"data": [
{
"id": "Mixtral-8x22B-Instruct-v0.1",
"object": "model",
"created": 1739421415,
"owned_by": "vllm",
"root": "mistralai/Mixtral-8x22B-Instruct-v0.1",
// Additional fields removed for readability
}
]
}
```
In this example, if the model's `id` is `Mixtral-8x22B-Instruct-v0.1`, you would set the model identifier in GitLab as `custom_openai/Mixtral-8x22B-Instruct-v0.1`.
For more information on:
- vLLM supported models, see the [vLLM Supported Models documentation](https://docs.vllm.ai/en/latest/models/supported_models.html).
- Available options when using vLLM to run a model, see the [vLLM documentation on engine arguments](https://docs.vllm.ai/en/stable/usage/engine_args.html).
- The hardware needed for the models, see the [Supported models and Hardware requirements documentation](supported_models_and_hardware_requirements.md).
Examples:
#### Mistral-7B-Instruct-v0.2
1. Download the model from HuggingFace:
```shell
git clone https://<your-hugging-face-username>:<your-hugging-face-token>@huggingface.co/mistralai/Mistral-7B-Instruct-v0.3
```
1. Run the server:
```shell
vllm serve <path-to-model>/Mistral-7B-Instruct-v0.3 \
--served_model_name <choose-a-name-for-the-model> \
--tokenizer_mode mistral \
--tensor_parallel_size <number-of-gpus> \
--load_format mistral \
--config_format mistral \
--tokenizer <path-to-model>/Mistral-7B-Instruct-v0.3
```
#### Mixtral-8x7B-Instruct-v0.1
1. Download the model from HuggingFace:
```shell
git clone https://<your-hugging-face-username>:<your-hugging-face-token>@huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1
```
1. Rename the token config:
```shell
cd <path-to-model>/Mixtral-8x7B-Instruct-v0.1
cp tokenizer.model tokenizer.model.v3
```
1. Run the model:
```shell
vllm serve <path-to-model>/Mixtral-8x7B-Instruct-v0.1 \
--tensor_parallel_size 4 \
--served_model_name <choose-a-name-for-the-model> \
--tokenizer_mode mistral \
--load_format safetensors \
--tokenizer <path-to-model>/Mixtral-8x7B-Instruct-v0.1
```
#### Disable request logging to reduce latency
When running vLLM in production, you can significantly reduce latency by using the `--disable-log-requests` flag to disable request logging.
{{< alert type="note" >}}
Use this flag only when you do not need detailed request logging.
{{< /alert >}}
Disabling request logging minimizes the overhead introduced by verbose logs, especially under high load, and can help improve performance levels.
```shell
vllm serve <path-to-model>/<model-version> \
--served_model_name <choose-a-name-for-the-model> \
--disable-log-requests
```
This change has been observed to notably improve response times in internal benchmarks.
## For cloud-hosted model deployments
### AWS Bedrock
[AWS Bedrock](https://aws.amazon.com/bedrock/) is a fully managed service that
allows developers to build and scale generative AI applications using pre-trained
models from leading AI companies. It seamlessly integrates with other AWS services
and offers a pay-as-you-go pricing model.
To access AWS Bedrock models:
1. Configure IAM credentials to access Bedrock with the appropriate AWS IAM
permissions:
- Make sure that the IAM role has the `AmazonBedrockFullAccess` policy to allow
[access to Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonBedrockFullAccess). You cannot do this in
the GitLab Duo Self-Hosted UI.
- [Use the AWS console to request access to the models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html) that you want to use.
1. Authenticate your AI gateway instance by exporting the appropriate AWS SDK
environment variables such as [`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_REGION_NAME`](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) when starting
the Docker container.
For more information, see the [AWS Identity and Access Management (IAM) Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).
{{< alert type="note" >}}
Temporary credentials are not supported by AI gateway at this time. For more information on adding support for Bedrock to use instance profile or temporary credentials, see [issue 542389](https://gitlab.com/gitlab-org/gitlab/-/issues/542389).
{{</alert>}}
1. Optional. To set up a private Bedrock endpoint operating in a virtual private cloud (VPC),
make sure the `AWS_BEDROCK_RUNTIME_ENDPOINT` environment variable is configured
with your internal URL when launching the AI gateway container.
An example configuration: `AWS_BEDROCK_RUNTIME_ENDPOINT = https://bedrock-runtime.{aws_region_name}.amazonaws.com`
For VPC endpoints, the URL format may be different, such as `https://vpce-{vpc-endpoint-id}-{service-name}.{aws_region_name}.vpce.amazonaws.com`
For more information, see [supported foundation models in Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html).
### Azure OpenAI
[Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/) provides
access to OpenAI's powerful models, enabling developers to integrate advanced AI
capabilities into their applications with robust security and scalable infrastructure.
For more information, see:
- [Working with Azure OpenAI models](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/working-with-models?tabs=powershell)
- [Azure OpenAI Service models](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure%2Cglobal-standard%2Cstandard-chat-completions)
## Use multiple models and platforms
With GitLab Duo Self-Hosted, you can use multiple models and platforms in the same GitLab instance.
For example, you can configure one feature to use Azure OpenAI, and another feature to use AWS Bedrock or self-hosted models served with vLLM.
This setup gives you flexibility to choose the best model and platform for each use case. Models must be supported and served through a compatible platform.
For more information on setting up different providers, see:
- [Configure GitLab Duo Self-Hosted features](configure_duo_features.md)
- [Supported GitLab Duo Self-Hosted models and hardware requirements](supported_models_and_hardware_requirements.md)
|
https://docs.gitlab.com/administration/supported_models_and_hardware_requirements
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/supported_models_and_hardware_requirements.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
supported_models_and_hardware_requirements.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Supported GitLab Duo Self-Hosted models and hardware requirements
|
Supported models and hardware requirements.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
GitLab Duo Self-Hosted supports integration with industry-leading models from Mistral,
Claude, and GPT
through your preferred serving platform. Choose from these models to match your specific performance
needs and use cases.
## Supported models
Support for the following GitLab-supported large language models (LLMs) is generally available. If the model you want to use is not in this documentation, provide feedback in the [model request issue (issue 526751)](https://gitlab.com/gitlab-org/gitlab/-/issues/526751).
- Fully compatible: The model can likely handle the feature without any loss of quality.
- Largely compatible: The model supports the feature, but there might be compromises or limitations.
- Not compatible: The model is unsuitable for the feature, likely resulting in significant quality loss or performance issues. Models that are marked not compatible for a feature will not receive GitLab support for that specific feature.
<!-- vale gitlab_base.Spelling = NO -->
| Model Family | Model | Supported Platforms | Code completion | Code generation | GitLab Duo Chat |
|-------------|-------|---------------------|-----------------|-----------------|-----------------|
| Mistral Codestral | [Codestral 22B v0.1](https://huggingface.co/mistralai/Codestral-22B-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | Not applicable |
| Mistral | [Mistral 7B-it v0.3](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Mistral | [Mixtral 8x7B-it v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments), [AWS Bedrock](https://aws.amazon.com/bedrock/mistral/) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Mistral | [Mixtral 8x22B-it v0.1](https://huggingface.co/mistralai/Mixtral-8x22B-Instruct-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Mistral | [Mistral Small 24B Instruct 2506](https://huggingface.co/mistralai/Mistral-Small-3.2-24B-Instruct-2506) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 3 | [Claude 3.5 Sonnet](https://www.anthropic.com/news/claude-3-5-sonnet) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 3 | [Claude 3.7 Sonnet](https://www.anthropic.com/news/claude-3-7-sonnet) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 4 | [Claude 4 Sonnet](https://www.anthropic.com/news/claude-4) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| GPT | [GPT-4 Turbo](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| GPT | [GPT-4o](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| GPT | [GPT-4o-mini](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Llama | [Llama 3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Llama | [Llama 3.1 8B](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Llama | [Llama 3 70B](https://huggingface.co/meta-llama/Meta-Llama-3-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Llama | [Llama 3.1 70B](https://huggingface.co/meta-llama/Llama-3.1-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Llama | [Llama 3.3 70B](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
### Experimental and beta models
The following models are configurable for the functionalities marked below, but are currently in beta or experimental status, under evaluation, and are excluded from the "Customer Integrated Models" definition in the [AI Functionality Terms](https://handbook.gitlab.com/handbook/legal/ai-functionality-terms/):
| Model family | Model | Supported platforms | Status | Code completion | Code generation | GitLab Duo Chat |
|--------------- |-------|---------------------|--------|-----------------|-----------------|-----------------|
| CodeGemma | [CodeGemma 2b](https://huggingface.co/google/codegemma-2b) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| CodeGemma | [CodeGemma 7b-it](https://huggingface.co/google/codegemma-7b-it) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| CodeGemma | [CodeGemma 7b-code](https://huggingface.co/google/codegemma-7b) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| Code Llama | [Code-Llama 13b](https://huggingface.co/meta-llama/CodeLlama-13b-Instruct-hf) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| DeepSeek Coder | [DeepSeek Coder 33b Instruct](https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| DeepSeek Coder | [DeepSeek Coder 33b Base](https://huggingface.co/deepseek-ai/deepseek-coder-33b-base) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| Mistral | [Mistral 7B-it v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) <br> [AWS Bedrock](https://aws.amazon.com/bedrock/mistral/) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
<!-- vale gitlab_base.Spelling = YES -->
## Hardware requirements
The following hardware specifications are the minimum requirements for running GitLab Duo Self-Hosted on-premise. Requirements vary significantly based on the model size and intended usage:
### Base system requirements
- **CPU**:
- Minimum: 8 cores (16 threads)
- Recommended: 16+ cores for production environments
- **RAM**:
- Minimum: 32 GB
- Recommended: 64 GB for most models
- **Storage**:
- SSD with sufficient space for model weights and data.
### GPU requirements by model size
| Model size | Minimum GPU configuration | Minimum VRAM required |
|--------------------------------------------|---------------------------|-----------------------|
| 7B models<br>(for example, Mistral 7B) | 1x NVIDIA A100 (40 GB) | 35 GB |
| 22B models<br>(for example, Codestral 22B) | 2x NVIDIA A100 (80 GB) | 110 GB |
| Mixtral 8x7B | 2x NVIDIA A100 (80 GB) | 220 GB |
| Mixtral 8x22B | 8x NVIDIA A100 (80 GB) | 526 GB |
Use [Hugging Face's memory utility](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) to verify memory requirements.
### Response time by model size and GPU
#### Small machine
With a `a2-highgpu-2g` (2x Nvidia A100 40 GB - 150 GB vRAM) or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests | Total TPS |
|--------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 7.09 | 717.0 | 101.19 | 7.09 | 101.17 |
| Mistral-7B-Instruct-v0.3 | 10 | 8.41 | 764.2 | 90.35 | 13.70 | 557.80 |
| Mistral-7B-Instruct-v0.3 | 100 | 13.97 | 693.23 | 49.17 | 20.81 | 3331.59 |
#### Medium machine
With a `a2-ultragpu-4g` (4x Nvidia A100 40 GB - 340 GB vRAM) machine on GCP or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests | Total TPS |
|----------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 3.80 | 499.0 | 131.25 | 3.80 | 131.23 |
| Mistral-7B-Instruct-v0.3 | 10 | 6.00 | 740.6 | 122.85 | 8.19 | 904.22 |
| Mistral-7B-Instruct-v0.3 | 100 | 11.71 | 695.71 | 59.06 | 15.54 | 4477.34 |
| Mixtral-8x7B-Instruct-v0.1 | 1 | 6.50 | 400.0 | 61.55 | 6.50 | 61.53 |
| Mixtral-8x7B-Instruct-v0.1 | 10 | 16.58 | 768.9 | 40.33 | 32.56 | 236.13 |
| Mixtral-8x7B-Instruct-v0.1 | 100 | 25.90 | 767.38 | 26.87 | 55.57 | 1380.68 |
#### Large machine
With a `a2-ultragpu-8g` (8 x NVIDIA A100 80 GB - 1360 GB vRAM) machine on GCP or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests (sec) | Total TPS |
|-----------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-----------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 3.23 | 479.0 | 148.41 | 3.22 | 148.36 |
| Mistral-7B-Instruct-v0.3 | 10 | 4.95 | 678.3 | 135.98 | 6.85 | 989.11 |
| Mistral-7B-Instruct-v0.3 | 100 | 10.14 | 713.27 | 69.63 | 13.96 | 5108.75 |
| Mixtral-8x7B-Instruct-v0.1 | 1 | 6.08 | 709.0 | 116.69 | 6.07 | 116.64 |
| Mixtral-8x7B-Instruct-v0.1 | 10 | 9.95 | 645.0 | 63.68 | 13.40 | 481.06 |
| Mixtral-8x7B-Instruct-v0.1 | 100 | 13.83 | 585.01 | 41.80 | 20.38 | 2869.12 |
| Mixtral-8x22B-Instruct-v0.1 | 1 | 14.39 | 828.0 | 57.56 | 14.38 | 57.55 |
| Mixtral-8x22B-Instruct-v0.1 | 10 | 20.57 | 629.7 | 30.24 | 28.02 | 224.71 |
| Mixtral-8x22B-Instruct-v0.1 | 100 | 27.58 | 592.49 | 21.34 | 36.80 | 1609.85 |
### AI Gateway Hardware Requirements
For recommendations on AI gateway hardware, see the [AI gateway scaling recommendations](../../install/install_ai_gateway.md#scaling-recommendations).
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Supported models and hardware requirements.
title: Supported GitLab Duo Self-Hosted models and hardware requirements
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
GitLab Duo Self-Hosted supports integration with industry-leading models from Mistral,
Claude, and GPT
through your preferred serving platform. Choose from these models to match your specific performance
needs and use cases.
## Supported models
Support for the following GitLab-supported large language models (LLMs) is generally available. If the model you want to use is not in this documentation, provide feedback in the [model request issue (issue 526751)](https://gitlab.com/gitlab-org/gitlab/-/issues/526751).
- Fully compatible: The model can likely handle the feature without any loss of quality.
- Largely compatible: The model supports the feature, but there might be compromises or limitations.
- Not compatible: The model is unsuitable for the feature, likely resulting in significant quality loss or performance issues. Models that are marked not compatible for a feature will not receive GitLab support for that specific feature.
<!-- vale gitlab_base.Spelling = NO -->
| Model Family | Model | Supported Platforms | Code completion | Code generation | GitLab Duo Chat |
|-------------|-------|---------------------|-----------------|-----------------|-----------------|
| Mistral Codestral | [Codestral 22B v0.1](https://huggingface.co/mistralai/Codestral-22B-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | Not applicable |
| Mistral | [Mistral 7B-it v0.3](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Mistral | [Mixtral 8x7B-it v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments), [AWS Bedrock](https://aws.amazon.com/bedrock/mistral/) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Mistral | [Mixtral 8x22B-it v0.1](https://huggingface.co/mistralai/Mixtral-8x22B-Instruct-v0.1) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Mistral | [Mistral Small 24B Instruct 2506](https://huggingface.co/mistralai/Mistral-Small-3.2-24B-Instruct-2506) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 3 | [Claude 3.5 Sonnet](https://www.anthropic.com/news/claude-3-5-sonnet) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 3 | [Claude 3.7 Sonnet](https://www.anthropic.com/news/claude-3-7-sonnet) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Claude 4 | [Claude 4 Sonnet](https://www.anthropic.com/news/claude-4) | [AWS Bedrock](https://aws.amazon.com/bedrock/claude/) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| GPT | [GPT-4 Turbo](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| GPT | [GPT-4o](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| GPT | [GPT-4o-mini](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo) | [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Llama | [Llama 3 8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Llama | [Llama 3.1 8B](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-dashed" >}} Largely compatible |
| Llama | [Llama 3 70B](https://huggingface.co/meta-llama/Meta-Llama-3-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-dashed" >}} Largely compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="dash-circle" >}} Not compatible |
| Llama | [Llama 3.1 70B](https://huggingface.co/meta-llama/Llama-3.1-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
| Llama | [Llama 3.3 70B](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible | {{< icon name="check-circle-filled" >}} Fully compatible |
### Experimental and beta models
The following models are configurable for the functionalities marked below, but are currently in beta or experimental status, under evaluation, and are excluded from the "Customer Integrated Models" definition in the [AI Functionality Terms](https://handbook.gitlab.com/handbook/legal/ai-functionality-terms/):
| Model family | Model | Supported platforms | Status | Code completion | Code generation | GitLab Duo Chat |
|--------------- |-------|---------------------|--------|-----------------|-----------------|-----------------|
| CodeGemma | [CodeGemma 2b](https://huggingface.co/google/codegemma-2b) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| CodeGemma | [CodeGemma 7b-it](https://huggingface.co/google/codegemma-7b-it) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| CodeGemma | [CodeGemma 7b-code](https://huggingface.co/google/codegemma-7b) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| Code Llama | [Code-Llama 13b](https://huggingface.co/meta-llama/CodeLlama-13b-Instruct-hf) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| DeepSeek Coder | [DeepSeek Coder 33b Instruct](https://huggingface.co/deepseek-ai/deepseek-coder-33b-instruct) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No |
| DeepSeek Coder | [DeepSeek Coder 33b Base](https://huggingface.co/deepseek-ai/deepseek-coder-33b-base) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="dotted-circle" >}} No | {{< icon name="dotted-circle" >}} No |
| Mistral | [Mistral 7B-it v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | [vLLM](supported_llm_serving_platforms.md#for-self-hosted-model-deployments) <br> [AWS Bedrock](https://aws.amazon.com/bedrock/mistral/) | Experimental | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
<!-- vale gitlab_base.Spelling = YES -->
## Hardware requirements
The following hardware specifications are the minimum requirements for running GitLab Duo Self-Hosted on-premise. Requirements vary significantly based on the model size and intended usage:
### Base system requirements
- **CPU**:
- Minimum: 8 cores (16 threads)
- Recommended: 16+ cores for production environments
- **RAM**:
- Minimum: 32 GB
- Recommended: 64 GB for most models
- **Storage**:
- SSD with sufficient space for model weights and data.
### GPU requirements by model size
| Model size | Minimum GPU configuration | Minimum VRAM required |
|--------------------------------------------|---------------------------|-----------------------|
| 7B models<br>(for example, Mistral 7B) | 1x NVIDIA A100 (40 GB) | 35 GB |
| 22B models<br>(for example, Codestral 22B) | 2x NVIDIA A100 (80 GB) | 110 GB |
| Mixtral 8x7B | 2x NVIDIA A100 (80 GB) | 220 GB |
| Mixtral 8x22B | 8x NVIDIA A100 (80 GB) | 526 GB |
Use [Hugging Face's memory utility](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) to verify memory requirements.
### Response time by model size and GPU
#### Small machine
With a `a2-highgpu-2g` (2x Nvidia A100 40 GB - 150 GB vRAM) or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests | Total TPS |
|--------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 7.09 | 717.0 | 101.19 | 7.09 | 101.17 |
| Mistral-7B-Instruct-v0.3 | 10 | 8.41 | 764.2 | 90.35 | 13.70 | 557.80 |
| Mistral-7B-Instruct-v0.3 | 100 | 13.97 | 693.23 | 49.17 | 20.81 | 3331.59 |
#### Medium machine
With a `a2-ultragpu-4g` (4x Nvidia A100 40 GB - 340 GB vRAM) machine on GCP or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests | Total TPS |
|----------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 3.80 | 499.0 | 131.25 | 3.80 | 131.23 |
| Mistral-7B-Instruct-v0.3 | 10 | 6.00 | 740.6 | 122.85 | 8.19 | 904.22 |
| Mistral-7B-Instruct-v0.3 | 100 | 11.71 | 695.71 | 59.06 | 15.54 | 4477.34 |
| Mixtral-8x7B-Instruct-v0.1 | 1 | 6.50 | 400.0 | 61.55 | 6.50 | 61.53 |
| Mixtral-8x7B-Instruct-v0.1 | 10 | 16.58 | 768.9 | 40.33 | 32.56 | 236.13 |
| Mixtral-8x7B-Instruct-v0.1 | 100 | 25.90 | 767.38 | 26.87 | 55.57 | 1380.68 |
#### Large machine
With a `a2-ultragpu-8g` (8 x NVIDIA A100 80 GB - 1360 GB vRAM) machine on GCP or equivalent:
| Model name | Number of requests | Average time per request (sec) | Average tokens in response | Average tokens per second per request | Total time for requests (sec) | Total TPS |
|-----------------------------|--------------------|------------------------------|----------------------------|---------------------------------------|-----------------------------|-----------|
| Mistral-7B-Instruct-v0.3 | 1 | 3.23 | 479.0 | 148.41 | 3.22 | 148.36 |
| Mistral-7B-Instruct-v0.3 | 10 | 4.95 | 678.3 | 135.98 | 6.85 | 989.11 |
| Mistral-7B-Instruct-v0.3 | 100 | 10.14 | 713.27 | 69.63 | 13.96 | 5108.75 |
| Mixtral-8x7B-Instruct-v0.1 | 1 | 6.08 | 709.0 | 116.69 | 6.07 | 116.64 |
| Mixtral-8x7B-Instruct-v0.1 | 10 | 9.95 | 645.0 | 63.68 | 13.40 | 481.06 |
| Mixtral-8x7B-Instruct-v0.1 | 100 | 13.83 | 585.01 | 41.80 | 20.38 | 2869.12 |
| Mixtral-8x22B-Instruct-v0.1 | 1 | 14.39 | 828.0 | 57.56 | 14.38 | 57.55 |
| Mixtral-8x22B-Instruct-v0.1 | 10 | 20.57 | 629.7 | 30.24 | 28.02 | 224.71 |
| Mixtral-8x22B-Instruct-v0.1 | 100 | 27.58 | 592.49 | 21.34 | 36.80 | 1609.85 |
### AI Gateway Hardware Requirements
For recommendations on AI gateway hardware, see the [AI gateway scaling recommendations](../../install/install_ai_gateway.md#scaling-recommendations).
|
https://docs.gitlab.com/administration/gitlab_duo_self_hosted
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
_index.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Duo Self-Hosted
|
Host your own AI gateway and language models.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
To maintain full control over your data privacy, security, and the deployment of large language models (LLMs) in your own infrastructure, use GitLab Duo Self-Hosted.
By deploying GitLab Duo Self-Hosted, you can manage the entire lifecycle of requests made to LLM backends for GitLab Duo features, ensuring that all requests stay in your enterprise network, and avoiding external dependencies.
For a click-through demo, see [GitLab Duo Self-Hosted product tour](https://gitlab.navattic.com/gitlab-duo-self-hosted).
<!-- Demo published on 2025-02-13 -->
<i class="fa-youtube-play" aria-hidden="true"></i>
For an overview, see [GitLab Duo Self-Hosted: AI in your private environment](https://youtu.be/TQoO3sFnb28?si=uD-ps6aRnE28xNv3).
<!-- Video published on 2025-02-20 -->
## Why use GitLab Duo Self-Hosted
With GitLab Duo Self-Hosted, you can:
- Choose any GitLab-supported LLM.
- Retain full control over data by keeping all request/response logs in your domain, ensuring complete privacy and security with no external API calls.
- Isolate the GitLab instance, AI gateway, and models in your own environment.
- Select specific GitLab Duo features tailored to your users.
- Eliminate reliance on the shared GitLab AI gateway.
This setup ensures enterprise-level privacy and flexibility, allowing seamless integration of your LLMs with GitLab Duo features.
### Supported GitLab Duo features
The following tables state:
- The GitLab Duo features and whether those features are available on GitLab Duo Self-Hosted.
- Which version of GitLab is needed to use those features on GitLab Duo Self-Hosted.
- The status of those features. A feature's status on GitLab Duo Self-Hosted can be
different to [that same feature's status when it is hosted on GitLab](../../user/gitlab_duo/feature_summary.md).
{{< alert type="note" >}}
To use these features with GitLab Duo Self-Hosted, you must have the Duo Enterprise add-on. This applies regardless
of whether you can use these features with Duo Core or Duo Pro when
[GitLab hosts the models and connects to those models through the cloud-based AI gateway](../../user/gitlab_duo/gateway.md).
{{< /alert >}}
#### Code Suggestions
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| ---------------------------------------------------------------------------- | ------------------------------------------- | --------------------- | --- |
| [Code Suggestions](../../user/project/repository/code_suggestions/_index.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
#### Chat
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [General](../../user/gitlab_duo_chat/_index.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Code Explanation](../../user/gitlab_duo_chat/examples.md#explain-selected-code) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Test Generation](../../user/gitlab_duo_chat/examples.md#write-tests-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Refactor Code](../../user/gitlab_duo_chat/examples.md#refactor-code-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Fix Code](../../user/gitlab_duo_chat/examples.md#fix-code-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Root Cause Analysis](../../user/gitlab_duo_chat/examples.md#troubleshoot-failed-cicd-jobs-with-root-cause-analysis) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.10 and later | Beta |
| [Vulnerability Explanation](../../user/application_security/vulnerabilities/_index.md#vulnerability-explanation) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
For more examples of a question you can ask, see
[Ask about GitLab](../../user/gitlab_duo_chat/examples.md).
#### GitLab Duo in merge requests
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [Merge Commit Message Generation](../../user/project/merge_requests/duo_in_merge_requests.md#generate-a-merge-commit-message) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [Merge Request Summary](../../user/project/merge_requests/duo_in_merge_requests.md#generate-a-description-by-summarizing-code-changes) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [Code Review](../../user/project/merge_requests/duo_in_merge_requests.md#have-gitlab-duo-review-your-code) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.3 and later | Beta |
| [Code Review Summary](../../user/project/merge_requests/duo_in_merge_requests.md#summarize-a-code-review) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Experiment |
#### GitLab Duo in issues
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [Issue Description Generation](../../user/project/issues/managing_issues.md#populate-an-issue-with-issue-description-generation) | {{< icon name="dash-circle" >}} No | Not applicable | Not applicable |
| [Discussion Summary](../../user/discussions/_index.md#summarize-issue-discussions-with-duo-chat) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
#### Other features
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [GitLab Duo for the CLI](../../editor_extensions/gitlab_cli/_index.md#gitlab-duo-for-the-cli) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md) | {{< icon name="dash-circle" >}} No | Not applicable | Not applicable |
| [Vulnerability Resolution](../../user/application_security/vulnerabilities/_index.md#vulnerability-resolution) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [AI Impact Dashboard](../../user/analytics/ai_impact_analytics.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Beta |
### Prerequisites
Before setting up the GitLab Duo Self-Hosted infrastructure, you must have:
- A [supported model](supported_models_and_hardware_requirements.md) (either cloud-based or on-premises).
- A [supported serving platform](supported_llm_serving_platforms.md) (either cloud-based or on-premises).
- A [locally hosted AI gateway](../../install/install_ai_gateway.md).
- [Premium or Ultimate with GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?toggle=gitlab-duo-pro).
- GitLab 17.9 or later.
## Decide on your configuration type
GitLab Self-Managed customers can implement AI-native features using either of the following options:
- [**Self-hosted AI gateway and LLMs**](#self-hosted-ai-gateway-and-llms): Full control over your AI infrastructure.
- [**GitLab.com AI gateway with default GitLab external vendor LLMs**](#gitlabcom-ai-gateway-with-default-gitlab-external-vendor-llms): Use GitLab managed AI infrastructure.
The differences between these options are:
| Feature | Self-hosted AI gateway | GitLab.com AI gateway |
| --------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------- |
| Infrastructure requirements | Requires hosting your own AI gateway and models | No additional infrastructure needed |
| Model options | Choose from [supported models](supported_models_and_hardware_requirements.md) | Uses the default GitLab external vendor LLMs |
| Network requirements | Can operate in fully isolated networks | Requires internet connectivity |
| Responsibilities | You set up your infrastructure, and do your own maintenance | GitLab does the set up and maintenance |
### Self-hosted AI gateway and LLMs
In a fully self-hosted configuration, you deploy your own AI gateway and use any [supported LLMs](supported_models_and_hardware_requirements.md) in your infrastructure, without relying on external public services. This gives you full control over your data and security.
While this configuration is fully self-hosted and you can use models like Mistral that are hosted on your own infrastructure, you can still use cloud-based LLM services like [AWS Bedrock](https://aws.amazon.com/bedrock/) or [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) as your model backend.
If you have an offline environment with physical barriers or security policies that prevent or limit internet access, and comprehensive LLM controls, you can use GitLab Duo Self-Hosted.
For licensing, you must have a GitLab Premium or Ultimate subscription, and [GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?type=free-trial). Offline Enterprise licenses are available for those customers with fully isolated offline environments. To get access to your purchased subscription, request a license through the [Customers Portal](../../subscriptions/customers_portal.md).
For more information, see:
- [Set up a GitLab Duo Self-Hosted infrastructure](#set-up-a-gitlab-duo-self-hosted-infrastructure)
- The [self-hosted AI gateway configuration diagram](configuration_types.md#self-hosted-ai-gateway).
### GitLab.com AI gateway with default GitLab external vendor LLMs
If you do not meet the use case criteria for GitLab Duo Self-Hosted, you can use the
GitLab.com AI gateway with default GitLab external vendor LLMs.
The GitLab.com AI gateway is the default Enterprise offering and is not self-hosted. In this configuration,
you connect your instance to the GitLab-hosted AI gateway, which
integrates with external vendor LLM providers, including:
- [Anthropic](https://www.anthropic.com/)
- [Fireworks AI](https://fireworks.ai/)
- [Google Vertex](https://cloud.google.com/vertex-ai/)
These LLMs communicate through the GitLab Cloud Connector,
offering a ready-to-use AI solution without the need for on-premise infrastructure.
For licensing, you must have a GitLab Premium or Ultimate subscription, and [GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?type=free-trial). To get access to your purchased subscription, request a license through the [Customers Portal](../../subscriptions/customers_portal.md)
For more information, see the
[GitLab.com AI gateway configuration diagram](configuration_types.md#gitlabcom-ai-gateway).
To set up this infrastructure, see [how to configure GitLab Duo on a GitLab Self-Managed instance](../../user/gitlab_duo/setup.md).
## Set up a GitLab Duo Self-Hosted infrastructure
To set up a fully isolated GitLab Duo Self-Hosted infrastructure:
1. **Install a Large Language Model (LLM) Serving Infrastructure**
- We support various platforms for serving and hosting your LLMs, such as vLLM, AWS Bedrock, and Azure OpenAI. To help you choose the most suitable option for effectively deploying your models, see the [supported LLM platforms documentation](supported_llm_serving_platforms.md) for more information on each platform's features.
- We provide a comprehensive matrix of supported models along with their specific features and hardware requirements. To help select models that best align with your infrastructure needs for optimal performance, see the [supported models and hardware requirements documentation](supported_models_and_hardware_requirements.md).
1. **Install the GitLab AI gateway**
[Install the AI gateway](../../install/install_ai_gateway.md) to efficiently configure your AI infrastructure.
1. **Configure GitLab Duo features**
See the [Configure GitLab Duo features documentation](configure_duo_features.md) for instructions on how to customize your environment to effectively meet your operational needs.
1. **Enable logging**
You can find configuration details for enabling logging in your environment. For help in using logs to track and manage your system's performance effectively, see the [logging documentation](logging.md).
## Related topics
- [Troubleshooting](troubleshooting.md)
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Host your own AI gateway and language models.
title: GitLab Duo Self-Hosted
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
To maintain full control over your data privacy, security, and the deployment of large language models (LLMs) in your own infrastructure, use GitLab Duo Self-Hosted.
By deploying GitLab Duo Self-Hosted, you can manage the entire lifecycle of requests made to LLM backends for GitLab Duo features, ensuring that all requests stay in your enterprise network, and avoiding external dependencies.
For a click-through demo, see [GitLab Duo Self-Hosted product tour](https://gitlab.navattic.com/gitlab-duo-self-hosted).
<!-- Demo published on 2025-02-13 -->
<i class="fa-youtube-play" aria-hidden="true"></i>
For an overview, see [GitLab Duo Self-Hosted: AI in your private environment](https://youtu.be/TQoO3sFnb28?si=uD-ps6aRnE28xNv3).
<!-- Video published on 2025-02-20 -->
## Why use GitLab Duo Self-Hosted
With GitLab Duo Self-Hosted, you can:
- Choose any GitLab-supported LLM.
- Retain full control over data by keeping all request/response logs in your domain, ensuring complete privacy and security with no external API calls.
- Isolate the GitLab instance, AI gateway, and models in your own environment.
- Select specific GitLab Duo features tailored to your users.
- Eliminate reliance on the shared GitLab AI gateway.
This setup ensures enterprise-level privacy and flexibility, allowing seamless integration of your LLMs with GitLab Duo features.
### Supported GitLab Duo features
The following tables state:
- The GitLab Duo features and whether those features are available on GitLab Duo Self-Hosted.
- Which version of GitLab is needed to use those features on GitLab Duo Self-Hosted.
- The status of those features. A feature's status on GitLab Duo Self-Hosted can be
different to [that same feature's status when it is hosted on GitLab](../../user/gitlab_duo/feature_summary.md).
{{< alert type="note" >}}
To use these features with GitLab Duo Self-Hosted, you must have the Duo Enterprise add-on. This applies regardless
of whether you can use these features with Duo Core or Duo Pro when
[GitLab hosts the models and connects to those models through the cloud-based AI gateway](../../user/gitlab_duo/gateway.md).
{{< /alert >}}
#### Code Suggestions
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| ---------------------------------------------------------------------------- | ------------------------------------------- | --------------------- | --- |
| [Code Suggestions](../../user/project/repository/code_suggestions/_index.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
#### Chat
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [General](../../user/gitlab_duo_chat/_index.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Code Explanation](../../user/gitlab_duo_chat/examples.md#explain-selected-code) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Test Generation](../../user/gitlab_duo_chat/examples.md#write-tests-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Refactor Code](../../user/gitlab_duo_chat/examples.md#refactor-code-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Fix Code](../../user/gitlab_duo_chat/examples.md#fix-code-in-the-ide) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Generally available |
| [Root Cause Analysis](../../user/gitlab_duo_chat/examples.md#troubleshoot-failed-cicd-jobs-with-root-cause-analysis) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.10 and later | Beta |
| [Vulnerability Explanation](../../user/application_security/vulnerabilities/_index.md#vulnerability-explanation) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
For more examples of a question you can ask, see
[Ask about GitLab](../../user/gitlab_duo_chat/examples.md).
#### GitLab Duo in merge requests
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [Merge Commit Message Generation](../../user/project/merge_requests/duo_in_merge_requests.md#generate-a-merge-commit-message) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [Merge Request Summary](../../user/project/merge_requests/duo_in_merge_requests.md#generate-a-description-by-summarizing-code-changes) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [Code Review](../../user/project/merge_requests/duo_in_merge_requests.md#have-gitlab-duo-review-your-code) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.3 and later | Beta |
| [Code Review Summary](../../user/project/merge_requests/duo_in_merge_requests.md#summarize-a-code-review) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Experiment |
#### GitLab Duo in issues
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [Issue Description Generation](../../user/project/issues/managing_issues.md#populate-an-issue-with-issue-description-generation) | {{< icon name="dash-circle" >}} No | Not applicable | Not applicable |
| [Discussion Summary](../../user/discussions/_index.md#summarize-issue-discussions-with-duo-chat) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
#### Other features
| Feature | Available on GitLab Duo Self-Hosted | GitLab version | Status |
| -------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ---------------------- | --- |
| [GitLab Duo for the CLI](../../editor_extensions/gitlab_cli/_index.md#gitlab-duo-for-the-cli) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [GitLab Duo Agent Platform](../../user/duo_agent_platform/_index.md) | {{< icon name="dash-circle" >}} No | Not applicable | Not applicable |
| [Vulnerability Resolution](../../user/application_security/vulnerabilities/_index.md#vulnerability-resolution) | {{< icon name="check-circle-filled" >}} Yes | GitLab 18.1.2 and later | Beta |
| [AI Impact Dashboard](../../user/analytics/ai_impact_analytics.md) | {{< icon name="check-circle-filled" >}} Yes | GitLab 17.9 and later | Beta |
### Prerequisites
Before setting up the GitLab Duo Self-Hosted infrastructure, you must have:
- A [supported model](supported_models_and_hardware_requirements.md) (either cloud-based or on-premises).
- A [supported serving platform](supported_llm_serving_platforms.md) (either cloud-based or on-premises).
- A [locally hosted AI gateway](../../install/install_ai_gateway.md).
- [Premium or Ultimate with GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?toggle=gitlab-duo-pro).
- GitLab 17.9 or later.
## Decide on your configuration type
GitLab Self-Managed customers can implement AI-native features using either of the following options:
- [**Self-hosted AI gateway and LLMs**](#self-hosted-ai-gateway-and-llms): Full control over your AI infrastructure.
- [**GitLab.com AI gateway with default GitLab external vendor LLMs**](#gitlabcom-ai-gateway-with-default-gitlab-external-vendor-llms): Use GitLab managed AI infrastructure.
The differences between these options are:
| Feature | Self-hosted AI gateway | GitLab.com AI gateway |
| --------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------- |
| Infrastructure requirements | Requires hosting your own AI gateway and models | No additional infrastructure needed |
| Model options | Choose from [supported models](supported_models_and_hardware_requirements.md) | Uses the default GitLab external vendor LLMs |
| Network requirements | Can operate in fully isolated networks | Requires internet connectivity |
| Responsibilities | You set up your infrastructure, and do your own maintenance | GitLab does the set up and maintenance |
### Self-hosted AI gateway and LLMs
In a fully self-hosted configuration, you deploy your own AI gateway and use any [supported LLMs](supported_models_and_hardware_requirements.md) in your infrastructure, without relying on external public services. This gives you full control over your data and security.
While this configuration is fully self-hosted and you can use models like Mistral that are hosted on your own infrastructure, you can still use cloud-based LLM services like [AWS Bedrock](https://aws.amazon.com/bedrock/) or [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) as your model backend.
If you have an offline environment with physical barriers or security policies that prevent or limit internet access, and comprehensive LLM controls, you can use GitLab Duo Self-Hosted.
For licensing, you must have a GitLab Premium or Ultimate subscription, and [GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?type=free-trial). Offline Enterprise licenses are available for those customers with fully isolated offline environments. To get access to your purchased subscription, request a license through the [Customers Portal](../../subscriptions/customers_portal.md).
For more information, see:
- [Set up a GitLab Duo Self-Hosted infrastructure](#set-up-a-gitlab-duo-self-hosted-infrastructure)
- The [self-hosted AI gateway configuration diagram](configuration_types.md#self-hosted-ai-gateway).
### GitLab.com AI gateway with default GitLab external vendor LLMs
If you do not meet the use case criteria for GitLab Duo Self-Hosted, you can use the
GitLab.com AI gateway with default GitLab external vendor LLMs.
The GitLab.com AI gateway is the default Enterprise offering and is not self-hosted. In this configuration,
you connect your instance to the GitLab-hosted AI gateway, which
integrates with external vendor LLM providers, including:
- [Anthropic](https://www.anthropic.com/)
- [Fireworks AI](https://fireworks.ai/)
- [Google Vertex](https://cloud.google.com/vertex-ai/)
These LLMs communicate through the GitLab Cloud Connector,
offering a ready-to-use AI solution without the need for on-premise infrastructure.
For licensing, you must have a GitLab Premium or Ultimate subscription, and [GitLab Duo Enterprise](https://about.gitlab.com/solutions/gitlab-duo-pro/sales/?type=free-trial). To get access to your purchased subscription, request a license through the [Customers Portal](../../subscriptions/customers_portal.md)
For more information, see the
[GitLab.com AI gateway configuration diagram](configuration_types.md#gitlabcom-ai-gateway).
To set up this infrastructure, see [how to configure GitLab Duo on a GitLab Self-Managed instance](../../user/gitlab_duo/setup.md).
## Set up a GitLab Duo Self-Hosted infrastructure
To set up a fully isolated GitLab Duo Self-Hosted infrastructure:
1. **Install a Large Language Model (LLM) Serving Infrastructure**
- We support various platforms for serving and hosting your LLMs, such as vLLM, AWS Bedrock, and Azure OpenAI. To help you choose the most suitable option for effectively deploying your models, see the [supported LLM platforms documentation](supported_llm_serving_platforms.md) for more information on each platform's features.
- We provide a comprehensive matrix of supported models along with their specific features and hardware requirements. To help select models that best align with your infrastructure needs for optimal performance, see the [supported models and hardware requirements documentation](supported_models_and_hardware_requirements.md).
1. **Install the GitLab AI gateway**
[Install the AI gateway](../../install/install_ai_gateway.md) to efficiently configure your AI infrastructure.
1. **Configure GitLab Duo features**
See the [Configure GitLab Duo features documentation](configure_duo_features.md) for instructions on how to customize your environment to effectively meet your operational needs.
1. **Enable logging**
You can find configuration details for enabling logging in your environment. For help in using logs to track and manage your system's performance effectively, see the [logging documentation](logging.md).
## Related topics
- [Troubleshooting](troubleshooting.md)
|
https://docs.gitlab.com/administration/logging
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/logging.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
logging.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Enable logging for self-hosted models
|
Enable logging for self-hosted models.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Ability to turn logging on and off through the UI added in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
Monitor your self-hosted model performance and debug issues more effectively with detailed
logging for GitLab Duo Self-Hosted.
## Enable logging
Prerequisites:
- You must be an administrator.
- You must have a Premium or Ultimate subscription.
- You must have a GitLab Duo Enterprise add-on.
To enable logging:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. In the GitLab Duo section, select **Change configuration**.
1. Under **Enable AI logs**, select **Capture detailed information about AI-related activities and requests**.
1. Select **Save changes**.
You can now access the logs in your GitLab installation.
## Logs in your GitLab installation
The logging setup is designed to protect sensitive information while maintaining transparency about system operations, and is made up of the following components:
- Logs that capture requests to the GitLab instance.
- Logging control.
- The `llm.log` file.
### Logs that capture requests to the GitLab instance
Logging in the `application.json`, `production_json.log`, and `production.log` files, among others, capture requests to the GitLab instance:
- **Filtered Requests**: We log the requests in these files but ensure that sensitive data (such as input parameters) is **filtered**. This means that while the request metadata is captured (for example, the request type, endpoint, and response status), the actual input data (for example, the query parameters, variables, and content) is not logged to prevent the exposure of sensitive information.
- **Example 1**: In the case of a code suggestions completion request, the logs capture the request details while filtering sensitive information:
```json
{
"method": "POST",
"path": "/api/graphql",
"controller": "GraphqlController",
"action": "execute",
"status": 500,
"params": [
{"key": "query", "value": "[FILTERED]"},
{"key": "variables", "value": "[FILTERED]"},
{"key": "operationName", "value": "chat"}
],
"exception": {
"class": "NoMethodError",
"message": "undefined method `id` for {:skip=>true}:Hash"
},
"time": "2024-08-28T14:13:50.328Z"
}
```
As shown, while the error information and general structure of the request are logged, the sensitive input parameters are marked as `[FILTERED]`.
- **Example 2**: In the case of a code suggestions completion request, the logs also capture the request details while filtering sensitive information:
```json
{
"method": "POST",
"path": "/api/v4/code_suggestions/completions",
"status": 200,
"params": [
{"key": "prompt_version", "value": 1},
{"key": "current_file", "value": {"file_name": "/test.rb", "language_identifier": "ruby", "content_above_cursor": "[FILTERED]", "content_below_cursor": "[FILTERED]"}},
{"key": "telemetry", "value": []}
],
"time": "2024-10-15T06:51:09.004Z"
}
```
As shown, while the general structure of the request is logged, the sensitive input parameters such as `content_above_cursor` and `content_below_cursor` are marked as `[FILTERED]`.
### Logging Control
You control a subset of these logs by turning [AI Logs](#enable-logging) on and off through the Duo settings page. Turning AI logs off disables logging for specific operations.
### The `llm.log` file
When [AI Logs](#enable-logging) are enabled, code generation and Chat events that occur through your GitLab Self-Managed instance are captured in the [`llm.log` file](../logs/_index.md#llmlog). The log file does not capture anything when it is not enabled. Code completion logs are captured directly in the AI gateway. These logs are not transmitted to GitLab, and are only visible on your GitLab Self-Managed infrastructure.
- [Rotate, manage, export, and visualize the logs in `llm.log`](../logs/_index.md).
- [View the log file location (for example, so you can delete logs)](../logs/_index.md#llm-input-and-output-logging).
### Logs in your AI gateway container
To specify the location of logs generated by AI gateway, run:
```shell
docker run -e AIGW_GITLAB_URL=<your_gitlab_instance> \
-e AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/ \
-e AIGW_LOGGING__TO_FILE="aigateway.log" \
-v <your_file_path>:"aigateway.log"
<image>
```
If you do not specify a filename, logs are streamed to the output and can also be managed using Docker logs.
For more information, see the [Docker Logs documentation](https://docs.docker.com/reference/cli/docker/container/logs/).
Additionally, the outputs of the AI gateway execution can help with debugging issues. To access them:
- When using Docker:
```shell
docker logs <container-id>
```
- When using Kubernetes:
```shell
kubectl logs <container-name>
```
To ingest these logs into the logging solution, see your logging provider documentation.
### Logs structure
When a POST request is made (for example, to the `/chat/completions` endpoint), the server logs the request:
- Payload
- Headers
- Metadata
#### 1. Request payload
The JSON payload typically includes the following fields:
- `messages`: An array of message objects.
- Each message object contains:
- `content`: A string representing the user's input or query.
- `role`: Indicates the role of the message sender (for example, `user`).
- `model`: A string specifying the model to be used (for example, `mistral`).
- `max_tokens`: An integer specifying the maximum number of tokens to generate in the response.
- `n`: An integer indicating the number of completions to generate.
- `stop`: An array of strings denoting stop sequences for the generated text.
- `stream`: A boolean indicating whether the response should be streamed.
- `temperature`: A float controlling the randomness of the output.
##### Example request
```json
{
"messages": [
{
"content": "<s>[SUFFIX]None[PREFIX]# # build a hello world ruby method\n def say_goodbye\n puts \"Goodbye, World!\"\n end\n\ndef main\n say_hello\n say_goodbye\nend\n\nmain",
"role": "user"
}
],
"model": "mistral",
"max_tokens": 128,
"n": 1,
"stop": ["[INST]", "[/INST]", "[PREFIX]", "[MIDDLE]", "[SUFFIX]"],
"stream": false,
"temperature": 0.0
}
```
#### 2. Request headers
The request headers provide additional context about the client making the request. Key headers might include:
- `Authorization`: Contains the Bearer token for API access.
- `Content-Type`: Indicates the media type of the resource (for example, `JSON`).
- `User-Agent`: Information about the client software making the request.
- `X-Stainless-` headers: Various headers providing additional metadata about the client environment.
##### Example request headers
```json
{
"host": "0.0.0.0:4000",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"accept": "application/json",
"content-type": "application/json",
"user-agent": "AsyncOpenAI/Python 1.51.0",
"authorization": "Bearer <TOKEN>",
"content-length": "364"
}
```
#### 3. Request metadata
The metadata includes various fields that describe the context of the request:
- `requester_metadata`: Additional metadata about the requester.
- `user_api_key`: The API key used for the request (anonymized).
- `api_version`: The version of the API being used.
- `request_timeout`: The timeout duration for the request.
- `call_id`: A unique identifier for the call.
##### Example metadata
```json
{
"user_api_key": "<ANONYMIZED_KEY>",
"api_version": "1.48.18",
"request_timeout": 600,
"call_id": "e1aaa316-221c-498c-96ce-5bc1e7cb63af"
}
```
### Example response
The server responds with a structured model response. For example:
```python
Response: ModelResponse(
id='chatcmpl-5d16ad41-c130-4e33-a71e-1c392741bcb9',
choices=[
Choices(
finish_reason='stop',
index=0,
message=Message(
content=' Here is the corrected Ruby code for your function:\n\n```ruby\ndef say_hello\n puts "Hello, World!"\nend\n\ndef say_goodbye\n puts "Goodbye, World!"\nend\n\ndef main\n say_hello\n say_goodbye\nend\n\nmain\n```\n\nIn your original code, the method names were misspelled as `say_hell` and `say_gobdye`. I corrected them to `say_hello` and `say_goodbye`. Also, there was no need for the prefix',
role='assistant',
tool_calls=None,
function_call=None
)
)
],
created=1728983827,
model='mistral',
object='chat.completion',
system_fingerprint=None,
usage=Usage(
completion_tokens=128,
prompt_tokens=69,
total_tokens=197,
completion_tokens_details=None,
prompt_tokens_details=None
)
)
```
### Logs in your inference service provider
GitLab does not manage logs generated by your inference service provider. See the documentation of your inference service
provider on how to use their logs.
## Logging behavior in GitLab and AI gateway environments
GitLab provides logging functionality for AI-related activities through the use of `llm.log`, which captures inputs, outputs, and other relevant information. However, the logging behavior differs depending on whether the GitLab instance and AI gateway are **self-hosted** or **cloud-connected**.
By default, the log does not contain LLM prompt input and response output to support [data retention policies](../../user/gitlab_duo/data_usage.md#data-retention) of AI feature data.
## Logging Scenarios
### GitLab Self-Managed and self-hosted AI gateway
In this configuration, both GitLab and the AI gateway are hosted by the customer.
- **Logging Behavior**: Full logging is enabled, and all prompts, inputs, and outputs are logged to `llm.log` on the instance.
- When [AI logs](#enable-logging) are enabled, extra debugging information is logged, including:
- Preprocessed prompts.
- Final prompts.
- Additional context.
- **Privacy**: Because both GitLab and the AI gateway are self-hosted:
- The customer has full control over data handling.
- Logging of sensitive information can be enabled or disabled at the customer's discretion.
{{< alert type="note" >}}
When an AI feature uses a GitLab AI third-party vendor model, no detailed logs are generated in the GitLab-hosted AI gateway, even when [AI logs are enabled](#enable-logging). This prevents unintended leaks of sensitive information.
{{< /alert >}}
### GitLab Self-Managed and GitLab-managed AI gateway (cloud-connected)
In this scenario, the customer hosts GitLab but relies on the GitLab-managed AI gateway for AI processing.
- **Logging Behavior**: Prompts and inputs sent to the AI gateway are **not logged** in the cloud-connected AI gateway to prevent exposure of sensitive information such as personally identifiable information (PII).
- **Expanded Logging**: Even if [AI logs are enabled](#enable-logging), no detailed logs are generated in the GitLab-managed AI gateway to avoid unintended leaks of sensitive information.
- Logging remains **minimal** in this setup, and the expanded logging features are disabled by default.
- **Privacy**: This configuration is designed to ensure that sensitive data is not logged in a cloud environment.
## AI logs
The [AI logs](#enable-logging) control whether additional debugging information, including prompts and inputs, is logged. This configuration is essential for monitoring and debugging AI-related activities.
### Behavior by Deployment Setup
- **GitLab Self-Managed and self-hosted AI gateway**:
- The setting enables detailed logging to `llm.log` on both the self-hosted instance and the AI gateway, capturing inputs and outputs for AI models.
- Logging remains disabled for the cloud-connected AI gateway to protect sensitive data, even when a feature uses a GitLab third-party vendor model.
- **GitLab Self-Managed and GitLab-managed AI gateway**:
- The setting enables detailed logging to `llm.log` on your GitLab Self-Managed instance.
- The setting does **not** activate expanded logging for the GitLab-managed AI gateway. Logging remains disabled for the cloud-connected AI gateway to protect sensitive data.
### Logging in cloud-connected AI gateways
To prevent potential data leakage of sensitive information, expanded logging (including prompts and inputs) is intentionally disabled when using a cloud-connected AI gateway. Preventing the exposure of PII is a priority.
### Cross-referencing logs between the AI gateway and GitLab
The property `correlation_id` is assigned to every request and is carried across different components that respond to a
request. For more information, see the [documentation on finding logs with a correlation ID](../logs/tracing_correlation_id.md).
The Correlation ID can be found in your AI gateway and GitLab logs. However, it is not present in your model provider logs.
#### Related topics
- [Parsing GitLab logs with jq](../logs/log_parsing.md)
- [Searching your logs for the correlation ID](../logs/tracing_correlation_id.md#searching-your-logs-for-the-correlation-id)
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Enable logging for self-hosted models.
title: Enable logging for self-hosted models
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Ability to turn logging on and off through the UI added in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
Monitor your self-hosted model performance and debug issues more effectively with detailed
logging for GitLab Duo Self-Hosted.
## Enable logging
Prerequisites:
- You must be an administrator.
- You must have a Premium or Ultimate subscription.
- You must have a GitLab Duo Enterprise add-on.
To enable logging:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. In the GitLab Duo section, select **Change configuration**.
1. Under **Enable AI logs**, select **Capture detailed information about AI-related activities and requests**.
1. Select **Save changes**.
You can now access the logs in your GitLab installation.
## Logs in your GitLab installation
The logging setup is designed to protect sensitive information while maintaining transparency about system operations, and is made up of the following components:
- Logs that capture requests to the GitLab instance.
- Logging control.
- The `llm.log` file.
### Logs that capture requests to the GitLab instance
Logging in the `application.json`, `production_json.log`, and `production.log` files, among others, capture requests to the GitLab instance:
- **Filtered Requests**: We log the requests in these files but ensure that sensitive data (such as input parameters) is **filtered**. This means that while the request metadata is captured (for example, the request type, endpoint, and response status), the actual input data (for example, the query parameters, variables, and content) is not logged to prevent the exposure of sensitive information.
- **Example 1**: In the case of a code suggestions completion request, the logs capture the request details while filtering sensitive information:
```json
{
"method": "POST",
"path": "/api/graphql",
"controller": "GraphqlController",
"action": "execute",
"status": 500,
"params": [
{"key": "query", "value": "[FILTERED]"},
{"key": "variables", "value": "[FILTERED]"},
{"key": "operationName", "value": "chat"}
],
"exception": {
"class": "NoMethodError",
"message": "undefined method `id` for {:skip=>true}:Hash"
},
"time": "2024-08-28T14:13:50.328Z"
}
```
As shown, while the error information and general structure of the request are logged, the sensitive input parameters are marked as `[FILTERED]`.
- **Example 2**: In the case of a code suggestions completion request, the logs also capture the request details while filtering sensitive information:
```json
{
"method": "POST",
"path": "/api/v4/code_suggestions/completions",
"status": 200,
"params": [
{"key": "prompt_version", "value": 1},
{"key": "current_file", "value": {"file_name": "/test.rb", "language_identifier": "ruby", "content_above_cursor": "[FILTERED]", "content_below_cursor": "[FILTERED]"}},
{"key": "telemetry", "value": []}
],
"time": "2024-10-15T06:51:09.004Z"
}
```
As shown, while the general structure of the request is logged, the sensitive input parameters such as `content_above_cursor` and `content_below_cursor` are marked as `[FILTERED]`.
### Logging Control
You control a subset of these logs by turning [AI Logs](#enable-logging) on and off through the Duo settings page. Turning AI logs off disables logging for specific operations.
### The `llm.log` file
When [AI Logs](#enable-logging) are enabled, code generation and Chat events that occur through your GitLab Self-Managed instance are captured in the [`llm.log` file](../logs/_index.md#llmlog). The log file does not capture anything when it is not enabled. Code completion logs are captured directly in the AI gateway. These logs are not transmitted to GitLab, and are only visible on your GitLab Self-Managed infrastructure.
- [Rotate, manage, export, and visualize the logs in `llm.log`](../logs/_index.md).
- [View the log file location (for example, so you can delete logs)](../logs/_index.md#llm-input-and-output-logging).
### Logs in your AI gateway container
To specify the location of logs generated by AI gateway, run:
```shell
docker run -e AIGW_GITLAB_URL=<your_gitlab_instance> \
-e AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/ \
-e AIGW_LOGGING__TO_FILE="aigateway.log" \
-v <your_file_path>:"aigateway.log"
<image>
```
If you do not specify a filename, logs are streamed to the output and can also be managed using Docker logs.
For more information, see the [Docker Logs documentation](https://docs.docker.com/reference/cli/docker/container/logs/).
Additionally, the outputs of the AI gateway execution can help with debugging issues. To access them:
- When using Docker:
```shell
docker logs <container-id>
```
- When using Kubernetes:
```shell
kubectl logs <container-name>
```
To ingest these logs into the logging solution, see your logging provider documentation.
### Logs structure
When a POST request is made (for example, to the `/chat/completions` endpoint), the server logs the request:
- Payload
- Headers
- Metadata
#### 1. Request payload
The JSON payload typically includes the following fields:
- `messages`: An array of message objects.
- Each message object contains:
- `content`: A string representing the user's input or query.
- `role`: Indicates the role of the message sender (for example, `user`).
- `model`: A string specifying the model to be used (for example, `mistral`).
- `max_tokens`: An integer specifying the maximum number of tokens to generate in the response.
- `n`: An integer indicating the number of completions to generate.
- `stop`: An array of strings denoting stop sequences for the generated text.
- `stream`: A boolean indicating whether the response should be streamed.
- `temperature`: A float controlling the randomness of the output.
##### Example request
```json
{
"messages": [
{
"content": "<s>[SUFFIX]None[PREFIX]# # build a hello world ruby method\n def say_goodbye\n puts \"Goodbye, World!\"\n end\n\ndef main\n say_hello\n say_goodbye\nend\n\nmain",
"role": "user"
}
],
"model": "mistral",
"max_tokens": 128,
"n": 1,
"stop": ["[INST]", "[/INST]", "[PREFIX]", "[MIDDLE]", "[SUFFIX]"],
"stream": false,
"temperature": 0.0
}
```
#### 2. Request headers
The request headers provide additional context about the client making the request. Key headers might include:
- `Authorization`: Contains the Bearer token for API access.
- `Content-Type`: Indicates the media type of the resource (for example, `JSON`).
- `User-Agent`: Information about the client software making the request.
- `X-Stainless-` headers: Various headers providing additional metadata about the client environment.
##### Example request headers
```json
{
"host": "0.0.0.0:4000",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"accept": "application/json",
"content-type": "application/json",
"user-agent": "AsyncOpenAI/Python 1.51.0",
"authorization": "Bearer <TOKEN>",
"content-length": "364"
}
```
#### 3. Request metadata
The metadata includes various fields that describe the context of the request:
- `requester_metadata`: Additional metadata about the requester.
- `user_api_key`: The API key used for the request (anonymized).
- `api_version`: The version of the API being used.
- `request_timeout`: The timeout duration for the request.
- `call_id`: A unique identifier for the call.
##### Example metadata
```json
{
"user_api_key": "<ANONYMIZED_KEY>",
"api_version": "1.48.18",
"request_timeout": 600,
"call_id": "e1aaa316-221c-498c-96ce-5bc1e7cb63af"
}
```
### Example response
The server responds with a structured model response. For example:
```python
Response: ModelResponse(
id='chatcmpl-5d16ad41-c130-4e33-a71e-1c392741bcb9',
choices=[
Choices(
finish_reason='stop',
index=0,
message=Message(
content=' Here is the corrected Ruby code for your function:\n\n```ruby\ndef say_hello\n puts "Hello, World!"\nend\n\ndef say_goodbye\n puts "Goodbye, World!"\nend\n\ndef main\n say_hello\n say_goodbye\nend\n\nmain\n```\n\nIn your original code, the method names were misspelled as `say_hell` and `say_gobdye`. I corrected them to `say_hello` and `say_goodbye`. Also, there was no need for the prefix',
role='assistant',
tool_calls=None,
function_call=None
)
)
],
created=1728983827,
model='mistral',
object='chat.completion',
system_fingerprint=None,
usage=Usage(
completion_tokens=128,
prompt_tokens=69,
total_tokens=197,
completion_tokens_details=None,
prompt_tokens_details=None
)
)
```
### Logs in your inference service provider
GitLab does not manage logs generated by your inference service provider. See the documentation of your inference service
provider on how to use their logs.
## Logging behavior in GitLab and AI gateway environments
GitLab provides logging functionality for AI-related activities through the use of `llm.log`, which captures inputs, outputs, and other relevant information. However, the logging behavior differs depending on whether the GitLab instance and AI gateway are **self-hosted** or **cloud-connected**.
By default, the log does not contain LLM prompt input and response output to support [data retention policies](../../user/gitlab_duo/data_usage.md#data-retention) of AI feature data.
## Logging Scenarios
### GitLab Self-Managed and self-hosted AI gateway
In this configuration, both GitLab and the AI gateway are hosted by the customer.
- **Logging Behavior**: Full logging is enabled, and all prompts, inputs, and outputs are logged to `llm.log` on the instance.
- When [AI logs](#enable-logging) are enabled, extra debugging information is logged, including:
- Preprocessed prompts.
- Final prompts.
- Additional context.
- **Privacy**: Because both GitLab and the AI gateway are self-hosted:
- The customer has full control over data handling.
- Logging of sensitive information can be enabled or disabled at the customer's discretion.
{{< alert type="note" >}}
When an AI feature uses a GitLab AI third-party vendor model, no detailed logs are generated in the GitLab-hosted AI gateway, even when [AI logs are enabled](#enable-logging). This prevents unintended leaks of sensitive information.
{{< /alert >}}
### GitLab Self-Managed and GitLab-managed AI gateway (cloud-connected)
In this scenario, the customer hosts GitLab but relies on the GitLab-managed AI gateway for AI processing.
- **Logging Behavior**: Prompts and inputs sent to the AI gateway are **not logged** in the cloud-connected AI gateway to prevent exposure of sensitive information such as personally identifiable information (PII).
- **Expanded Logging**: Even if [AI logs are enabled](#enable-logging), no detailed logs are generated in the GitLab-managed AI gateway to avoid unintended leaks of sensitive information.
- Logging remains **minimal** in this setup, and the expanded logging features are disabled by default.
- **Privacy**: This configuration is designed to ensure that sensitive data is not logged in a cloud environment.
## AI logs
The [AI logs](#enable-logging) control whether additional debugging information, including prompts and inputs, is logged. This configuration is essential for monitoring and debugging AI-related activities.
### Behavior by Deployment Setup
- **GitLab Self-Managed and self-hosted AI gateway**:
- The setting enables detailed logging to `llm.log` on both the self-hosted instance and the AI gateway, capturing inputs and outputs for AI models.
- Logging remains disabled for the cloud-connected AI gateway to protect sensitive data, even when a feature uses a GitLab third-party vendor model.
- **GitLab Self-Managed and GitLab-managed AI gateway**:
- The setting enables detailed logging to `llm.log` on your GitLab Self-Managed instance.
- The setting does **not** activate expanded logging for the GitLab-managed AI gateway. Logging remains disabled for the cloud-connected AI gateway to protect sensitive data.
### Logging in cloud-connected AI gateways
To prevent potential data leakage of sensitive information, expanded logging (including prompts and inputs) is intentionally disabled when using a cloud-connected AI gateway. Preventing the exposure of PII is a priority.
### Cross-referencing logs between the AI gateway and GitLab
The property `correlation_id` is assigned to every request and is carried across different components that respond to a
request. For more information, see the [documentation on finding logs with a correlation ID](../logs/tracing_correlation_id.md).
The Correlation ID can be found in your AI gateway and GitLab logs. However, it is not present in your model provider logs.
#### Related topics
- [Parsing GitLab logs with jq](../logs/log_parsing.md)
- [Searching your logs for the correlation ID](../logs/tracing_correlation_id.md#searching-your-logs-for-the-correlation-id)
|
https://docs.gitlab.com/administration/configure_duo_features
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/configure_duo_features.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
configure_duo_features.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configure GitLab to access GitLab Duo Self-Hosted
|
Configure your GitLab instance to use GitLab Duo Self-Hosted.
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8
- Ability to set AI gateway URL using UI [added](https://gitlab.com/gitlab-org/gitlab/-/issues/473143) in GitLab 17.9.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
Prerequisites:
- [Upgrade GitLab to version 17.9 or later](../../update/_index.md).
To configure your GitLab instance to access the available self-hosted models in your infrastructure:
1. [Confirm that a fully self-hosted configuration is appropriate for your use case](_index.md#decide-on-your-configuration-type).
1. Configure your GitLab instance to access the AI gateway.
1. Configure the self-hosted model.
1. Configure the GitLab Duo features to use your self-hosted model.
## Configure your GitLab instance to access the AI gateway
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Change configuration**.
1. Under **Local AI Gateway URL**, enter your AI Gateway URL.
1. Select **Save changes**.
{{< alert type="note" >}}
If your AI gateway URL points to a local network or private IP address (for example, `172.31.x.x` or internal hostnames like `ip-172-xx-xx-xx.region.compute.internal`), GitLab might block the request for security reasons. To allow requests to this address, [add the address to the IP allowlist](../../security/webhooks.md#allow-outbound-requests-to-certain-ip-addresses-and-domains).
{{< /alert >}}
## Configure the self-hosted model
Prerequisites:
- You must be an administrator.
- You must have a Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
To configure a self-hosted model:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
- If the **Configure GitLab Duo Self-Hosted** button is not available, synchronize your
subscription after purchase:
1. On the left sidebar, select **Subscription**.
1. In **Subscription details**, to the right of **Last sync**, select
synchronize subscription ({{< icon name="retry" >}}).
1. Select **Add self-hosted model**.
1. Complete the fields:
- **Deployment name**: Enter a name to uniquely identify the model deployment, for example, `Mixtral-8x7B-it-v0.1 on GCP`.
- **Model family**: Select the model family the deployment belongs to. Only GitLab-supported models
are in this list.
- **Endpoint**: Enter the URL where the model is hosted.
- For more information about configuring the endpoint for models deployed through vLLM, see the [vLLM documentation](supported_llm_serving_platforms.md#endpoint-configuration).
- **API key**: Optional. Add an API key if you need one to access the model.
- **Model identifier**: This is a required field. The value of this field is based on your deployment method, and should match the following structure:
| Deployment method | Format | Example |
|-------------|---------|---------|
| vLLM | `custom_openai/<name of the model served through vLLM>` | `custom_openai/Mixtral-8x7B-Instruct-v0.1` |
| Bedrock | `bedrock/<model ID of the model>` | `bedrock/mistral.mixtral-8x7b-instruct-v0:1` |
| Azure OpenAI | `azure/<model ID of the model>` | `azure/gpt-35-turbo` |
- For Amazon Bedrock models:
1. Set your `AWS_REGION` and make sure you have access to models in that region in your AI gateway Docker configuration.
1. Add the appropriate region prefix to the model's inference profile ID
for cross-region inferencing.
1. Enter the region prefix and model inference profile ID in the **Model identifier**
field, with the `bedrock/` prefix.
For example, for the Anthropic Claude 3.5 v2 model in the Tokyo region:
- The `AWS_REGION` is `ap-northeast-1`.
- The cross-region inferencing prefix is `apac.`.
- The model identifier is `bedrock/apac.anthropic.claude-3-5-sonnet-20241022-v2:0`
1. Select **Create self-hosted model**.
For more information about:
- Configuring the model identifier for models deployed through vLLM, see the [vLLM documentation](supported_llm_serving_platforms.md#find-the-model-name).
- Configuring Amazon Bedrock models with cross-region inferencing, see the
[Amazon supported regions and models for inference profiles documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)
## Configure self-hosted beta models and features
Prerequisites:
- You must be an administrator.
- You must have an Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
To enable self-hosted [beta](../../policy/development_stages_support.md#beta) models and features:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Change configuration**.
1. Under **Self-hosted beta models and features**, select the **Use beta models and features in GitLab Duo Self-Hosted** checkbox.
1. Select **Save changes**.
{{< alert type="note" >}}
Turning on beta self-hosted models and features also accepts the [GitLab Testing Agreement](https://handbook.gitlab.com/handbook/legal/testing-agreement/).
{{< /alert >}}
For more information, see the [list of available beta models](supported_models_and_hardware_requirements.md#experimental-and-beta-models) under evaluation.
## Configure GitLab Duo features to use self-hosted models
Prerequisites:
- You must be an administrator.
- You must have an Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
### View configured features
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
- If the **Configure GitLab Duo Self-Hosted** button is not available, synchronize your
subscription after purchase:
1. On the left sidebar, select **Subscription**.
1. In **Subscription details**, to the right of **Last sync**, select
synchronize subscription ({{< icon name="retry" >}}).
1. Select the **AI-native features** tab.
### Configure the feature to use a self-hosted model
Configure the GitLab Duo feature and sub-feature to send queries to the configured self-hosted model:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
1. Select the **AI-native features** tab.
1. For the feature and sub-feature you want to configure, from the dropdown list, choose the self-hosted model you want to use.
For example, for the code generation sub-feature under GitLab Duo Code Suggestions, you can select **Claude-3 on Bedrock deployment (Claude 3)**.

#### GitLab Duo Chat sub-feature fall back configuration
When configuring GitLab Duo Chat sub-features, if you do not select a specific self-hosted model for a sub-feature, that sub-feature automatically falls back to using the self-hosted model configured for **General Chat**. This ensures all Chat functionality works even if you have not explicitly configured each sub-feature with its own self-hosted model.
### Self-host the GitLab documentation
If your setup of GitLab Duo Self-Hosted stops you from accessing the GitLab documentation at `docs.gitlab.com`, you can self-host the documentation instead. For more information, see how to [host the GitLab product documentation](../docs_self_host.md).
### Disable GitLab Duo features
To disable a feature, you must explicitly select **Disabled** when configuring a feature or sub-feature.
- Not choosing a model for a sub-feature is insufficient.
- For Chat sub-features, not selecting a model causes that sub-feature to [fall back to using the model configured for **General Chat**](#gitlab-duo-chat-sub-feature-fall-back-configuration).
To disable a GitLab Duo feature or sub-feature:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
1. Select the **AI-native features** tab.
1. For the feature or sub-feature you want to disable, from the dropdown list, select **Disabled**.
For example, to specifically disable the `Write Test` and `Refactor Code` features, select **Disabled**:

|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Configure your GitLab instance to use GitLab Duo Self-Hosted.
title: Configure GitLab to access GitLab Duo Self-Hosted
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8
- Ability to set AI gateway URL using UI [added](https://gitlab.com/gitlab-org/gitlab/-/issues/473143) in GitLab 17.9.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
Prerequisites:
- [Upgrade GitLab to version 17.9 or later](../../update/_index.md).
To configure your GitLab instance to access the available self-hosted models in your infrastructure:
1. [Confirm that a fully self-hosted configuration is appropriate for your use case](_index.md#decide-on-your-configuration-type).
1. Configure your GitLab instance to access the AI gateway.
1. Configure the self-hosted model.
1. Configure the GitLab Duo features to use your self-hosted model.
## Configure your GitLab instance to access the AI gateway
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Change configuration**.
1. Under **Local AI Gateway URL**, enter your AI Gateway URL.
1. Select **Save changes**.
{{< alert type="note" >}}
If your AI gateway URL points to a local network or private IP address (for example, `172.31.x.x` or internal hostnames like `ip-172-xx-xx-xx.region.compute.internal`), GitLab might block the request for security reasons. To allow requests to this address, [add the address to the IP allowlist](../../security/webhooks.md#allow-outbound-requests-to-certain-ip-addresses-and-domains).
{{< /alert >}}
## Configure the self-hosted model
Prerequisites:
- You must be an administrator.
- You must have a Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
To configure a self-hosted model:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
- If the **Configure GitLab Duo Self-Hosted** button is not available, synchronize your
subscription after purchase:
1. On the left sidebar, select **Subscription**.
1. In **Subscription details**, to the right of **Last sync**, select
synchronize subscription ({{< icon name="retry" >}}).
1. Select **Add self-hosted model**.
1. Complete the fields:
- **Deployment name**: Enter a name to uniquely identify the model deployment, for example, `Mixtral-8x7B-it-v0.1 on GCP`.
- **Model family**: Select the model family the deployment belongs to. Only GitLab-supported models
are in this list.
- **Endpoint**: Enter the URL where the model is hosted.
- For more information about configuring the endpoint for models deployed through vLLM, see the [vLLM documentation](supported_llm_serving_platforms.md#endpoint-configuration).
- **API key**: Optional. Add an API key if you need one to access the model.
- **Model identifier**: This is a required field. The value of this field is based on your deployment method, and should match the following structure:
| Deployment method | Format | Example |
|-------------|---------|---------|
| vLLM | `custom_openai/<name of the model served through vLLM>` | `custom_openai/Mixtral-8x7B-Instruct-v0.1` |
| Bedrock | `bedrock/<model ID of the model>` | `bedrock/mistral.mixtral-8x7b-instruct-v0:1` |
| Azure OpenAI | `azure/<model ID of the model>` | `azure/gpt-35-turbo` |
- For Amazon Bedrock models:
1. Set your `AWS_REGION` and make sure you have access to models in that region in your AI gateway Docker configuration.
1. Add the appropriate region prefix to the model's inference profile ID
for cross-region inferencing.
1. Enter the region prefix and model inference profile ID in the **Model identifier**
field, with the `bedrock/` prefix.
For example, for the Anthropic Claude 3.5 v2 model in the Tokyo region:
- The `AWS_REGION` is `ap-northeast-1`.
- The cross-region inferencing prefix is `apac.`.
- The model identifier is `bedrock/apac.anthropic.claude-3-5-sonnet-20241022-v2:0`
1. Select **Create self-hosted model**.
For more information about:
- Configuring the model identifier for models deployed through vLLM, see the [vLLM documentation](supported_llm_serving_platforms.md#find-the-model-name).
- Configuring Amazon Bedrock models with cross-region inferencing, see the
[Amazon supported regions and models for inference profiles documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)
## Configure self-hosted beta models and features
Prerequisites:
- You must be an administrator.
- You must have an Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
To enable self-hosted [beta](../../policy/development_stages_support.md#beta) models and features:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Change configuration**.
1. Under **Self-hosted beta models and features**, select the **Use beta models and features in GitLab Duo Self-Hosted** checkbox.
1. Select **Save changes**.
{{< alert type="note" >}}
Turning on beta self-hosted models and features also accepts the [GitLab Testing Agreement](https://handbook.gitlab.com/handbook/legal/testing-agreement/).
{{< /alert >}}
For more information, see the [list of available beta models](supported_models_and_hardware_requirements.md#experimental-and-beta-models) under evaluation.
## Configure GitLab Duo features to use self-hosted models
Prerequisites:
- You must be an administrator.
- You must have an Premium or Ultimate license.
- You must have a GitLab Duo Enterprise license add-on.
### View configured features
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
- If the **Configure GitLab Duo Self-Hosted** button is not available, synchronize your
subscription after purchase:
1. On the left sidebar, select **Subscription**.
1. In **Subscription details**, to the right of **Last sync**, select
synchronize subscription ({{< icon name="retry" >}}).
1. Select the **AI-native features** tab.
### Configure the feature to use a self-hosted model
Configure the GitLab Duo feature and sub-feature to send queries to the configured self-hosted model:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
1. Select the **AI-native features** tab.
1. For the feature and sub-feature you want to configure, from the dropdown list, choose the self-hosted model you want to use.
For example, for the code generation sub-feature under GitLab Duo Code Suggestions, you can select **Claude-3 on Bedrock deployment (Claude 3)**.

#### GitLab Duo Chat sub-feature fall back configuration
When configuring GitLab Duo Chat sub-features, if you do not select a specific self-hosted model for a sub-feature, that sub-feature automatically falls back to using the self-hosted model configured for **General Chat**. This ensures all Chat functionality works even if you have not explicitly configured each sub-feature with its own self-hosted model.
### Self-host the GitLab documentation
If your setup of GitLab Duo Self-Hosted stops you from accessing the GitLab documentation at `docs.gitlab.com`, you can self-host the documentation instead. For more information, see how to [host the GitLab product documentation](../docs_self_host.md).
### Disable GitLab Duo features
To disable a feature, you must explicitly select **Disabled** when configuring a feature or sub-feature.
- Not choosing a model for a sub-feature is insufficient.
- For Chat sub-features, not selecting a model causes that sub-feature to [fall back to using the model configured for **General Chat**](#gitlab-duo-chat-sub-feature-fall-back-configuration).
To disable a GitLab Duo feature or sub-feature:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **GitLab Duo**.
1. Select **Configure GitLab Duo Self-Hosted**.
1. Select the **AI-native features** tab.
1. For the feature or sub-feature you want to disable, from the dropdown list, select **Disabled**.
For example, to specifically disable the `Write Test` and `Refactor Code` features, select **Disabled**:

|
https://docs.gitlab.com/administration/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/troubleshooting.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
troubleshooting.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting GitLab Duo Self-Hosted
|
Troubleshooting tips for deploying GitLab Duo Self-Hosted
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
When working with GitLab Duo Self-Hosted, you might encounter issues.
Before you begin troubleshooting, you should:
- Be able to access the [`gitlab-rails` console](../operations/rails_console.md).
- Open a shell in the AI gateway Docker image.
- Know the endpoint where your:
- AI gateway is hosted.
- Model is hosted.
- [Enable logging](logging.md#enable-logging) to make sure that requests and responses from GitLab to the AI gateway are being logged to [`llm.log`](../logs/_index.md#llmlog).
For more information on troubleshooting GitLab Duo, see:
- [Troubleshooting GitLab Duo](../../user/gitlab_duo/troubleshooting.md).
- [Troubleshooting Code Suggestions](../../user/project/repository/code_suggestions/troubleshooting.md).
- [GitLab Duo Chat troubleshooting](../../user/gitlab_duo_chat/troubleshooting.md).
## Use debugging scripts
We provide two debugging scripts to help administrators verify their self-hosted model configuration.
1. Debug the GitLab to AI gateway connection. From your GitLab instance, run the
[Rake task](../../administration/raketasks/_index.md):
```shell
gitlab-rake "gitlab:duo:verify_self_hosted_setup[<username>]"
```
Optional: Include a `<username>` that has an assigned seat.
If you do not include a username parameter, the Rake task uses the root user.
1. Debug the AI gateway setup. For your AI gateway container:
- Restart the AI gateway container with authentication disabled by setting:
```shell
-e AIGW_AUTH__BYPASS_EXTERNAL=true
```
This setting is required for the troubleshooting command to run the **System Exchange test**. You must remove this setting after troubleshooting is complete.
- From your AI gateway container, run:
```shell
docker exec -it <ai-gateway-container> sh
poetry run troubleshoot [options]
```
The `troubleshoot` command supports the following options:
| Option | Default | Example | Description |
|----------------------|------------------|---------------------------------------------------------------|-------------|
| `--endpoint` | `localhost:5052` | `--endpoint=localhost:5052` | AI Gateway endpoint |
| `--model-family` | - | `--model-family=mistral` | Model family to test. Possible values are `mistral`, `mixtral`, `gpt`, or `claude_3` |
| `--model-endpoint` | - | `--model-endpoint=http://localhost:4000/v1` | Model endpoint. For models hosted on vLLM, add the `/v1` suffix. |
| `--model-identifier` | - | `--model-identifier=custom_openai/Mixtral-8x7B-Instruct-v0.1` | Model identifier. |
| `--api-key` | - | `--api-key=your-api-key` | Model API key. |
**Examples**:
For a `claude_3` model running on AWS Bedrock:
```shell
poetry run troubleshoot \
--model-family=claude_3 \
--model-identifier=bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0
```
For a `mixtral` model running on vLLM:
```shell
poetry run troubleshoot \
--model-family=mixtral \
--model-identifier=custom_openai/Mixtral-8x7B-Instruct-v0.1 \
--api-key=your-api-key \
--model-endpoint=http://<your-model-endpoint>/v1
```
After troubleshooting is complete, stop and restart the AI gateway container **without** `AIGW_AUTH__BYPASS_EXTERNAL=true`.
{{< alert type="warning" >}}
You must not bypass authentication in production.
{{< /alert >}}
Verify the output of the commands, and fix accordingly.
If both commands are successful, but GitLab Duo Code Suggestions is still not working,
raise an issue on the issue tracker.
## GitLab Duo health check is not working
When you [run a health check for GitLab Duo](../../administration/gitlab_duo/setup.md#run-a-health-check-for-gitlab-duo), you might get an error like a `401 response from the AI gateway`.
To resolve, first check if GitLab Duo features are functioning correctly. For example, send a message to Duo Chat.
If this does not work, the error might be because of a known issue with GitLab Duo health check. For more information, see [issue 517097](https://gitlab.com/gitlab-org/gitlab/-/issues/517097).
## Check if GitLab can make a request to the model
From the GitLab Rails console, verify that GitLab can make a request to the model
by running:
```ruby
model_name = "<your_model_name>"
model_endpoint = "<your_model_endpoint>"
model_api_key = "<your_model_api_key>"
body = {:prompt_components=>[{:type=>"prompt", :metadata=>{:source=>"GitLab EE", :version=>"17.3.0"}, :payload=>{:content=>[{:role=>:user, :content=>"Hello"}], :provider=>:litellm, :model=>model_name, :model_endpoint=>model_endpoint, :model_api_key=>model_api_key}}]}
ai_gateway_url = Ai::Setting.instance.ai_gateway_url # Verify that the AI gateway URL is set in the database
client = Gitlab::Llm::AiGateway::Client.new(User.find_by_id(1), service_name: :self_hosted_models)
client.complete(url: "#{ai_gateway_url}/v1/chat/agent", body: body)
```
This should return a response from the model in the format:
```ruby
{"response"=> "<Model response>",
"metadata"=>
{"provider"=>"litellm",
"model"=>"<>",
"timestamp"=>1723448920}}
```
If that is not the case, this might means one of the following:
- The user might not have access to Code Suggestions. To resolve,
[check if a user can request Code Suggestions](#check-if-a-user-can-request-code-suggestions).
- The GitLab environment variables are not configured correctly. To resolve, [check that the GitLab environment variables are set up correctly](#check-that-the-ai-gateway-environment-variables-are-set-up-correctly).
- The GitLab instance is not configured to use self-hosted models. To resolve, [check if the GitLab instance is configured to use self-hosted models](#check-if-gitlab-instance-is-configured-to-use-self-hosted-models).
- The AI gateway is not reachable. To resolve, [check if GitLab can make an HTTP request to the AI gateway](#check-if-gitlab-can-make-an-http-request-to-the-ai-gateway).
- When the LLM server is installed on the same instance as the AI gateway container, local requests may not work. To resolve, [allow local requests from the Docker container](#llm-server-is-not-available-inside-the-ai-gateway-container).
## Check if a user can request Code Suggestions
In the GitLab Rails console, check if a user can request Code Suggestions by running:
```ruby
User.find_by_id("<user_id>").can?(:access_code_suggestions)
```
If this returns `false`, it means some configuration is missing, and the user
cannot access Code Suggestions.
This missing configuration might be because of either of the following:
- The license is not valid. To resolve, [check or update your license](../license_file.md#see-current-license-information).
- GitLab Duo was not configured to use a self-hosted model. To resolve, [check if the GitLab instance is configured to use self-hosted models](#check-if-gitlab-instance-is-configured-to-use-self-hosted-models).
## Check if GitLab instance is configured to use self-hosted models
To check if GitLab Duo was configured correctly:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Self-hosted models**
1. Expand **AI-native features**.
1. Under **Features**, check that **Code Suggestions** and **Code generation** are set to **Self-hosted model**.
## Check that the AI gateway URL is set up correctly
To check that the AI gateway URL is correct, run the following on the GitLab Rails console:
```ruby
Ai::Setting.instance.ai_gateway_url == "<your-ai-gateway-instance-url>"
```
If the AI gateway is not set up, [configure your GitLab instance to access the AI gateway](configure_duo_features.md#configure-your-gitlab-instance-to-access-the-ai-gateway).
## Check if GitLab can make an HTTP request to the AI gateway
In the GitLab Rails console, verify that GitLab can make an HTTP request to AI
Gateway by running:
```ruby
HTTParty.get('<your-aigateway-endpoint>/monitoring/healthz', headers: { 'accept' => 'application/json' }).code
```
If the response is not `200`, this means either of the following:
- The network is not properly configured to allow GitLab to reach the AI gateway container. Contact your network administrator to verify the setup.
- The AI gateway is not able to process requests. To resolve this issue, [check if the AI gateway can make a request to the model](#check-if-the-ai-gateway-can-make-a-request-to-the-model).
## Check if the AI gateway can make a request to the model
From the AI gateway container, make an HTTP request to the AI gateway API for a
Code Suggestion. Replace:
- `<your_model_name>` with the name of the model you are using. For example `mistral` or `codegemma`.
- `<your_model_endpoint>` with the endpoint where the model is hosted.
```shell
docker exec -it <ai-gateway-container> sh
curl --request POST "http://localhost:5052/v1/chat/agent" \
--header 'accept: application/json' \
--header 'Content-Type: application/json' \
--data '{ "prompt_components": [ { "type": "string", "metadata": { "source": "string", "version": "string" }, "payload": { "content": "Hello", "provider": "litellm", "model": "<your_model_name>", "model_endpoint": "<your_model_endpoint>" } } ], "stream": false }'
```
If the request fails, the:
- AI gateway might not be configured properly to use self-hosted models. To resolve this,
[check that the AI gateway URL is set up correctly](#check-that-the-ai-gateway-url-is-set-up-correctly).
- AI gateway might not be able to access the model. To resolve,
[check if the model is reachable from the AI gateway](#check-if-the-model-is-reachable-from-ai-gateway).
- Model name or endpoint might be incorrect. Check the values, and correct them
if necessary.
## Check if AI gateway can process requests
```shell
docker exec -it <ai-gateway-container> sh
curl '<your-aigateway-endpoint>/monitoring/healthz'
```
If the response is not `200`, this means that AI gateway is not installed correctly. To resolve, follow the [documentation on how to install the AI gateway](../../install/install_ai_gateway.md).
## Check that the AI gateway environment variables are set up correctly
To check that the AI gateway environment variables are set up correctly, run the
following in a console on the AI gateway container:
```shell
docker exec -it <ai-gateway-container> sh
echo $AIGW_CUSTOM_MODELS__ENABLED # must be true
```
If the environment variables are not set up correctly, set them by
[creating a container](../../install/install_ai_gateway.md#find-the-ai-gateway-image).
## Check if the model is reachable from AI gateway
Create a shell on the AI gateway container and make a curl request to the model.
If you find that the AI gateway cannot make that request, this might be caused by the:
1. Model server not functioning correctly.
1. Network settings around the container not being properly configured to allow
requests to where the model is hosted.
To resolve this, contact your network administrator.
## Check if AI Gateway can make requests to your GitLab instance
The GitLab instance defined in `AIGW_GITLAB_URL` must be accessible from the AI Gateway container for request authentication.
If the instance is not reachable (for example, because of proxy configuration errors), requests can fail with errors, such as the following:
- ```shell
jose.exceptions.JWTError: Signature verification failed
```
- ```shell
gitlab_cloud_connector.providers.CompositeProvider.CriticalAuthError: No keys founds in JWKS; are OIDC providers up?
```
In this scenario, verify if `AIGW_GITLAB_URL` and `$AIGW_GITLAB_API_URL` are properly set to the container and accessible.
The following commands should be successful when run from the container:
```shell
poetry run troubleshoot
curl "$AIGW_GITLAB_API_URL/projects"
```
If not successful, verify your network configurations.
## The image's platform does not match the host
When [finding the AI gateway release](../../install/install_ai_gateway.md#find-the-ai-gateway-image),
you might get an error that states `The requested image's platform (linux/amd64) does not match the detected host`.
To work around this error, add `--platform linux/amd64` to the `docker run` command:
```shell
docker run --platform linux/amd64 -e AIGW_GITLAB_URL=<your-gitlab-endpoint> <image>
```
## LLM server is not available inside the AI gateway container
If the LLM server is installed on the same instance as the AI gateway container, it may not be accessible through the local host.
To resolve this:
1. Include `--network host` in the `docker run` command to enable local requests from the AI gateway container.
1. Use the `-e AIGW_FASTAPI__METRICS_PORT=8083` flag to address the port conflicts.
```shell
docker run --network host -e AIGW_GITLAB_URL=<your-gitlab-endpoint> -e AIGW_FASTAPI__METRICS_PORT=8083 <image>
```
## vLLM 404 Error
If you encounter a **404 error** while using vLLM, follow these steps to resolve the issue:
1. Create a chat template file named `chat_template.jinja` with the following content:
```jinja
{%- for message in messages %}
{%- if message["role"] == "user" %}
{{- "[INST] " + message["content"] + "[/INST]" }}
{%- elif message["role"] == "assistant" %}
{{- message["content"] }}
{%- elif message["role"] == "system" %}
{{- bos_token }}{{- message["content"] }}
{%- endif %}
{%- endfor %}
```
1. When running the vLLM command, ensure you specify the `--served-model-name`. For example:
```shell
vllm serve "mistralai/Mistral-7B-Instruct-v0.3" --port <port> --max-model-len 17776 --served-model-name mistral --chat-template chat_template.jinja
```
1. Check the vLLM server URL in the GitLab UI to make sure that URL includes the `/v1` suffix. The correct format is:
```shell
http(s)://<your-host>:<your-port>/v1
```
## Code Suggestions access error
If you are experiencing issues accessing Code Suggestions after setup, try the following steps:
1. In the Rails console, check and verify the license parameters:
```shell
sudo gitlab-rails console
user = User.find(id) # Replace id with the user provisioned with GitLab Duo Enterprise seat
Ability.allowed?(user, :access_code_suggestions) # Must return true
```
1. Check if the necessary features are enabled and available:
```shell
::Ai::FeatureSetting.code_suggestions_self_hosted? # Should be true
```
## Verify GitLab setup
To verify your GitLab Self-Managed setup, run the following command:
```shell
gitlab-rake gitlab:duo:verify_self_hosted_setup
```
## No logs generated in the AI gateway server
If no logs are generated in the **AI gateway server**, follow these steps to troubleshoot:
1. Ensure that [AI logs are enabled](logging.md#enable-logging).
1. Run the following commands to view the GitLab Rails logs for any errors:
```shell
sudo gitlab-ctl tail
sudo gitlab-ctl tail sidekiq
```
1. Look for keywords like "Error" or "Exception" in the logs to identify any underlying issues.
## SSL certificate errors and key de-serialization issues in the AI gateway Container
When attempting to initiate a Duo Chat inside the AI gateway container, SSL certificate errors and key deserialization issues may occur.
The system might encounter issues loading the PEM file, resulting in errors like:
```plaintext
JWKError: Could not deserialize key data. The data may be in an incorrect format, the provided password may be incorrect, or it may be encrypted with an unsupported algorithm.
```
To resolve the SSL certificate error:
- Set the appropriate certificate bundle path in the Docker container using the following environment variables:
- `SSL_CERT_FILE=/path/to/ca-bundle.pem`
- `REQUESTS_CA_BUNDLE=/path/to/ca-bundle.pem`
## Troubleshooting common Duo Chat errors
### Error A1000
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1000`.
This error occurs when there is a timeout during processing. Try your request again.
### Error A1001
You might get an error that states
`I'm sorry, I can't generate a response. Please try again. Error code: A1001`.
This error means there was a problem connecting to the AI gateway. You might need to check the network settings and ensure that the AI gateway is accessible from the GitLab instance.
Use the [self-hosted debugging script](#use-debugging-scripts) to verify if the AI gateway is accessible from the GitLab instance and is working as expected.
If problem persists, report the issue to the GitLab support team.
### Error A1002
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1002`.
This error occurs when no events are returned from AI gateway or GitLab failed to parse the events. Check the [AI Gateway logs](logging.md) for any errors.
### Error A1003
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1003`.
This error typically occurs due to issues with streaming from the model to the AI gateway. To resolve this issue:
1. In the AI gateway container, run the following command:
```shell
curl --request 'POST' \
'http://localhost:5052/v2/chat/agent' \
--header 'accept: application/json' \
--header 'Content-Type: application/json' \
--header 'x-gitlab-enabled-instance-verbose-ai-logs: true' \
--data '{
"messages": [
{
"role": "user",
"content": "Hello",
"context": null,
"current_file": null,
"additional_context": []
}
],
"model_metadata": {
"provider": "custom_openai",
"name": "mistral",
"endpoint": "<change here>",
"api_key": "<change here>",
"identifier": "<change here>"
},
"unavailable_resources": [],
"options": {
"agent_scratchpad": {
"agent_type": "react",
"steps": []
}
}
}'
```
If streaming is working, chunked responses should be displayed. If it is not, it will likely show an empty response.
1. Check the [AI gateway logs](logging.md) for specific error messages, because this is usually a model deployment issue.
1. To validate the connection, disable the streaming by setting the `AIGW_CUSTOM_MODELS__DISABLE_STREAMING` environment variable in your AI gateway container:
```shell
docker run .... -e AIGW_CUSTOM_MODELS__DISABLE_STREAMING=true ...
```
### Error A9999
You might get an error that states
`I'm sorry, I can't generate a response. Please try again. Error code: A9999`.
This error occurs when an unknown error occurs in ReAct agent. Try your request again. If the problem persists, report the issue to the GitLab support team.
## Feature not accessible or feature button not visible
If a feature is not working or a feature button (for example, **`/troubleshoot`**) is not visible:
1. Check if the feature's `unit_primitive` is listed in the [self-hosted models unit primitives list in the `gitlab-cloud-connector` gem configuration](https://gitlab.com/gitlab-org/cloud-connector/gitlab-cloud-connector/-/blob/main/config/services/self_hosted_models.yml).
If the feature is missing from this file, that could be the reason it's not accessible.
1. Optional. If the feature is not listed, you can verify this is the cause of the issue by setting the following in your GitLab instance:
```shell
CLOUD_CONNECTOR_SELF_SIGN_TOKENS=1
```
Then restart GitLab and check if the feature becomes accessible.
**Important**: After troubleshooting, restart GitLab **without** this flag set.
{{< alert type="warning" >}}
**Do not use `CLOUD_CONNECTOR_SELF_SIGN_TOKENS=1` in production**. Development environments should closely mirror production, with no hidden flags or internal-only workarounds.
{{< /alert >}}
1. To resolve this issue:
- If you're a GitLab team member, contact the Custom Models team through the [`#g_custom_models` Slack channel](https://gitlab.enterprise.slack.com/archives/C06DCB3N96F).
- If you're a customer, report the issue through [GitLab Support](https://about.gitlab.com/support/).
## Related topics
- [GitLab Duo troubleshooting](../../user/gitlab_duo_chat/troubleshooting.md)
- [Support Engineer Playbook and Common Issues](support_engineer_playbook.md)
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Troubleshooting tips for deploying GitLab Duo Self-Hosted
title: Troubleshooting GitLab Duo Self-Hosted
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
When working with GitLab Duo Self-Hosted, you might encounter issues.
Before you begin troubleshooting, you should:
- Be able to access the [`gitlab-rails` console](../operations/rails_console.md).
- Open a shell in the AI gateway Docker image.
- Know the endpoint where your:
- AI gateway is hosted.
- Model is hosted.
- [Enable logging](logging.md#enable-logging) to make sure that requests and responses from GitLab to the AI gateway are being logged to [`llm.log`](../logs/_index.md#llmlog).
For more information on troubleshooting GitLab Duo, see:
- [Troubleshooting GitLab Duo](../../user/gitlab_duo/troubleshooting.md).
- [Troubleshooting Code Suggestions](../../user/project/repository/code_suggestions/troubleshooting.md).
- [GitLab Duo Chat troubleshooting](../../user/gitlab_duo_chat/troubleshooting.md).
## Use debugging scripts
We provide two debugging scripts to help administrators verify their self-hosted model configuration.
1. Debug the GitLab to AI gateway connection. From your GitLab instance, run the
[Rake task](../../administration/raketasks/_index.md):
```shell
gitlab-rake "gitlab:duo:verify_self_hosted_setup[<username>]"
```
Optional: Include a `<username>` that has an assigned seat.
If you do not include a username parameter, the Rake task uses the root user.
1. Debug the AI gateway setup. For your AI gateway container:
- Restart the AI gateway container with authentication disabled by setting:
```shell
-e AIGW_AUTH__BYPASS_EXTERNAL=true
```
This setting is required for the troubleshooting command to run the **System Exchange test**. You must remove this setting after troubleshooting is complete.
- From your AI gateway container, run:
```shell
docker exec -it <ai-gateway-container> sh
poetry run troubleshoot [options]
```
The `troubleshoot` command supports the following options:
| Option | Default | Example | Description |
|----------------------|------------------|---------------------------------------------------------------|-------------|
| `--endpoint` | `localhost:5052` | `--endpoint=localhost:5052` | AI Gateway endpoint |
| `--model-family` | - | `--model-family=mistral` | Model family to test. Possible values are `mistral`, `mixtral`, `gpt`, or `claude_3` |
| `--model-endpoint` | - | `--model-endpoint=http://localhost:4000/v1` | Model endpoint. For models hosted on vLLM, add the `/v1` suffix. |
| `--model-identifier` | - | `--model-identifier=custom_openai/Mixtral-8x7B-Instruct-v0.1` | Model identifier. |
| `--api-key` | - | `--api-key=your-api-key` | Model API key. |
**Examples**:
For a `claude_3` model running on AWS Bedrock:
```shell
poetry run troubleshoot \
--model-family=claude_3 \
--model-identifier=bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0
```
For a `mixtral` model running on vLLM:
```shell
poetry run troubleshoot \
--model-family=mixtral \
--model-identifier=custom_openai/Mixtral-8x7B-Instruct-v0.1 \
--api-key=your-api-key \
--model-endpoint=http://<your-model-endpoint>/v1
```
After troubleshooting is complete, stop and restart the AI gateway container **without** `AIGW_AUTH__BYPASS_EXTERNAL=true`.
{{< alert type="warning" >}}
You must not bypass authentication in production.
{{< /alert >}}
Verify the output of the commands, and fix accordingly.
If both commands are successful, but GitLab Duo Code Suggestions is still not working,
raise an issue on the issue tracker.
## GitLab Duo health check is not working
When you [run a health check for GitLab Duo](../../administration/gitlab_duo/setup.md#run-a-health-check-for-gitlab-duo), you might get an error like a `401 response from the AI gateway`.
To resolve, first check if GitLab Duo features are functioning correctly. For example, send a message to Duo Chat.
If this does not work, the error might be because of a known issue with GitLab Duo health check. For more information, see [issue 517097](https://gitlab.com/gitlab-org/gitlab/-/issues/517097).
## Check if GitLab can make a request to the model
From the GitLab Rails console, verify that GitLab can make a request to the model
by running:
```ruby
model_name = "<your_model_name>"
model_endpoint = "<your_model_endpoint>"
model_api_key = "<your_model_api_key>"
body = {:prompt_components=>[{:type=>"prompt", :metadata=>{:source=>"GitLab EE", :version=>"17.3.0"}, :payload=>{:content=>[{:role=>:user, :content=>"Hello"}], :provider=>:litellm, :model=>model_name, :model_endpoint=>model_endpoint, :model_api_key=>model_api_key}}]}
ai_gateway_url = Ai::Setting.instance.ai_gateway_url # Verify that the AI gateway URL is set in the database
client = Gitlab::Llm::AiGateway::Client.new(User.find_by_id(1), service_name: :self_hosted_models)
client.complete(url: "#{ai_gateway_url}/v1/chat/agent", body: body)
```
This should return a response from the model in the format:
```ruby
{"response"=> "<Model response>",
"metadata"=>
{"provider"=>"litellm",
"model"=>"<>",
"timestamp"=>1723448920}}
```
If that is not the case, this might means one of the following:
- The user might not have access to Code Suggestions. To resolve,
[check if a user can request Code Suggestions](#check-if-a-user-can-request-code-suggestions).
- The GitLab environment variables are not configured correctly. To resolve, [check that the GitLab environment variables are set up correctly](#check-that-the-ai-gateway-environment-variables-are-set-up-correctly).
- The GitLab instance is not configured to use self-hosted models. To resolve, [check if the GitLab instance is configured to use self-hosted models](#check-if-gitlab-instance-is-configured-to-use-self-hosted-models).
- The AI gateway is not reachable. To resolve, [check if GitLab can make an HTTP request to the AI gateway](#check-if-gitlab-can-make-an-http-request-to-the-ai-gateway).
- When the LLM server is installed on the same instance as the AI gateway container, local requests may not work. To resolve, [allow local requests from the Docker container](#llm-server-is-not-available-inside-the-ai-gateway-container).
## Check if a user can request Code Suggestions
In the GitLab Rails console, check if a user can request Code Suggestions by running:
```ruby
User.find_by_id("<user_id>").can?(:access_code_suggestions)
```
If this returns `false`, it means some configuration is missing, and the user
cannot access Code Suggestions.
This missing configuration might be because of either of the following:
- The license is not valid. To resolve, [check or update your license](../license_file.md#see-current-license-information).
- GitLab Duo was not configured to use a self-hosted model. To resolve, [check if the GitLab instance is configured to use self-hosted models](#check-if-gitlab-instance-is-configured-to-use-self-hosted-models).
## Check if GitLab instance is configured to use self-hosted models
To check if GitLab Duo was configured correctly:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Self-hosted models**
1. Expand **AI-native features**.
1. Under **Features**, check that **Code Suggestions** and **Code generation** are set to **Self-hosted model**.
## Check that the AI gateway URL is set up correctly
To check that the AI gateway URL is correct, run the following on the GitLab Rails console:
```ruby
Ai::Setting.instance.ai_gateway_url == "<your-ai-gateway-instance-url>"
```
If the AI gateway is not set up, [configure your GitLab instance to access the AI gateway](configure_duo_features.md#configure-your-gitlab-instance-to-access-the-ai-gateway).
## Check if GitLab can make an HTTP request to the AI gateway
In the GitLab Rails console, verify that GitLab can make an HTTP request to AI
Gateway by running:
```ruby
HTTParty.get('<your-aigateway-endpoint>/monitoring/healthz', headers: { 'accept' => 'application/json' }).code
```
If the response is not `200`, this means either of the following:
- The network is not properly configured to allow GitLab to reach the AI gateway container. Contact your network administrator to verify the setup.
- The AI gateway is not able to process requests. To resolve this issue, [check if the AI gateway can make a request to the model](#check-if-the-ai-gateway-can-make-a-request-to-the-model).
## Check if the AI gateway can make a request to the model
From the AI gateway container, make an HTTP request to the AI gateway API for a
Code Suggestion. Replace:
- `<your_model_name>` with the name of the model you are using. For example `mistral` or `codegemma`.
- `<your_model_endpoint>` with the endpoint where the model is hosted.
```shell
docker exec -it <ai-gateway-container> sh
curl --request POST "http://localhost:5052/v1/chat/agent" \
--header 'accept: application/json' \
--header 'Content-Type: application/json' \
--data '{ "prompt_components": [ { "type": "string", "metadata": { "source": "string", "version": "string" }, "payload": { "content": "Hello", "provider": "litellm", "model": "<your_model_name>", "model_endpoint": "<your_model_endpoint>" } } ], "stream": false }'
```
If the request fails, the:
- AI gateway might not be configured properly to use self-hosted models. To resolve this,
[check that the AI gateway URL is set up correctly](#check-that-the-ai-gateway-url-is-set-up-correctly).
- AI gateway might not be able to access the model. To resolve,
[check if the model is reachable from the AI gateway](#check-if-the-model-is-reachable-from-ai-gateway).
- Model name or endpoint might be incorrect. Check the values, and correct them
if necessary.
## Check if AI gateway can process requests
```shell
docker exec -it <ai-gateway-container> sh
curl '<your-aigateway-endpoint>/monitoring/healthz'
```
If the response is not `200`, this means that AI gateway is not installed correctly. To resolve, follow the [documentation on how to install the AI gateway](../../install/install_ai_gateway.md).
## Check that the AI gateway environment variables are set up correctly
To check that the AI gateway environment variables are set up correctly, run the
following in a console on the AI gateway container:
```shell
docker exec -it <ai-gateway-container> sh
echo $AIGW_CUSTOM_MODELS__ENABLED # must be true
```
If the environment variables are not set up correctly, set them by
[creating a container](../../install/install_ai_gateway.md#find-the-ai-gateway-image).
## Check if the model is reachable from AI gateway
Create a shell on the AI gateway container and make a curl request to the model.
If you find that the AI gateway cannot make that request, this might be caused by the:
1. Model server not functioning correctly.
1. Network settings around the container not being properly configured to allow
requests to where the model is hosted.
To resolve this, contact your network administrator.
## Check if AI Gateway can make requests to your GitLab instance
The GitLab instance defined in `AIGW_GITLAB_URL` must be accessible from the AI Gateway container for request authentication.
If the instance is not reachable (for example, because of proxy configuration errors), requests can fail with errors, such as the following:
- ```shell
jose.exceptions.JWTError: Signature verification failed
```
- ```shell
gitlab_cloud_connector.providers.CompositeProvider.CriticalAuthError: No keys founds in JWKS; are OIDC providers up?
```
In this scenario, verify if `AIGW_GITLAB_URL` and `$AIGW_GITLAB_API_URL` are properly set to the container and accessible.
The following commands should be successful when run from the container:
```shell
poetry run troubleshoot
curl "$AIGW_GITLAB_API_URL/projects"
```
If not successful, verify your network configurations.
## The image's platform does not match the host
When [finding the AI gateway release](../../install/install_ai_gateway.md#find-the-ai-gateway-image),
you might get an error that states `The requested image's platform (linux/amd64) does not match the detected host`.
To work around this error, add `--platform linux/amd64` to the `docker run` command:
```shell
docker run --platform linux/amd64 -e AIGW_GITLAB_URL=<your-gitlab-endpoint> <image>
```
## LLM server is not available inside the AI gateway container
If the LLM server is installed on the same instance as the AI gateway container, it may not be accessible through the local host.
To resolve this:
1. Include `--network host` in the `docker run` command to enable local requests from the AI gateway container.
1. Use the `-e AIGW_FASTAPI__METRICS_PORT=8083` flag to address the port conflicts.
```shell
docker run --network host -e AIGW_GITLAB_URL=<your-gitlab-endpoint> -e AIGW_FASTAPI__METRICS_PORT=8083 <image>
```
## vLLM 404 Error
If you encounter a **404 error** while using vLLM, follow these steps to resolve the issue:
1. Create a chat template file named `chat_template.jinja` with the following content:
```jinja
{%- for message in messages %}
{%- if message["role"] == "user" %}
{{- "[INST] " + message["content"] + "[/INST]" }}
{%- elif message["role"] == "assistant" %}
{{- message["content"] }}
{%- elif message["role"] == "system" %}
{{- bos_token }}{{- message["content"] }}
{%- endif %}
{%- endfor %}
```
1. When running the vLLM command, ensure you specify the `--served-model-name`. For example:
```shell
vllm serve "mistralai/Mistral-7B-Instruct-v0.3" --port <port> --max-model-len 17776 --served-model-name mistral --chat-template chat_template.jinja
```
1. Check the vLLM server URL in the GitLab UI to make sure that URL includes the `/v1` suffix. The correct format is:
```shell
http(s)://<your-host>:<your-port>/v1
```
## Code Suggestions access error
If you are experiencing issues accessing Code Suggestions after setup, try the following steps:
1. In the Rails console, check and verify the license parameters:
```shell
sudo gitlab-rails console
user = User.find(id) # Replace id with the user provisioned with GitLab Duo Enterprise seat
Ability.allowed?(user, :access_code_suggestions) # Must return true
```
1. Check if the necessary features are enabled and available:
```shell
::Ai::FeatureSetting.code_suggestions_self_hosted? # Should be true
```
## Verify GitLab setup
To verify your GitLab Self-Managed setup, run the following command:
```shell
gitlab-rake gitlab:duo:verify_self_hosted_setup
```
## No logs generated in the AI gateway server
If no logs are generated in the **AI gateway server**, follow these steps to troubleshoot:
1. Ensure that [AI logs are enabled](logging.md#enable-logging).
1. Run the following commands to view the GitLab Rails logs for any errors:
```shell
sudo gitlab-ctl tail
sudo gitlab-ctl tail sidekiq
```
1. Look for keywords like "Error" or "Exception" in the logs to identify any underlying issues.
## SSL certificate errors and key de-serialization issues in the AI gateway Container
When attempting to initiate a Duo Chat inside the AI gateway container, SSL certificate errors and key deserialization issues may occur.
The system might encounter issues loading the PEM file, resulting in errors like:
```plaintext
JWKError: Could not deserialize key data. The data may be in an incorrect format, the provided password may be incorrect, or it may be encrypted with an unsupported algorithm.
```
To resolve the SSL certificate error:
- Set the appropriate certificate bundle path in the Docker container using the following environment variables:
- `SSL_CERT_FILE=/path/to/ca-bundle.pem`
- `REQUESTS_CA_BUNDLE=/path/to/ca-bundle.pem`
## Troubleshooting common Duo Chat errors
### Error A1000
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1000`.
This error occurs when there is a timeout during processing. Try your request again.
### Error A1001
You might get an error that states
`I'm sorry, I can't generate a response. Please try again. Error code: A1001`.
This error means there was a problem connecting to the AI gateway. You might need to check the network settings and ensure that the AI gateway is accessible from the GitLab instance.
Use the [self-hosted debugging script](#use-debugging-scripts) to verify if the AI gateway is accessible from the GitLab instance and is working as expected.
If problem persists, report the issue to the GitLab support team.
### Error A1002
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1002`.
This error occurs when no events are returned from AI gateway or GitLab failed to parse the events. Check the [AI Gateway logs](logging.md) for any errors.
### Error A1003
You might get an error that states
`I'm sorry, I couldn't respond in time. Please try again. Error code: A1003`.
This error typically occurs due to issues with streaming from the model to the AI gateway. To resolve this issue:
1. In the AI gateway container, run the following command:
```shell
curl --request 'POST' \
'http://localhost:5052/v2/chat/agent' \
--header 'accept: application/json' \
--header 'Content-Type: application/json' \
--header 'x-gitlab-enabled-instance-verbose-ai-logs: true' \
--data '{
"messages": [
{
"role": "user",
"content": "Hello",
"context": null,
"current_file": null,
"additional_context": []
}
],
"model_metadata": {
"provider": "custom_openai",
"name": "mistral",
"endpoint": "<change here>",
"api_key": "<change here>",
"identifier": "<change here>"
},
"unavailable_resources": [],
"options": {
"agent_scratchpad": {
"agent_type": "react",
"steps": []
}
}
}'
```
If streaming is working, chunked responses should be displayed. If it is not, it will likely show an empty response.
1. Check the [AI gateway logs](logging.md) for specific error messages, because this is usually a model deployment issue.
1. To validate the connection, disable the streaming by setting the `AIGW_CUSTOM_MODELS__DISABLE_STREAMING` environment variable in your AI gateway container:
```shell
docker run .... -e AIGW_CUSTOM_MODELS__DISABLE_STREAMING=true ...
```
### Error A9999
You might get an error that states
`I'm sorry, I can't generate a response. Please try again. Error code: A9999`.
This error occurs when an unknown error occurs in ReAct agent. Try your request again. If the problem persists, report the issue to the GitLab support team.
## Feature not accessible or feature button not visible
If a feature is not working or a feature button (for example, **`/troubleshoot`**) is not visible:
1. Check if the feature's `unit_primitive` is listed in the [self-hosted models unit primitives list in the `gitlab-cloud-connector` gem configuration](https://gitlab.com/gitlab-org/cloud-connector/gitlab-cloud-connector/-/blob/main/config/services/self_hosted_models.yml).
If the feature is missing from this file, that could be the reason it's not accessible.
1. Optional. If the feature is not listed, you can verify this is the cause of the issue by setting the following in your GitLab instance:
```shell
CLOUD_CONNECTOR_SELF_SIGN_TOKENS=1
```
Then restart GitLab and check if the feature becomes accessible.
**Important**: After troubleshooting, restart GitLab **without** this flag set.
{{< alert type="warning" >}}
**Do not use `CLOUD_CONNECTOR_SELF_SIGN_TOKENS=1` in production**. Development environments should closely mirror production, with no hidden flags or internal-only workarounds.
{{< /alert >}}
1. To resolve this issue:
- If you're a GitLab team member, contact the Custom Models team through the [`#g_custom_models` Slack channel](https://gitlab.enterprise.slack.com/archives/C06DCB3N96F).
- If you're a customer, report the issue through [GitLab Support](https://about.gitlab.com/support/).
## Related topics
- [GitLab Duo troubleshooting](../../user/gitlab_duo_chat/troubleshooting.md)
- [Support Engineer Playbook and Common Issues](support_engineer_playbook.md)
|
https://docs.gitlab.com/administration/support_engineer_playbook
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/support_engineer_playbook.md
|
2025-08-13
|
doc/administration/gitlab_duo_self_hosted
|
[
"doc",
"administration",
"gitlab_duo_self_hosted"
] |
support_engineer_playbook.md
|
AI-powered
|
Custom Models
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Duo Self-Hosted Support Engineer Playbook
|
Troubleshooting tips for GitLab Duo Self-Hosted
|
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
## Support Engineer Playbook and Common Issues
This section provides Support Engineers with essential commands and troubleshooting steps for debugging GitLab Duo Self-Hosted issues.
## Essential Debugging Commands
### Display AI Gateway Environment Variables
Check all AI Gateway environment variables to verify configuration:
```shell
docker exec -it <ai-gateway-container> env | grep AIGW
```
Key variables to verify:
- `AIGW_CUSTOM_MODELS__ENABLED` - must be `true`
- `AIGW_GITLAB_URL` - should match your GitLab instance URL
- `AIGW_GITLAB_API_URL` - should be accessible from the container
- `AIGW_AUTH__BYPASS_EXTERNAL` - should only be `true` during troubleshooting
### Verify User Permissions
Check if a user has the correct permissions for Code Suggestions with self-hosted models:
```ruby
# In GitLab Rails console
user = User.find_by_id("<user_id>")
user.allowed_to_use?(:code_suggestions, service_name: :self_hosted_models)
```
### Examine AI Gateway Client Logs
View AI Gateway client logs to identify connection issues:
```shell
docker logs <ai-gateway-container> | grep "Gitlab::Llm::AiGateway::Client"
```
### View GitLab Logs for AI Gateway Requests
To see the actual requests made to the AI Gateway, use:
```shell
# View live logs
sudo gitlab-ctl tail | grep -E "(ai_gateway|llm\.log)"
# View specific log file with JSON formatting
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq '.'
# Filter for specific request types
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq 'select(.message)'
sudo cat /var/log/gitlab/gitlab-rails/llm.log | grep Llm::CompletionWorker | jq '.'
```
### View AI Gateway Logs for Model Requests
To see the actual requests sent to the model:
```shell
# View AI Gateway container logs
docker logs <ai-gateway-container> 2>&1 | grep -E "(model|litellm|custom_openai)"
# For structured logs, if available
docker logs <ai-gateway-container> 2>&1 | grep "model_endpoint"
```
## Common Configuration Issues and Solutions
### Missing `/v1` Suffix in Model Endpoint
**Symptom**: 404 errors when making requests to vLLM or OpenAI-compatible models
**How to spot in logs**:
```shell
# Look for 404 errors in AI Gateway logs
docker logs <ai-gateway-container> | grep "404"
```
**Solution**: Ensure the model endpoint includes the `/v1` suffix:
- Incorrect: `http://localhost:4000`
- Correct: `http://localhost:4000/v1`
### Certificate Validation Issues
**Symptom**: SSL certificate errors or connection failures
**How to spot in logs**:
```shell
# Look for SSL/TLS errors
sudo cat /var/log/gitlab/gitlab-rails/llm.log | grep -i "ssl\|certificate\|tls"
```
**Validation**: Verify certificate status - GitLab server must use a trusted certificate, as self-signed certificates are not supported.
**Solution**:
- Use trusted certificates for GitLab instance
- If using self-signed certificates, configure proper certificate paths in the AI Gateway container
### Network Connectivity Issues
**Symptom**: Timeouts or connection refused errors
**How to spot in logs**:
```shell
# Look for network-related errors
docker logs <ai-gateway-container> | grep -E "(timeout|connection|refused|unreachable)"
```
**Validation commands**:
```shell
# Test from AI Gateway container to GitLab
docker exec -it <ai-gateway-container> curl "$AIGW_GITLAB_API_URL/projects"
# Test from AI Gateway container to model endpoint
docker exec -it <ai-gateway-container> curl "<model_endpoint>/health"
```
### Authentication and Authorization Issues
**Symptom**: 401 Unauthorized or 403 Forbidden errors
**How to spot in logs**:
```shell
# Look for authentication errors
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq 'select(.status == 401 or .status == 403)'
```
**Common causes**:
- User doesn't have GitLab Duo Enterprise seat assigned
- License issues
- Incorrect AI Gateway URL configuration
### Model Configuration Issues
**Symptom**: Model not responding or returning errors
**How to spot in logs**:
```shell
# Look for model-specific errors
docker logs <ai-gateway-container> | grep -E "(model_name|model_endpoint|litellm)"
```
**Validation**:
```shell
# Test model directly from AI Gateway container
docker exec -it <ai-gateway-container> sh
curl --request POST "<model_endpoint>/v1/chat/completions" \
--header 'Content-Type: application/json' \
--data '{"model": "<model_name>", "messages": [{"role": "user", "content": "Hello"}]}'
```
## Log Analysis Workflow
### Step 1: Enable Verbose Logging
Check if the `Capture detailed information about AI-related activities and requests` instance setting is enabled, in GitLab Rails console:
```ruby
::Ai::Setting.instance.enabled_instance_verbose_ai_logs
```
If it returns `false`, enable the flag using:
```ruby
::Ai::Setting.instance.update!(enabled_instance_verbose_ai_logs: true)
```
{{< alert type="note" >}}
To enable logging, use the `enabled_instance_verbose_ai_logs` instance setting. Do not use the `expanded_ai_logging` feature flag. Only use the `expanded_ai_logging` feature flag on GitLab.com for debugging purposes. Do not use this feature flag in GitLab Self-Managed instances, including instances running GitLab Duo Self-Hosted.
{{< /alert >}}
### Step 2: Reproduce the Issue
Have the user reproduce the issue while monitoring logs:
```shell
# Terminal 1: Monitor GitLab logs
sudo gitlab-ctl tail | grep -E "(ai_gateway|llm\.log)"
# Terminal 2: Monitor AI Gateway logs
docker logs -f <ai-gateway-container>
```
### Step 3: Analyze Request Flow
1. **GitLab to AI Gateway**: Check if request reaches AI Gateway
1. **AI Gateway to Model**: Verify model endpoint is called
1. **Response Path**: Ensure response is properly formatted and returned
### Step 4: Common Error Patterns
| Error Pattern | Location | Likely Cause |
|---------------|----------|--------------|
| `Connection refused` | GitLab logs | AI Gateway not accessible |
| `404 Not Found` | AI Gateway logs | Missing `/v1` in model endpoint |
| `401 Unauthorized` | GitLab logs | Authentication/license issues |
| `Timeout` | Either | Network or model performance issues |
| `SSL certificate verify failed` | GitLab logs | Certificate validation issues |
## Quick Diagnostic Commands
## **AI Gateway Instance Commands:**
**1. Test AI Gateway health:**
```shell
curl --silent --output /dev/null --write-out "%{http_code}" "<ai-gateway-url>/monitoring/healthz"
```
**2. Check AI Gateway environment variables:**
```shell
docker exec <ai-gateway-container> env | grep AIGW
```
**3. Check AI Gateway logs for errors:**
```shell
docker logs <ai-gateway-container> 2>&1 | grep --ignore-case error | tail --lines=20
```
## **GitLab Self-Managed Instance Commands:**
**4. Check user permissions (GitLab Rails console):**
```shell
sudo gitlab-rails console
```
Then in the console:
```ruby
User.find_by_id('<user_id>').can?(:access_code_suggestions)
```
**5. Check GitLab LLM logs for errors:**
```shell
sudo tail --lines=100 /var/log/gitlab/gitlab-rails/llm.log | grep --ignore-case error
```
**6. Check feature flags:**
```shell
sudo gitlab-rails console
```
Then:
```ruby
Feature.enabled?(:expanded_ai_logging)
```
**7. Test connectivity from GitLab to AI Gateway:**
```shell
curl --verbose "<ai-gateway-url>/monitoring/healthz"
```
### Emergency Diagnostic One-liner
For quick issue identification:
```shell
# Check all critical components at once
docker exec <ai-gateway-container> env | grep AIGW_CUSTOM_MODELS__ENABLED && \
curl --silent "<ai-gateway-url>/monitoring/healthz" && \
sudo tail --lines=10 /var/log/gitlab/gitlab-rails/llm.log | jq '.level'
```
## Escalation Criteria
Escalate to Custom Models team when:
1. **All basic troubleshooting steps completed** without resolution
1. **Model integration issues** that require deep technical knowledge
1. **Feature not listed** in self-hosted models unit primitives
1. **Suspected GitLab Duo platform bugs** affecting multiple users
1. **Performance issues** with specific model configurations
## Additional Resources
- [AI Gateway Installation Guide](../../install/install_ai_gateway.md)
- [GitLab Duo Self-Hosted Troubleshooting](troubleshooting.md)
|
---
stage: AI-powered
group: Custom Models
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Troubleshooting tips for GitLab Duo Self-Hosted
title: GitLab Duo Self-Hosted Support Engineer Playbook
breadcrumbs:
- doc
- administration
- gitlab_duo_self_hosted
---
{{< details >}}
- Tier: Premium, Ultimate
- Add-on: GitLab Duo Enterprise
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/12972) in GitLab 17.1 [with a flag](../feature_flags/_index.md) named `ai_custom_model`. Disabled by default.
- [Enabled on GitLab Self-Managed](https://gitlab.com/groups/gitlab-org/-/epics/15176) in GitLab 17.6.
- Changed to require GitLab Duo add-on in GitLab 17.6 and later.
- Feature flag `ai_custom_model` removed in GitLab 17.8.
- Generally available in GitLab 17.9.
- Changed to include Premium in GitLab 18.0.
{{< /history >}}
## Support Engineer Playbook and Common Issues
This section provides Support Engineers with essential commands and troubleshooting steps for debugging GitLab Duo Self-Hosted issues.
## Essential Debugging Commands
### Display AI Gateway Environment Variables
Check all AI Gateway environment variables to verify configuration:
```shell
docker exec -it <ai-gateway-container> env | grep AIGW
```
Key variables to verify:
- `AIGW_CUSTOM_MODELS__ENABLED` - must be `true`
- `AIGW_GITLAB_URL` - should match your GitLab instance URL
- `AIGW_GITLAB_API_URL` - should be accessible from the container
- `AIGW_AUTH__BYPASS_EXTERNAL` - should only be `true` during troubleshooting
### Verify User Permissions
Check if a user has the correct permissions for Code Suggestions with self-hosted models:
```ruby
# In GitLab Rails console
user = User.find_by_id("<user_id>")
user.allowed_to_use?(:code_suggestions, service_name: :self_hosted_models)
```
### Examine AI Gateway Client Logs
View AI Gateway client logs to identify connection issues:
```shell
docker logs <ai-gateway-container> | grep "Gitlab::Llm::AiGateway::Client"
```
### View GitLab Logs for AI Gateway Requests
To see the actual requests made to the AI Gateway, use:
```shell
# View live logs
sudo gitlab-ctl tail | grep -E "(ai_gateway|llm\.log)"
# View specific log file with JSON formatting
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq '.'
# Filter for specific request types
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq 'select(.message)'
sudo cat /var/log/gitlab/gitlab-rails/llm.log | grep Llm::CompletionWorker | jq '.'
```
### View AI Gateway Logs for Model Requests
To see the actual requests sent to the model:
```shell
# View AI Gateway container logs
docker logs <ai-gateway-container> 2>&1 | grep -E "(model|litellm|custom_openai)"
# For structured logs, if available
docker logs <ai-gateway-container> 2>&1 | grep "model_endpoint"
```
## Common Configuration Issues and Solutions
### Missing `/v1` Suffix in Model Endpoint
**Symptom**: 404 errors when making requests to vLLM or OpenAI-compatible models
**How to spot in logs**:
```shell
# Look for 404 errors in AI Gateway logs
docker logs <ai-gateway-container> | grep "404"
```
**Solution**: Ensure the model endpoint includes the `/v1` suffix:
- Incorrect: `http://localhost:4000`
- Correct: `http://localhost:4000/v1`
### Certificate Validation Issues
**Symptom**: SSL certificate errors or connection failures
**How to spot in logs**:
```shell
# Look for SSL/TLS errors
sudo cat /var/log/gitlab/gitlab-rails/llm.log | grep -i "ssl\|certificate\|tls"
```
**Validation**: Verify certificate status - GitLab server must use a trusted certificate, as self-signed certificates are not supported.
**Solution**:
- Use trusted certificates for GitLab instance
- If using self-signed certificates, configure proper certificate paths in the AI Gateway container
### Network Connectivity Issues
**Symptom**: Timeouts or connection refused errors
**How to spot in logs**:
```shell
# Look for network-related errors
docker logs <ai-gateway-container> | grep -E "(timeout|connection|refused|unreachable)"
```
**Validation commands**:
```shell
# Test from AI Gateway container to GitLab
docker exec -it <ai-gateway-container> curl "$AIGW_GITLAB_API_URL/projects"
# Test from AI Gateway container to model endpoint
docker exec -it <ai-gateway-container> curl "<model_endpoint>/health"
```
### Authentication and Authorization Issues
**Symptom**: 401 Unauthorized or 403 Forbidden errors
**How to spot in logs**:
```shell
# Look for authentication errors
sudo cat /var/log/gitlab/gitlab-rails/llm.log | jq 'select(.status == 401 or .status == 403)'
```
**Common causes**:
- User doesn't have GitLab Duo Enterprise seat assigned
- License issues
- Incorrect AI Gateway URL configuration
### Model Configuration Issues
**Symptom**: Model not responding or returning errors
**How to spot in logs**:
```shell
# Look for model-specific errors
docker logs <ai-gateway-container> | grep -E "(model_name|model_endpoint|litellm)"
```
**Validation**:
```shell
# Test model directly from AI Gateway container
docker exec -it <ai-gateway-container> sh
curl --request POST "<model_endpoint>/v1/chat/completions" \
--header 'Content-Type: application/json' \
--data '{"model": "<model_name>", "messages": [{"role": "user", "content": "Hello"}]}'
```
## Log Analysis Workflow
### Step 1: Enable Verbose Logging
Check if the `Capture detailed information about AI-related activities and requests` instance setting is enabled, in GitLab Rails console:
```ruby
::Ai::Setting.instance.enabled_instance_verbose_ai_logs
```
If it returns `false`, enable the flag using:
```ruby
::Ai::Setting.instance.update!(enabled_instance_verbose_ai_logs: true)
```
{{< alert type="note" >}}
To enable logging, use the `enabled_instance_verbose_ai_logs` instance setting. Do not use the `expanded_ai_logging` feature flag. Only use the `expanded_ai_logging` feature flag on GitLab.com for debugging purposes. Do not use this feature flag in GitLab Self-Managed instances, including instances running GitLab Duo Self-Hosted.
{{< /alert >}}
### Step 2: Reproduce the Issue
Have the user reproduce the issue while monitoring logs:
```shell
# Terminal 1: Monitor GitLab logs
sudo gitlab-ctl tail | grep -E "(ai_gateway|llm\.log)"
# Terminal 2: Monitor AI Gateway logs
docker logs -f <ai-gateway-container>
```
### Step 3: Analyze Request Flow
1. **GitLab to AI Gateway**: Check if request reaches AI Gateway
1. **AI Gateway to Model**: Verify model endpoint is called
1. **Response Path**: Ensure response is properly formatted and returned
### Step 4: Common Error Patterns
| Error Pattern | Location | Likely Cause |
|---------------|----------|--------------|
| `Connection refused` | GitLab logs | AI Gateway not accessible |
| `404 Not Found` | AI Gateway logs | Missing `/v1` in model endpoint |
| `401 Unauthorized` | GitLab logs | Authentication/license issues |
| `Timeout` | Either | Network or model performance issues |
| `SSL certificate verify failed` | GitLab logs | Certificate validation issues |
## Quick Diagnostic Commands
## **AI Gateway Instance Commands:**
**1. Test AI Gateway health:**
```shell
curl --silent --output /dev/null --write-out "%{http_code}" "<ai-gateway-url>/monitoring/healthz"
```
**2. Check AI Gateway environment variables:**
```shell
docker exec <ai-gateway-container> env | grep AIGW
```
**3. Check AI Gateway logs for errors:**
```shell
docker logs <ai-gateway-container> 2>&1 | grep --ignore-case error | tail --lines=20
```
## **GitLab Self-Managed Instance Commands:**
**4. Check user permissions (GitLab Rails console):**
```shell
sudo gitlab-rails console
```
Then in the console:
```ruby
User.find_by_id('<user_id>').can?(:access_code_suggestions)
```
**5. Check GitLab LLM logs for errors:**
```shell
sudo tail --lines=100 /var/log/gitlab/gitlab-rails/llm.log | grep --ignore-case error
```
**6. Check feature flags:**
```shell
sudo gitlab-rails console
```
Then:
```ruby
Feature.enabled?(:expanded_ai_logging)
```
**7. Test connectivity from GitLab to AI Gateway:**
```shell
curl --verbose "<ai-gateway-url>/monitoring/healthz"
```
### Emergency Diagnostic One-liner
For quick issue identification:
```shell
# Check all critical components at once
docker exec <ai-gateway-container> env | grep AIGW_CUSTOM_MODELS__ENABLED && \
curl --silent "<ai-gateway-url>/monitoring/healthz" && \
sudo tail --lines=10 /var/log/gitlab/gitlab-rails/llm.log | jq '.level'
```
## Escalation Criteria
Escalate to Custom Models team when:
1. **All basic troubleshooting steps completed** without resolution
1. **Model integration issues** that require deep technical knowledge
1. **Feature not listed** in self-hosted models unit primitives
1. **Suspected GitLab Duo platform bugs** affecting multiple users
1. **Performance issues** with specific model configurations
## Additional Resources
- [AI Gateway Installation Guide](../../install/install_ai_gateway.md)
- [GitLab Duo Self-Hosted Troubleshooting](troubleshooting.md)
|
https://docs.gitlab.com/administration/snippets
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/snippets
|
[
"doc",
"administration",
"snippets"
] |
_index.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Snippets
|
Configure snippets settings for your GitLab instance.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To prevent abuse of snippets on your instance, configure a maximum snippet size that is enforced
when users create or update snippets. Existing snippets are not affected by the limit unless a
user updates them, and their content changes.
The default limit is 52428800 bytes (50 MB).
## Configure the snippet size limit
To configure the snippet size limit, use either the Rails console
or the [Application settings API](../../api/settings.md).
The limit must be in bytes.
This setting is not available in the [**Admin** area settings](../settings/_index.md).
### Use the Rails console
To configure this setting through the Rails console:
1. [Start the Rails console](../operations/rails_console.md#starting-a-rails-console-session).
1. Update the snippets maximum file size:
```ruby
ApplicationSetting.first.update!(snippet_size_limit: 50.megabytes)
```
To retrieve the current value, start the Rails console and run:
```ruby
Gitlab::CurrentSettings.snippet_size_limit
```
### Use the API
To set the limit by using the Application Settings API
(similar to [updating any other setting](../../api/settings.md#update-application-settings)),
use this command:
```shell
curl --request PUT \
--header "PRIVATE-TOKEN: <your_access_token>"
--url "https://gitlab.example.com/api/v4/application/settings?snippet_size_limit=52428800"
```
To [retrieve the current value](../../api/settings.md#get-details-on-current-application-settings)
from the API:
```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/application/settings"
```
## Related topics
- [User snippets](../../user/snippets.md)
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Configure snippets settings for your GitLab instance.
title: Snippets
breadcrumbs:
- doc
- administration
- snippets
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To prevent abuse of snippets on your instance, configure a maximum snippet size that is enforced
when users create or update snippets. Existing snippets are not affected by the limit unless a
user updates them, and their content changes.
The default limit is 52428800 bytes (50 MB).
## Configure the snippet size limit
To configure the snippet size limit, use either the Rails console
or the [Application settings API](../../api/settings.md).
The limit must be in bytes.
This setting is not available in the [**Admin** area settings](../settings/_index.md).
### Use the Rails console
To configure this setting through the Rails console:
1. [Start the Rails console](../operations/rails_console.md#starting-a-rails-console-session).
1. Update the snippets maximum file size:
```ruby
ApplicationSetting.first.update!(snippet_size_limit: 50.megabytes)
```
To retrieve the current value, start the Rails console and run:
```ruby
Gitlab::CurrentSettings.snippet_size_limit
```
### Use the API
To set the limit by using the Application Settings API
(similar to [updating any other setting](../../api/settings.md#update-application-settings)),
use this command:
```shell
curl --request PUT \
--header "PRIVATE-TOKEN: <your_access_token>"
--url "https://gitlab.example.com/api/v4/application/settings?snippet_size_limit=52428800"
```
To [retrieve the current value](../../api/settings.md#get-details-on-current-application-settings)
from the API:
```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/application/settings"
```
## Related topics
- [User snippets](../../user/snippets.md)
|
https://docs.gitlab.com/administration/maintenance_mode
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/maintenance_mode
|
[
"doc",
"administration",
"maintenance_mode"
] |
_index.md
|
Tenant Scale
|
Geo
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Maintenance Mode
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Maintenance Mode allows administrators to reduce write operations to a minimum while maintenance tasks are performed. The main goal is to block all external actions that change the internal state. The internal state includes the PostgreSQL database, but especially files, Git repositories, and Container repositories.
When Maintenance Mode is enabled, in-progress actions finish relatively quickly because no new actions are coming in, and internal state changes are minimal.
In that state, various maintenance tasks are easier. Services can be stopped completely or
further degraded for a shorter period of time than might otherwise be needed. For example, stopping cron jobs and draining queues should be fairly quick.
Maintenance Mode allows most external actions that do not change internal state. On a high-level, HTTP `POST`, `PUT`, `PATCH`, and `DELETE` requests are blocked and a detailed overview of [how special cases are handled](#rest-api) is available.
## Enable Maintenance Mode
Enable Maintenance Mode as an administrator in one of these ways:
- **Web UI**:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings** > **General**.
1. Expand **Maintenance Mode**, and toggle **Enable Maintenance Mode**.
You can optionally add a message for the banner as well.
1. Select **Save changes**.
- **API**:
```shell
curl --request PUT --header "PRIVATE-TOKEN:$ADMIN_TOKEN" "<gitlab-url>/api/v4/application/settings?maintenance_mode=true"
```
## Disable Maintenance Mode
Disable Maintenance Mode in one of three ways:
- **Web UI**:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings** > **General**.
1. Expand **Maintenance Mode**, and toggle **Enable Maintenance Mode**.
You can optionally add a message for the banner as well.
1. Select **Save changes**.
- **API**:
```shell
curl --request PUT --header "PRIVATE-TOKEN:$ADMIN_TOKEN" "<gitlab-url>/api/v4/application/settings?maintenance_mode=false"
```
## Behavior of GitLab features in Maintenance Mode
When Maintenance Mode is enabled, a banner is displayed at the top of the page.
The banner can be customized with a specific message.
An error is displayed when a user tries to perform a write operation that isn't allowed.

{{< alert type="note" >}}
In some cases, the visual feedback from an action could be misleading. For example, when starring a project, the **Star** button changes to show the **Unstar** action. However, this is only the frontend update, and it doesn't take into account the failed status of the POST request. These visual bugs are to be fixed [in follow-up iterations](https://gitlab.com/gitlab-org/gitlab/-/issues/295197).
{{< /alert >}}
### Administrator functions
Systems administrators can edit the application settings. This allows
them to disable Maintenance Mode after it's been enabled.
### Authentication
All users can sign in and out of the GitLab instance but no new users can be created.
If there are [LDAP syncs](../auth/ldap/_index.md) scheduled for that time, they fail because user creation is disabled. Similarly, [user creations based on SAML](../../integration/saml.md#configure-saml-support-in-gitlab) fail.
### Git actions
All read-only Git operations continue to work, for example
`git clone` and `git pull`. All write operations fail, both through the CLI and Web IDE with the error message: `Git push is not allowed because this GitLab instance is currently in (read-only) maintenance mode.`
If Geo is enabled, Git pushes to both primary and secondaries fail.
### Merge requests, issues, epics
All write actions except those mentioned previously fail. For example, a user cannot update merge requests or issues.
### Incoming email
Creating new issue replies, issues (including new Service Desk issues), merge requests [by email](../incoming_email.md) fail.
### Outgoing email
Notification emails continue to arrive, but emails that require database writes, like resetting the password, do not arrive.
### REST API
For most JSON requests, `POST`, `PUT`, `PATCH`, and `DELETE` are blocked, and the API returns a `503` response with the error message: `GitLab Maintenance: system is in maintenance mode`. Only the following requests are allowed:
|HTTP request | Allowed routes | Notes |
|:----:|:--------------------------------------:|:----:|
| `POST` | `/admin/application_settings/general` | To allow updating application settings in the administrator UI |
| `PUT` | `/api/v4/application/settings` | To allow updating application settings with the API |
| `POST` | `/users/sign_in` | To allow users to sign in. |
| `POST` | `/users/sign_out`| To allow users to sign out. |
| `POST` | `/oauth/token` | To allow users to sign in to a Geo secondary for the first time. |
| `POST` | `/admin/session`, `/admin/session/destroy` | To allow [Admin Mode for GitLab administrators](https://gitlab.com/groups/gitlab-org/-/epics/2158) |
| `POST` | Paths ending with `/compare`| Git revision routes. |
| `POST` | `.git/git-upload-pack` | To allow Git pull/clone. |
| `POST` | `/api/v4/internal` | internal API routes |
| `POST` | `/admin/sidekiq` | To allow management of background jobs in the **Admin** area |
| `POST` | `/admin/geo` | To allow updating Geo Nodes in the administrator UI |
| `POST` | `/api/v4/geo_replication`| To allow certain Geo-specific administrator UI actions on secondary sites |
### GraphQL API
{{< history >}}
- The `GeoRegistriesUpdate` mutation addition in the allowlist was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124259) in GitLab 16.2.
{{< /history >}}
`POST /api/graphql` requests are allowed but mutations are blocked with the error message `You cannot perform write operations on a read-only instance`.
The only mutation that is allowed is the `GeoRegistriesUpdate` which is used to resync and reverify registries.
### Continuous Integration
- No new jobs or pipelines start, scheduled or otherwise.
- Jobs that were already running continue to have a `running` status in the GitLab UI,
even if they finish running on the GitLab Runner.
- Jobs in the `running` state for longer than the project's time limit do not time out.
- Pipelines cannot be started, retried or canceled. No new jobs can be created either.
- The status of the runners in `/admin/runners` isn't updated.
- `gitlab-runner verify` returns the error `ERROR: Verifying runner... is removed`.
After Maintenance Mode is disabled, new jobs are picked up again. Jobs that were
in the `running` state before enabling Maintenance Mode resume and their logs start
updating again.
{{< alert type="note" >}}
You should restart previously `running` pipelines after Maintenance Mode
is turned off.
{{< /alert >}}
### Deployments
Deployments don't go through because pipelines are unfinished.
You should disable auto deploys during Maintenance Mode, and enable them when it is disabled.
#### Terraform integration
Terraform integration depends on running CI pipelines, hence it is blocked.
### Container registry
`docker push` fails with this error: `denied: requested access to the resource is denied`, but `docker pull` works.
### Package registry
Package registry allows you to install but not publish packages.
### Background jobs
Background jobs (cron jobs, Sidekiq) continue running as is, because background jobs are not automatically disabled.
As background jobs perform operations that can change the internal state of your instance, you may want to disable
some or all of them while maintenance mode is enabled.
[During a planned Geo failover](../geo/disaster_recovery/planned_failover.md#prevent-updates-to-the-primary-site),
you should disable all cron jobs except for those related to Geo.
To monitor queues and disable jobs:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Monitoring** > **Background jobs**.
1. In the Sidekiq dashboard, select **Cron** and disable jobs individually or all at once by selecting **Disable All**.
### Incident management
[Incident management](../../operations/incident_management/_index.md) functions are limited. The creation of [alerts](../../operations/incident_management/alerts.md) and [incidents](../../operations/incident_management/manage_incidents.md#create-an-incident) are paused entirely. Notifications and paging on alerts and incidents are therefore disabled.
### Feature flags
- Development feature flags cannot be turned on or off through the API, but can be toggled through the Rails console.
- [The feature flag service](../../operations/feature_flags.md) responds to feature flag checks but feature flags cannot be toggled
### Geo secondaries
When primary is in Maintenance Mode, secondary also automatically goes into Maintenance Mode.
It is important that you do not disable replication before enabling Maintenance Mode.
Replication, verification and manual actions to resync and reverify registries through the Admin UI
continue to work, but proxied Git pushes to primary don't.
### Secure features
Features that depend on creating issues or creating or approving merge requests,
do not work.
Exporting a vulnerability list from a vulnerability report page does not work.
Changing the status on a finding or vulnerability object does not work, even though no error is shown in the UI.
SAST and Secret Detection cannot be initiated because they depend on passing CI jobs to create artifacts.
## An example use case: a planned failover
In the use case of [a planned failover](../geo/disaster_recovery/planned_failover.md), a few writes in the primary database are acceptable, because they are replicated quickly and are not significant in number.
For the same reason we don't automatically block background jobs when Maintenance Mode is enabled.
The resulting database writes are acceptable. Here, the trade-off is between more service degradation and the completion of replication.
However, during a planned failover, we [ask users to turn off cron jobs that are not related to Geo, manually](../geo/disaster_recovery/planned_failover.md#prevent-updates-to-the-primary-site). In the absence of new database writes and non-Geo cron jobs, new background jobs would either not be created at all or be minimal.
|
---
stage: Tenant Scale
group: Geo
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab Maintenance Mode
breadcrumbs:
- doc
- administration
- maintenance_mode
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Maintenance Mode allows administrators to reduce write operations to a minimum while maintenance tasks are performed. The main goal is to block all external actions that change the internal state. The internal state includes the PostgreSQL database, but especially files, Git repositories, and Container repositories.
When Maintenance Mode is enabled, in-progress actions finish relatively quickly because no new actions are coming in, and internal state changes are minimal.
In that state, various maintenance tasks are easier. Services can be stopped completely or
further degraded for a shorter period of time than might otherwise be needed. For example, stopping cron jobs and draining queues should be fairly quick.
Maintenance Mode allows most external actions that do not change internal state. On a high-level, HTTP `POST`, `PUT`, `PATCH`, and `DELETE` requests are blocked and a detailed overview of [how special cases are handled](#rest-api) is available.
## Enable Maintenance Mode
Enable Maintenance Mode as an administrator in one of these ways:
- **Web UI**:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings** > **General**.
1. Expand **Maintenance Mode**, and toggle **Enable Maintenance Mode**.
You can optionally add a message for the banner as well.
1. Select **Save changes**.
- **API**:
```shell
curl --request PUT --header "PRIVATE-TOKEN:$ADMIN_TOKEN" "<gitlab-url>/api/v4/application/settings?maintenance_mode=true"
```
## Disable Maintenance Mode
Disable Maintenance Mode in one of three ways:
- **Web UI**:
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Settings** > **General**.
1. Expand **Maintenance Mode**, and toggle **Enable Maintenance Mode**.
You can optionally add a message for the banner as well.
1. Select **Save changes**.
- **API**:
```shell
curl --request PUT --header "PRIVATE-TOKEN:$ADMIN_TOKEN" "<gitlab-url>/api/v4/application/settings?maintenance_mode=false"
```
## Behavior of GitLab features in Maintenance Mode
When Maintenance Mode is enabled, a banner is displayed at the top of the page.
The banner can be customized with a specific message.
An error is displayed when a user tries to perform a write operation that isn't allowed.

{{< alert type="note" >}}
In some cases, the visual feedback from an action could be misleading. For example, when starring a project, the **Star** button changes to show the **Unstar** action. However, this is only the frontend update, and it doesn't take into account the failed status of the POST request. These visual bugs are to be fixed [in follow-up iterations](https://gitlab.com/gitlab-org/gitlab/-/issues/295197).
{{< /alert >}}
### Administrator functions
Systems administrators can edit the application settings. This allows
them to disable Maintenance Mode after it's been enabled.
### Authentication
All users can sign in and out of the GitLab instance but no new users can be created.
If there are [LDAP syncs](../auth/ldap/_index.md) scheduled for that time, they fail because user creation is disabled. Similarly, [user creations based on SAML](../../integration/saml.md#configure-saml-support-in-gitlab) fail.
### Git actions
All read-only Git operations continue to work, for example
`git clone` and `git pull`. All write operations fail, both through the CLI and Web IDE with the error message: `Git push is not allowed because this GitLab instance is currently in (read-only) maintenance mode.`
If Geo is enabled, Git pushes to both primary and secondaries fail.
### Merge requests, issues, epics
All write actions except those mentioned previously fail. For example, a user cannot update merge requests or issues.
### Incoming email
Creating new issue replies, issues (including new Service Desk issues), merge requests [by email](../incoming_email.md) fail.
### Outgoing email
Notification emails continue to arrive, but emails that require database writes, like resetting the password, do not arrive.
### REST API
For most JSON requests, `POST`, `PUT`, `PATCH`, and `DELETE` are blocked, and the API returns a `503` response with the error message: `GitLab Maintenance: system is in maintenance mode`. Only the following requests are allowed:
|HTTP request | Allowed routes | Notes |
|:----:|:--------------------------------------:|:----:|
| `POST` | `/admin/application_settings/general` | To allow updating application settings in the administrator UI |
| `PUT` | `/api/v4/application/settings` | To allow updating application settings with the API |
| `POST` | `/users/sign_in` | To allow users to sign in. |
| `POST` | `/users/sign_out`| To allow users to sign out. |
| `POST` | `/oauth/token` | To allow users to sign in to a Geo secondary for the first time. |
| `POST` | `/admin/session`, `/admin/session/destroy` | To allow [Admin Mode for GitLab administrators](https://gitlab.com/groups/gitlab-org/-/epics/2158) |
| `POST` | Paths ending with `/compare`| Git revision routes. |
| `POST` | `.git/git-upload-pack` | To allow Git pull/clone. |
| `POST` | `/api/v4/internal` | internal API routes |
| `POST` | `/admin/sidekiq` | To allow management of background jobs in the **Admin** area |
| `POST` | `/admin/geo` | To allow updating Geo Nodes in the administrator UI |
| `POST` | `/api/v4/geo_replication`| To allow certain Geo-specific administrator UI actions on secondary sites |
### GraphQL API
{{< history >}}
- The `GeoRegistriesUpdate` mutation addition in the allowlist was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124259) in GitLab 16.2.
{{< /history >}}
`POST /api/graphql` requests are allowed but mutations are blocked with the error message `You cannot perform write operations on a read-only instance`.
The only mutation that is allowed is the `GeoRegistriesUpdate` which is used to resync and reverify registries.
### Continuous Integration
- No new jobs or pipelines start, scheduled or otherwise.
- Jobs that were already running continue to have a `running` status in the GitLab UI,
even if they finish running on the GitLab Runner.
- Jobs in the `running` state for longer than the project's time limit do not time out.
- Pipelines cannot be started, retried or canceled. No new jobs can be created either.
- The status of the runners in `/admin/runners` isn't updated.
- `gitlab-runner verify` returns the error `ERROR: Verifying runner... is removed`.
After Maintenance Mode is disabled, new jobs are picked up again. Jobs that were
in the `running` state before enabling Maintenance Mode resume and their logs start
updating again.
{{< alert type="note" >}}
You should restart previously `running` pipelines after Maintenance Mode
is turned off.
{{< /alert >}}
### Deployments
Deployments don't go through because pipelines are unfinished.
You should disable auto deploys during Maintenance Mode, and enable them when it is disabled.
#### Terraform integration
Terraform integration depends on running CI pipelines, hence it is blocked.
### Container registry
`docker push` fails with this error: `denied: requested access to the resource is denied`, but `docker pull` works.
### Package registry
Package registry allows you to install but not publish packages.
### Background jobs
Background jobs (cron jobs, Sidekiq) continue running as is, because background jobs are not automatically disabled.
As background jobs perform operations that can change the internal state of your instance, you may want to disable
some or all of them while maintenance mode is enabled.
[During a planned Geo failover](../geo/disaster_recovery/planned_failover.md#prevent-updates-to-the-primary-site),
you should disable all cron jobs except for those related to Geo.
To monitor queues and disable jobs:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Monitoring** > **Background jobs**.
1. In the Sidekiq dashboard, select **Cron** and disable jobs individually or all at once by selecting **Disable All**.
### Incident management
[Incident management](../../operations/incident_management/_index.md) functions are limited. The creation of [alerts](../../operations/incident_management/alerts.md) and [incidents](../../operations/incident_management/manage_incidents.md#create-an-incident) are paused entirely. Notifications and paging on alerts and incidents are therefore disabled.
### Feature flags
- Development feature flags cannot be turned on or off through the API, but can be toggled through the Rails console.
- [The feature flag service](../../operations/feature_flags.md) responds to feature flag checks but feature flags cannot be toggled
### Geo secondaries
When primary is in Maintenance Mode, secondary also automatically goes into Maintenance Mode.
It is important that you do not disable replication before enabling Maintenance Mode.
Replication, verification and manual actions to resync and reverify registries through the Admin UI
continue to work, but proxied Git pushes to primary don't.
### Secure features
Features that depend on creating issues or creating or approving merge requests,
do not work.
Exporting a vulnerability list from a vulnerability report page does not work.
Changing the status on a finding or vulnerability object does not work, even though no error is shown in the UI.
SAST and Secret Detection cannot be initiated because they depend on passing CI jobs to create artifacts.
## An example use case: a planned failover
In the use case of [a planned failover](../geo/disaster_recovery/planned_failover.md), a few writes in the primary database are acceptable, because they are replicated quickly and are not significant in number.
For the same reason we don't automatically block background jobs when Maintenance Mode is enabled.
The resulting database writes are acceptable. Here, the trade-off is between more service degradation and the completion of replication.
However, during a planned failover, we [ask users to turn off cron jobs that are not related to Geo, manually](../geo/disaster_recovery/planned_failover.md#prevent-updates-to-the-primary-site). In the absence of new database writes and non-Geo cron jobs, new background jobs would either not be created at all or be minimal.
|
https://docs.gitlab.com/administration/crowd
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/crowd.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
crowd.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use Atlassian Crowd as an authentication provider
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Authenticate to GitLab using the Atlassian Crowd OmniAuth provider. Enabling
this provider also allows Crowd authentication for Git-over-https requests.
## Configure a new Crowd application
1. On the top menu, select **Applications > Add application**.
1. Go through the **Add application** steps, entering the appropriate details.
1. When complete, select **Add application**.
## Configure GitLab
1. On your GitLab server, open the configuration file.
- Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
- Self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `crowd` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration:
- Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "crowd",
args: {
crowd_server_url: "CROWD_SERVER_URL",
application_name: "YOUR_APP_NAME",
application_password: "YOUR_APP_PASSWORD"
}
}
]
```
- Self-compiled installations:
```yaml
- { name: 'crowd',
args: {
crowd_server_url: 'CROWD_SERVER_URL',
application_name: 'YOUR_APP_NAME',
application_password: 'YOUR_APP_PASSWORD' } }
```
1. Change `CROWD_SERVER_URL` to the [base URL of your Crowd server](https://confluence.atlassian.com/crowdkb/how-to-change-the-crowd-base-url-245827278.html).
1. Change `YOUR_APP_NAME` to the application name from Crowd applications page.
1. Change `YOUR_APP_PASSWORD` to the application password you've set.
1. Save the configuration file.
1. [Reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) (Linux package installations) or
[restart](../restart_gitlab.md#self-compiled-installations) (self-compiled installations) for the changes to take effect.
On the sign in page there should now be a Crowd tab in the sign in form.
## Troubleshooting
### Error: "could not authorize you from Crowd because invalid credentials"
This error sometimes occurs when a user attempts to authenticate with Crowd. The
Crowd administrator should consult the Crowd log file to know the exact cause of
this error message.
Ensure the Crowd users who must sign in to GitLab are authorized to the
[application](#configure-a-new-crowd-application) in the **Authorization** step.
This could be verified by trying "Authentication test" for Crowd (as of 2.11).

|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use Atlassian Crowd as an authentication provider
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Authenticate to GitLab using the Atlassian Crowd OmniAuth provider. Enabling
this provider also allows Crowd authentication for Git-over-https requests.
## Configure a new Crowd application
1. On the top menu, select **Applications > Add application**.
1. Go through the **Add application** steps, entering the appropriate details.
1. When complete, select **Add application**.
## Configure GitLab
1. On your GitLab server, open the configuration file.
- Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
- Self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `crowd` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration:
- Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "crowd",
args: {
crowd_server_url: "CROWD_SERVER_URL",
application_name: "YOUR_APP_NAME",
application_password: "YOUR_APP_PASSWORD"
}
}
]
```
- Self-compiled installations:
```yaml
- { name: 'crowd',
args: {
crowd_server_url: 'CROWD_SERVER_URL',
application_name: 'YOUR_APP_NAME',
application_password: 'YOUR_APP_PASSWORD' } }
```
1. Change `CROWD_SERVER_URL` to the [base URL of your Crowd server](https://confluence.atlassian.com/crowdkb/how-to-change-the-crowd-base-url-245827278.html).
1. Change `YOUR_APP_NAME` to the application name from Crowd applications page.
1. Change `YOUR_APP_PASSWORD` to the application password you've set.
1. Save the configuration file.
1. [Reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) (Linux package installations) or
[restart](../restart_gitlab.md#self-compiled-installations) (self-compiled installations) for the changes to take effect.
On the sign in page there should now be a Crowd tab in the sign in form.
## Troubleshooting
### Error: "could not authorize you from Crowd because invalid credentials"
This error sometimes occurs when a user attempts to authenticate with Crowd. The
Crowd administrator should consult the Crowd log file to know the exact cause of
this error message.
Ensure the Crowd users who must sign in to GitLab are authorized to the
[application](#configure-a-new-crowd-application) in the **Authorization** step.
This could be verified by trying "Authentication test" for Crowd (as of 2.11).

|
https://docs.gitlab.com/administration/smartcard
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/smartcard.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
smartcard.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Smart card authentication
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab supports authentication using smart cards.
## Existing password authentication
By default, existing users can continue to sign in with a username and password when smart card
authentication is enabled.
To force existing users to use only smart card authentication,
[disable username and password authentication](../settings/sign_in_restrictions.md#password-authentication-enabled).
## Authentication methods
GitLab supports two authentication methods:
- X.509 certificates with local databases.
- LDAP servers.
### Authentication against a local database with X.509 certificates
{{< details >}}
- Status: Experiment
{{< /details >}}
Smart cards with X.509 certificates can be used to authenticate with GitLab.
To use a smart card with an X.509 certificate to authenticate against a local
database with GitLab, `CN` and `emailAddress` must be defined in the
certificate. For example:
```plaintext
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 12856475246677808609 (0xb26b601ecdd555e1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=Random Corp Ltd, CN=Random Corp
Validity
Not Before: Oct 30 12:00:00 2018 GMT
Not After : Oct 30 12:00:00 2019 GMT
Subject: CN=Gitlab User, emailAddress=gitlab-user@example.com
```
### Authentication against a local database with X.509 certificates and SAN extension
{{< details >}}
- Status: Experiment
{{< /details >}}
Smart cards with X.509 certificates using SAN extensions can be used to authenticate
with GitLab.
To use a smart card with an X.509 certificate to authenticate against a local
database with GitLab:
- At least one of the `subjectAltName` (SAN) extensions
must define the user identity (`email`) within the GitLab instance (`URI`).
- The `URI` must match `Gitlab.config.host.gitlab`.
- If your certificate contains only **one** SAN email entry, you don't need to
add or modify it to match the `email` with the `URI`.
For example:
```plaintext
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 12856475246677808609 (0xb26b601ecdd555e1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=Random Corp Ltd, CN=Random Corp
Validity
Not Before: Oct 30 12:00:00 2018 GMT
Not After : Oct 30 12:00:00 2019 GMT
...
X509v3 extensions:
X509v3 Key Usage:
Key Encipherment, Data Encipherment
X509v3 Extended Key Usage:
TLS Web Server Authentication
X509v3 Subject Alternative Name:
email:gitlab-user@example.com, URI:http://gitlab.example.com/
```
### Authentication against an LDAP server
{{< details >}}
- Status: Experiment
{{< /details >}}
GitLab implements a standard way of certificate matching following
[RFC4523](https://www.rfc-editor.org/rfc/rfc4523). It uses the
`certificateExactMatch` certificate matching rule against the `userCertificate`
attribute. As a prerequisite, you must use an LDAP server that:
- Supports the `certificateExactMatch` matching rule.
- Has the certificate stored in the `userCertificate` attribute.
### Authentication against an Active Directory LDAP server
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/328074) in GitLab 16.9.
- [Added](https://gitlab.com/gitlab-org/gitlab/-/issues/514025) `reverse_issuer_and_subject` and `reverse_issuer_and_serial_number` formats in GitLab 17.11.
{{< /history >}}
Active Directory does not support the `certificateExactMatch` rule or the `userCertificate` attribute. Most tools for certificate-based authentication such as smart cards use the `altSecurityIdentities` attribute, which can contain multiple certificates for each user. The data in the field must match [one of the formats Microsoft recommends](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-certificate-based-authentication-certificateuserids#supported-patterns-for-certificate-user-ids).
Use the following attributes to customize the field GitLab checks and the format for certificate data:
- `smartcard_ad_cert_field` - specify the name of the field to search. This can be any attribute on a user object.
- `smartcard_ad_cert_format` - specify the format of the information gathered from the certificate. This format must be one of the following values. The most common is
`issuer_and_serial_number` to match the behavior of non-Active Directory LDAP servers.
| `smartcard_ad_cert_format` | Example data |
| -------------------------- | ------------------------------------------------------------ |
| `principal_name` | `X509:<PN>alice@example.com` |
| `rfc822_name` | `X509:<RFC822>bob@example.com` |
| `subject` | `X509:<S>DC=com,DC=example,OU=UserAccounts,CN=dennis` |
| `issuer_and_serial_number` | `X509:<I>DC=com,DC=example,CN=CONTOSO-DC-CA<SR>1181914561` |
| `issuer_and_subject` | `X509:<I>DC=com,DC=example,CN=EXAMPLE-DC-CA<S>DC=com,DC=example,OU=UserAccounts,CN=cynthia` |
| `reverse_issuer_and_serial_number` | `X509:<I>CN=CONTOSO-DC-CA,DC=example,DC=com<SR>1181914561` |
| `reverse_issuer_and_subject` | `X509:<I>CN=EXAMPLE-DC-CA,DC=example,DC=com<S>DC=com,DC=example,OU=UserAccounts,CN=cynthia` |
For `issuer_and_serial_number`, the `<SR>` portion is in reverse-byte-order, with the least-significant byte first. For more information, see [how to map a user to a certificate using the altSecurityIdentities attribute](https://learn.microsoft.com/en-us/archive/blogs/spatdsg/howto-map-a-user-to-a-certificate-via-all-the-methods-available-in-the-altsecurityidentities-attribute).
The reverse issuer formats sort the issuer string from the smallest unit to the largest. Some
Active Directory servers store certificates in this format.
{{< alert type="note" >}}
If no `smartcard_ad_cert_format` is specified, but an LDAP server is configured with `active_directory: true` and smart cards enabled, GitLab defaults to the behavior of 16.8 and earlier, and uses `certificateExactMatch` on the `userCertificate` attribute.
{{< /alert >}}
### Authentication against Entra ID Domain Services
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/328074) in GitLab 16.9.
{{< /history >}}
[Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/fundamentals/whatis), formerly known as Azure Active Directory, provides a cloud-based directory for companies and organizations. [Entra Domain Services](https://learn.microsoft.com/en-us/entra/identity/domain-services/overview) provides a secure read-only LDAP interface to the directory, but only exposes a limited subset of the fields Entra ID has.
Entra ID uses the `CertificateUserIds` field to manage client certificates for users, but this field is not exposed in LDAP / Entra ID Domain Services. With a cloud-only setup, it is not possible for GitLab to authenticate users' smart cards using LDAP.
In a hybrid on-premise and cloud environment, entities are synced between the on-premise Active Directory controller and the cloud Entra ID using [Entra Connect](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-azure-ad-connect-v2). If you are [syncing your `altSecurityIdentities` attribute to `certificateUserIds` in Entra ID using Entra ID Connect](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-certificate-based-authentication-certificateuserids#update-certificateuserids-using-microsoft-entra-connect), you can expose this data in LDAP / Entra ID Domain Services so it can be authenticated by GitLab:
1. Add a rule to Entra ID Connect to sync the `altSecurityIdentities` to an additional attribute in Entra ID.
1. Enable that extra attribute as an [extension attribute in Entra ID Domain Services](https://learn.microsoft.com/en-us/entra/identity/domain-services/concepts-custom-attributes).
1. Configure the `smartcard_ad_cert_field` field in GitLab to use this extension attribute.
## Configure GitLab for smart card authentication
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Allow smart card authentication
gitlab_rails['smartcard_enabled'] = true
# Path to a file containing a CA certificate
gitlab_rails['smartcard_ca_file'] = "/etc/ssl/certs/CA.pem"
# Host and port where the client side certificate is requested by the
# webserver (NGINX/Apache)
gitlab_rails['smartcard_client_certificate_required_host'] = "smartcard.example.com"
gitlab_rails['smartcard_client_certificate_required_port'] = 3444
```
{{< alert type="note" >}}
Assign a value to at least one of the following variables:
`gitlab_rails['smartcard_client_certificate_required_host']` or
`gitlab_rails['smartcard_client_certificate_required_port']`.
{{< /alert >}}
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Configure NGINX to request a client side certificate
In NGINX configuration, an **additional** server context must be defined with
the same configuration except:
- The additional NGINX server context must be configured to run on a different
port:
```plaintext
listen *:3444 ssl;
```
- It can also be configured to run on a different hostname:
```plaintext
listen smartcard.example.com:443 ssl;
```
- The additional NGINX server context must be configured to require the client
side certificate:
```plaintext
ssl_verify_depth 2;
ssl_client_certificate /etc/ssl/certs/CA.pem;
ssl_verify_client on;
```
- The additional NGINX server context must be configured to forward the client
side certificate:
```plaintext
proxy_set_header X-SSL-Client-Certificate $ssl_client_escaped_cert;
```
For example, the following is an example server context in an NGINX
configuration file (such as in `/etc/nginx/sites-available/gitlab-ssl`):
```plaintext
server {
listen smartcard.example.com:3443 ssl;
# certificate for configuring SSL
ssl_certificate /path/to/example.com.crt;
ssl_certificate_key /path/to/example.com.key;
ssl_verify_depth 2;
# CA certificate for client side certificate verification
ssl_client_certificate /etc/ssl/certs/CA.pem;
ssl_verify_client on;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-SSL-Client-Certificate $ssl_client_escaped_cert;
proxy_read_timeout 300;
proxy_pass http://gitlab-workhorse;
}
}
```
1. Edit `config/gitlab.yml`:
```yaml
## Smart card authentication settings
smartcard:
# Allow smart card authentication
enabled: true
# Path to a file containing a CA certificate
ca_file: '/etc/ssl/certs/CA.pem'
# Host and port where the client side certificate is requested by the
# webserver (NGINX/Apache)
client_certificate_required_host: smartcard.example.com
client_certificate_required_port: 3443
```
{{< alert type="note" >}}
Assign a value to at least one of the following variables:
`client_certificate_required_host` or `client_certificate_required_port`.
{{< /alert >}}
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Additional steps when using SAN extensions
For Linux package installations:
1. Add to `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['smartcard_san_extensions'] = true
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Add the `san_extensions` line to `config/gitlab.yml` within the smart card section:
```yaml
smartcard:
enabled: true
ca_file: '/etc/ssl/certs/CA.pem'
client_certificate_required_port: 3444
# Enable the use of SAN extensions to match users with certificates
san_extensions: true
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Additional steps when authenticating against an LDAP server
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = YAML.load <<-EOS
main:
# snip...
# Enable smart card authentication against the LDAP server. Valid values
# are "false", "optional", and "required".
smartcard_auth: optional
# If your LDAP server is Active Directory, you can configure these two fields.
# Specify which field contains certificate information, 'altSecurityIdentities' by default
smartcard_ad_cert_field: altSecurityIdentities
# Specify format of certificate information. Valid values are:
# principal_name, rfc822_name, issuer_and_subject, subject, issuer_and_serial_number
smartcard_ad_cert_format: issuer_and_serial_number
EOS
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
production:
ldap:
servers:
main:
# snip...
# Enable smart card authentication against the LDAP server. Valid values
# are "false", "optional", and "required".
smartcard_auth: optional
# If your LDAP server is Active Directory, you can configure these two fields.
# Specify which field contains certificate information, 'altSecurityIdentities' by default
smartcard_ad_cert_field: altSecurityIdentities
# Specify format of certificate information. Valid values are:
# principal_name, rfc822_name, issuer_and_subject, subject, issuer_and_serial_number
smartcard_ad_cert_format: issuer_and_serial_number
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Require browser session with smart card sign-in for Git access
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['smartcard_required_for_git_access'] = true
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
## Smart card authentication settings
smartcard:
# snip...
# Browser session with smart card sign-in is required for Git access
required_for_git_access: true
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
## Passwords for users created via smart card authentication
The [Generated passwords for users created through integrated authentication](../../security/passwords_for_integrated_authentication_methods.md) guide provides an overview of how GitLab generates and sets passwords for users created via smart card authentication.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Smart card authentication
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab supports authentication using smart cards.
## Existing password authentication
By default, existing users can continue to sign in with a username and password when smart card
authentication is enabled.
To force existing users to use only smart card authentication,
[disable username and password authentication](../settings/sign_in_restrictions.md#password-authentication-enabled).
## Authentication methods
GitLab supports two authentication methods:
- X.509 certificates with local databases.
- LDAP servers.
### Authentication against a local database with X.509 certificates
{{< details >}}
- Status: Experiment
{{< /details >}}
Smart cards with X.509 certificates can be used to authenticate with GitLab.
To use a smart card with an X.509 certificate to authenticate against a local
database with GitLab, `CN` and `emailAddress` must be defined in the
certificate. For example:
```plaintext
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 12856475246677808609 (0xb26b601ecdd555e1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=Random Corp Ltd, CN=Random Corp
Validity
Not Before: Oct 30 12:00:00 2018 GMT
Not After : Oct 30 12:00:00 2019 GMT
Subject: CN=Gitlab User, emailAddress=gitlab-user@example.com
```
### Authentication against a local database with X.509 certificates and SAN extension
{{< details >}}
- Status: Experiment
{{< /details >}}
Smart cards with X.509 certificates using SAN extensions can be used to authenticate
with GitLab.
To use a smart card with an X.509 certificate to authenticate against a local
database with GitLab:
- At least one of the `subjectAltName` (SAN) extensions
must define the user identity (`email`) within the GitLab instance (`URI`).
- The `URI` must match `Gitlab.config.host.gitlab`.
- If your certificate contains only **one** SAN email entry, you don't need to
add or modify it to match the `email` with the `URI`.
For example:
```plaintext
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 12856475246677808609 (0xb26b601ecdd555e1)
Signature Algorithm: sha256WithRSAEncryption
Issuer: O=Random Corp Ltd, CN=Random Corp
Validity
Not Before: Oct 30 12:00:00 2018 GMT
Not After : Oct 30 12:00:00 2019 GMT
...
X509v3 extensions:
X509v3 Key Usage:
Key Encipherment, Data Encipherment
X509v3 Extended Key Usage:
TLS Web Server Authentication
X509v3 Subject Alternative Name:
email:gitlab-user@example.com, URI:http://gitlab.example.com/
```
### Authentication against an LDAP server
{{< details >}}
- Status: Experiment
{{< /details >}}
GitLab implements a standard way of certificate matching following
[RFC4523](https://www.rfc-editor.org/rfc/rfc4523). It uses the
`certificateExactMatch` certificate matching rule against the `userCertificate`
attribute. As a prerequisite, you must use an LDAP server that:
- Supports the `certificateExactMatch` matching rule.
- Has the certificate stored in the `userCertificate` attribute.
### Authentication against an Active Directory LDAP server
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/328074) in GitLab 16.9.
- [Added](https://gitlab.com/gitlab-org/gitlab/-/issues/514025) `reverse_issuer_and_subject` and `reverse_issuer_and_serial_number` formats in GitLab 17.11.
{{< /history >}}
Active Directory does not support the `certificateExactMatch` rule or the `userCertificate` attribute. Most tools for certificate-based authentication such as smart cards use the `altSecurityIdentities` attribute, which can contain multiple certificates for each user. The data in the field must match [one of the formats Microsoft recommends](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-certificate-based-authentication-certificateuserids#supported-patterns-for-certificate-user-ids).
Use the following attributes to customize the field GitLab checks and the format for certificate data:
- `smartcard_ad_cert_field` - specify the name of the field to search. This can be any attribute on a user object.
- `smartcard_ad_cert_format` - specify the format of the information gathered from the certificate. This format must be one of the following values. The most common is
`issuer_and_serial_number` to match the behavior of non-Active Directory LDAP servers.
| `smartcard_ad_cert_format` | Example data |
| -------------------------- | ------------------------------------------------------------ |
| `principal_name` | `X509:<PN>alice@example.com` |
| `rfc822_name` | `X509:<RFC822>bob@example.com` |
| `subject` | `X509:<S>DC=com,DC=example,OU=UserAccounts,CN=dennis` |
| `issuer_and_serial_number` | `X509:<I>DC=com,DC=example,CN=CONTOSO-DC-CA<SR>1181914561` |
| `issuer_and_subject` | `X509:<I>DC=com,DC=example,CN=EXAMPLE-DC-CA<S>DC=com,DC=example,OU=UserAccounts,CN=cynthia` |
| `reverse_issuer_and_serial_number` | `X509:<I>CN=CONTOSO-DC-CA,DC=example,DC=com<SR>1181914561` |
| `reverse_issuer_and_subject` | `X509:<I>CN=EXAMPLE-DC-CA,DC=example,DC=com<S>DC=com,DC=example,OU=UserAccounts,CN=cynthia` |
For `issuer_and_serial_number`, the `<SR>` portion is in reverse-byte-order, with the least-significant byte first. For more information, see [how to map a user to a certificate using the altSecurityIdentities attribute](https://learn.microsoft.com/en-us/archive/blogs/spatdsg/howto-map-a-user-to-a-certificate-via-all-the-methods-available-in-the-altsecurityidentities-attribute).
The reverse issuer formats sort the issuer string from the smallest unit to the largest. Some
Active Directory servers store certificates in this format.
{{< alert type="note" >}}
If no `smartcard_ad_cert_format` is specified, but an LDAP server is configured with `active_directory: true` and smart cards enabled, GitLab defaults to the behavior of 16.8 and earlier, and uses `certificateExactMatch` on the `userCertificate` attribute.
{{< /alert >}}
### Authentication against Entra ID Domain Services
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/328074) in GitLab 16.9.
{{< /history >}}
[Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/fundamentals/whatis), formerly known as Azure Active Directory, provides a cloud-based directory for companies and organizations. [Entra Domain Services](https://learn.microsoft.com/en-us/entra/identity/domain-services/overview) provides a secure read-only LDAP interface to the directory, but only exposes a limited subset of the fields Entra ID has.
Entra ID uses the `CertificateUserIds` field to manage client certificates for users, but this field is not exposed in LDAP / Entra ID Domain Services. With a cloud-only setup, it is not possible for GitLab to authenticate users' smart cards using LDAP.
In a hybrid on-premise and cloud environment, entities are synced between the on-premise Active Directory controller and the cloud Entra ID using [Entra Connect](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-azure-ad-connect-v2). If you are [syncing your `altSecurityIdentities` attribute to `certificateUserIds` in Entra ID using Entra ID Connect](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-certificate-based-authentication-certificateuserids#update-certificateuserids-using-microsoft-entra-connect), you can expose this data in LDAP / Entra ID Domain Services so it can be authenticated by GitLab:
1. Add a rule to Entra ID Connect to sync the `altSecurityIdentities` to an additional attribute in Entra ID.
1. Enable that extra attribute as an [extension attribute in Entra ID Domain Services](https://learn.microsoft.com/en-us/entra/identity/domain-services/concepts-custom-attributes).
1. Configure the `smartcard_ad_cert_field` field in GitLab to use this extension attribute.
## Configure GitLab for smart card authentication
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Allow smart card authentication
gitlab_rails['smartcard_enabled'] = true
# Path to a file containing a CA certificate
gitlab_rails['smartcard_ca_file'] = "/etc/ssl/certs/CA.pem"
# Host and port where the client side certificate is requested by the
# webserver (NGINX/Apache)
gitlab_rails['smartcard_client_certificate_required_host'] = "smartcard.example.com"
gitlab_rails['smartcard_client_certificate_required_port'] = 3444
```
{{< alert type="note" >}}
Assign a value to at least one of the following variables:
`gitlab_rails['smartcard_client_certificate_required_host']` or
`gitlab_rails['smartcard_client_certificate_required_port']`.
{{< /alert >}}
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Configure NGINX to request a client side certificate
In NGINX configuration, an **additional** server context must be defined with
the same configuration except:
- The additional NGINX server context must be configured to run on a different
port:
```plaintext
listen *:3444 ssl;
```
- It can also be configured to run on a different hostname:
```plaintext
listen smartcard.example.com:443 ssl;
```
- The additional NGINX server context must be configured to require the client
side certificate:
```plaintext
ssl_verify_depth 2;
ssl_client_certificate /etc/ssl/certs/CA.pem;
ssl_verify_client on;
```
- The additional NGINX server context must be configured to forward the client
side certificate:
```plaintext
proxy_set_header X-SSL-Client-Certificate $ssl_client_escaped_cert;
```
For example, the following is an example server context in an NGINX
configuration file (such as in `/etc/nginx/sites-available/gitlab-ssl`):
```plaintext
server {
listen smartcard.example.com:3443 ssl;
# certificate for configuring SSL
ssl_certificate /path/to/example.com.crt;
ssl_certificate_key /path/to/example.com.key;
ssl_verify_depth 2;
# CA certificate for client side certificate verification
ssl_client_certificate /etc/ssl/certs/CA.pem;
ssl_verify_client on;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-SSL-Client-Certificate $ssl_client_escaped_cert;
proxy_read_timeout 300;
proxy_pass http://gitlab-workhorse;
}
}
```
1. Edit `config/gitlab.yml`:
```yaml
## Smart card authentication settings
smartcard:
# Allow smart card authentication
enabled: true
# Path to a file containing a CA certificate
ca_file: '/etc/ssl/certs/CA.pem'
# Host and port where the client side certificate is requested by the
# webserver (NGINX/Apache)
client_certificate_required_host: smartcard.example.com
client_certificate_required_port: 3443
```
{{< alert type="note" >}}
Assign a value to at least one of the following variables:
`client_certificate_required_host` or `client_certificate_required_port`.
{{< /alert >}}
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Additional steps when using SAN extensions
For Linux package installations:
1. Add to `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['smartcard_san_extensions'] = true
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Add the `san_extensions` line to `config/gitlab.yml` within the smart card section:
```yaml
smartcard:
enabled: true
ca_file: '/etc/ssl/certs/CA.pem'
client_certificate_required_port: 3444
# Enable the use of SAN extensions to match users with certificates
san_extensions: true
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Additional steps when authenticating against an LDAP server
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = YAML.load <<-EOS
main:
# snip...
# Enable smart card authentication against the LDAP server. Valid values
# are "false", "optional", and "required".
smartcard_auth: optional
# If your LDAP server is Active Directory, you can configure these two fields.
# Specify which field contains certificate information, 'altSecurityIdentities' by default
smartcard_ad_cert_field: altSecurityIdentities
# Specify format of certificate information. Valid values are:
# principal_name, rfc822_name, issuer_and_subject, subject, issuer_and_serial_number
smartcard_ad_cert_format: issuer_and_serial_number
EOS
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
production:
ldap:
servers:
main:
# snip...
# Enable smart card authentication against the LDAP server. Valid values
# are "false", "optional", and "required".
smartcard_auth: optional
# If your LDAP server is Active Directory, you can configure these two fields.
# Specify which field contains certificate information, 'altSecurityIdentities' by default
smartcard_ad_cert_field: altSecurityIdentities
# Specify format of certificate information. Valid values are:
# principal_name, rfc822_name, issuer_and_subject, subject, issuer_and_serial_number
smartcard_ad_cert_format: issuer_and_serial_number
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
### Require browser session with smart card sign-in for Git access
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['smartcard_required_for_git_access'] = true
```
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation)
GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
## Smart card authentication settings
smartcard:
# snip...
# Browser session with smart card sign-in is required for Git access
required_for_git_access: true
```
1. Save the file and [restart](../restart_gitlab.md#self-compiled-installations)
GitLab for the changes to take effect.
## Passwords for users created via smart card authentication
The [Generated passwords for users created through integrated authentication](../../security/passwords_for_integrated_authentication_methods.md) guide provides an overview of how GitLab generates and sets passwords for users created via smart card authentication.
|
https://docs.gitlab.com/administration/jwt
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/jwt.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
jwt.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use JWT as an authentication provider
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To enable the JWT OmniAuth provider, you must register your application with JWT.
JWT provides you with a secret key for you to use.
1. On your GitLab server, open the configuration file.
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `jwt` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{ name: "jwt",
label: "Provider name", # optional label for login button, defaults to "Jwt"
args: {
secret: "YOUR_APP_SECRET",
algorithm: "HS256", # Supported algorithms: "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512"
uid_claim: "email",
required_claims: ["name", "email"],
info_map: { name: "name", email: "email" },
auth_url: "https://example.com/",
valid_within: 3600 # 1 hour
}
}
]
```
For self-compiled installations:
```yaml
- { name: 'jwt',
label: 'Provider name', # optional label for login button, defaults to "Jwt"
args: {
secret: 'YOUR_APP_SECRET',
algorithm: 'HS256', # Supported algorithms: 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512'
uid_claim: 'email',
required_claims: ['name', 'email'],
info_map: { name: 'name', email: 'email' },
auth_url: 'https://example.com/',
valid_within: 3600 # 1 hour
}
}
```
{{< alert type="note" >}}
For more information on each configuration option refer to
the [OmniAuth JWT usage documentation](https://github.com/mbleigh/omniauth-jwt#usage).
{{< /alert >}}
{{< alert type="warning" >}}
Incorrectly configuring these settings can result in an insecure instance.
{{< /alert >}}
1. Change `YOUR_APP_SECRET` to the client secret and set `auth_url` to your redirect URL.
1. Save the configuration file.
1. For changes to take effect, if you:
- Used the Linux package to install GitLab, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- Self-compiled your GitLab installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign in page there should now be a JWT icon below the regular sign in form.
Select the icon to begin the authentication process. JWT asks the user to
sign in and authorize the GitLab application. If everything goes well, the user
is redirected to GitLab and signed in.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use JWT as an authentication provider
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To enable the JWT OmniAuth provider, you must register your application with JWT.
JWT provides you with a secret key for you to use.
1. On your GitLab server, open the configuration file.
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `jwt` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{ name: "jwt",
label: "Provider name", # optional label for login button, defaults to "Jwt"
args: {
secret: "YOUR_APP_SECRET",
algorithm: "HS256", # Supported algorithms: "RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512"
uid_claim: "email",
required_claims: ["name", "email"],
info_map: { name: "name", email: "email" },
auth_url: "https://example.com/",
valid_within: 3600 # 1 hour
}
}
]
```
For self-compiled installations:
```yaml
- { name: 'jwt',
label: 'Provider name', # optional label for login button, defaults to "Jwt"
args: {
secret: 'YOUR_APP_SECRET',
algorithm: 'HS256', # Supported algorithms: 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512'
uid_claim: 'email',
required_claims: ['name', 'email'],
info_map: { name: 'name', email: 'email' },
auth_url: 'https://example.com/',
valid_within: 3600 # 1 hour
}
}
```
{{< alert type="note" >}}
For more information on each configuration option refer to
the [OmniAuth JWT usage documentation](https://github.com/mbleigh/omniauth-jwt#usage).
{{< /alert >}}
{{< alert type="warning" >}}
Incorrectly configuring these settings can result in an insecure instance.
{{< /alert >}}
1. Change `YOUR_APP_SECRET` to the client secret and set `auth_url` to your redirect URL.
1. Save the configuration file.
1. For changes to take effect, if you:
- Used the Linux package to install GitLab, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- Self-compiled your GitLab installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign in page there should now be a JWT icon below the regular sign in form.
Select the icon to begin the authentication process. JWT asks the user to
sign in and authorize the GitLab application. If everything goes well, the user
is redirected to GitLab and signed in.
|
https://docs.gitlab.com/administration/atlassian
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/atlassian.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
atlassian.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use Atlassian as an OAuth 2.0 authentication provider
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To enable the Atlassian OmniAuth provider for passwordless authentication you must register an application with Atlassian.
## Atlassian application registration
1. Go to the [Atlassian developer console](https://developer.atlassian.com/console/myapps/) and sign-in with the Atlassian
account to administer the application.
1. Select **Create a new app**.
1. Choose an App Name, such as 'GitLab', and select **Create**.
1. Note the `Client ID` and `Secret` for the [GitLab configuration](#gitlab-configuration) steps.
1. On the left sidebar under **APIS AND FEATURES**, select **OAuth 2.0 (3LO)**.
1. Enter the GitLab callback URL using the format `https://gitlab.example.com/users/auth/atlassian_oauth2/callback` and select **Save changes**.
1. Select **+ Add** in the left sidebar under **APIS AND FEATURES**.
1. Select **Add** for **Jira platform REST API** and then **Configure**.
1. Select **Add** next to the following scopes:
- **View Jira issue data**
- **View user profiles**
- **Create and manage issues**
## GitLab configuration
1. On your GitLab server, open the configuration file:
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
sudo -u git -H editor /home/git/gitlab/config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `atlassian_oauth2` as a single sign-on provider. This enables
Just-In-Time account provisioning for users who do not have an existing
GitLab account.
1. Add the provider configuration for Atlassian:
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "atlassian_oauth2",
# label: "Provider name", # optional label for login button, defaults to "Atlassian"
app_id: "<your_client_id>",
app_secret: "<your_client_secret>",
args: { scope: "offline_access read:jira-user read:jira-work", prompt: "consent" }
}
]
```
For self-compiled installations:
```yaml
- { name: "atlassian_oauth2",
# label: "Provider name", # optional label for login button, defaults to "Atlassian"
app_id: "<your_client_id>",
app_secret: "<your_client_secret>",
args: { scope: "offline_access read:jira-user read:jira-work", prompt: "consent" }
}
```
1. Change `<your_client_id>` and `<your_client_secret>` to the Client credentials you received during [application registration](#atlassian-application-registration).
1. Save the configuration file.
1. For the changes to take effect:
- If you installed using the Linux package, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- If you self-compiled your installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign-in page there should now be an Atlassian icon below the regular sign in form. Select the icon to begin the authentication process.
If everything goes right, the user is signed in to GitLab using their Atlassian credentials.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use Atlassian as an OAuth 2.0 authentication provider
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To enable the Atlassian OmniAuth provider for passwordless authentication you must register an application with Atlassian.
## Atlassian application registration
1. Go to the [Atlassian developer console](https://developer.atlassian.com/console/myapps/) and sign-in with the Atlassian
account to administer the application.
1. Select **Create a new app**.
1. Choose an App Name, such as 'GitLab', and select **Create**.
1. Note the `Client ID` and `Secret` for the [GitLab configuration](#gitlab-configuration) steps.
1. On the left sidebar under **APIS AND FEATURES**, select **OAuth 2.0 (3LO)**.
1. Enter the GitLab callback URL using the format `https://gitlab.example.com/users/auth/atlassian_oauth2/callback` and select **Save changes**.
1. Select **+ Add** in the left sidebar under **APIS AND FEATURES**.
1. Select **Add** for **Jira platform REST API** and then **Configure**.
1. Select **Add** next to the following scopes:
- **View Jira issue data**
- **View user profiles**
- **Create and manage issues**
## GitLab configuration
1. On your GitLab server, open the configuration file:
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
sudo -u git -H editor /home/git/gitlab/config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `atlassian_oauth2` as a single sign-on provider. This enables
Just-In-Time account provisioning for users who do not have an existing
GitLab account.
1. Add the provider configuration for Atlassian:
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "atlassian_oauth2",
# label: "Provider name", # optional label for login button, defaults to "Atlassian"
app_id: "<your_client_id>",
app_secret: "<your_client_secret>",
args: { scope: "offline_access read:jira-user read:jira-work", prompt: "consent" }
}
]
```
For self-compiled installations:
```yaml
- { name: "atlassian_oauth2",
# label: "Provider name", # optional label for login button, defaults to "Atlassian"
app_id: "<your_client_id>",
app_secret: "<your_client_secret>",
args: { scope: "offline_access read:jira-user read:jira-work", prompt: "consent" }
}
```
1. Change `<your_client_id>` and `<your_client_secret>` to the Client credentials you received during [application registration](#atlassian-application-registration).
1. Save the configuration file.
1. For the changes to take effect:
- If you installed using the Linux package, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- If you self-compiled your installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign-in page there should now be an Atlassian icon below the regular sign in form. Select the icon to begin the authentication process.
If everything goes right, the user is signed in to GitLab using their Atlassian credentials.
|
https://docs.gitlab.com/administration/oidc
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/oidc.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
oidc.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use OpenID Connect as an authentication provider
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can use GitLab as a client application with [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html)
as an OmniAuth provider.
To enable the OpenID Connect OmniAuth provider, you must register your application
with an OpenID Connect provider.
The OpenID Connect provider provides you with a client's details and secret for you to use.
1. On your GitLab server, open the configuration file.
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `openid_connect` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Provider name", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback"
}
}
}
]
```
For Linux package installations with multiple identity providers:
```ruby
{ 'name' => 'openid_connect',
'label' => '...',
'icon' => '...',
'args' => {
'name' => 'openid_connect',
'strategy_class': 'OmniAuth::Strategies::OpenIDConnect',
'scope' => ['openid', 'profile', 'email'],
'discovery' => true,
'response_type' => 'code',
'issuer' => 'https://...',
'client_auth_method' => 'query',
'uid_field' => '...',
'client_options' => {
`identifier`: "<your_oidc_client_id>",
`secret`: "<your_oidc_client_secret>",
'redirect_uri' => 'https://.../users/auth/openid_connect/callback'
}
}
},
{ 'name' => 'openid_connect_2fa',
'label' => '...',
'icon' => '...',
'args' => {
'name' => 'openid_connect_2fa',
'strategy_class': 'OmniAuth::Strategies::OpenIDConnect',
'scope' => ['openid', 'profile', 'email'],
'discovery' => true,
'response_type' => 'code',
'issuer' => 'https://...',
'client_auth_method' => 'query',
'uid_field' => '...',
'client_options' => {
...
'redirect_uri' => 'https://.../users/auth/openid_connect_2fa/callback'
}
}
}
```
For self-compiled installations:
```yaml
- { name: 'openid_connect', # do not change this parameter
label: 'Provider name', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback'
}
}
}
```
{{< alert type="note" >}}
For more information on each configuration option, refer to the [OmniAuth OpenID Connect usage documentation](https://github.com/omniauth/omniauth_openid_connect#usage) and [OpenID Connect Core 1.0 specification](https://openid.net/specs/openid-connect-core-1_0.html).
{{< /alert >}}
1. For the provider configuration, change the values for the provider to match your
OpenID Connect client setup. Use the following as a guide:
- `<your_oidc_label>` is the label that appears on the login page.
- `<custom_provider_icon>` (optional) is the icon that appears on the login page.
Icons for the major social login platforms are built into GitLab,
but you can override these icons by specifying this parameter. GitLab accepts both
local paths and absolute URLs.
GitLab includes icons for most major social login platforms,
but you can override these icons by specifying an external URL or
an absolute or relative path to your own icon file.
- For local absolute paths, configure the provider settings as `icon: <path>/<to>/<your-icon>`.
- Store the icon file in `/opt/gitlab/embedded/service/gitlab-rails/public/<path>/<to>/<your-icon>`.
- Access the icon file at `https://gitlab.example/<path>/<to>/<your-icon>`.
- For local relative paths, configure the provider settings as `icon: <your-icon>`.
- Store the icon file in `/opt/gitlab/embedded/service/gitlab-rails/public/images/<your-icon>`.
- Access the icon file at `https://gitlab.example.com/images/<your-icon>`.
- `<your_oidc_url>` (optional) is the URL that points to the OpenID Connect
provider (for example, `https://example.com/auth/realms/your-realm`).
If this value is not provided, the URL is constructed from `client_options`
in the following format: `<client_options.scheme>://<client_options.host>:<client_options.port>`.
- If `discovery` is set to `true`, the OpenID Connect provider attempts to automatically
discover the client options using `<your_oidc_url>/.well-known/openid-configuration`.
Defaults to `false`.
- `client_auth_method` (optional) specifies the method used for authenticating
the client with the OpenID Connect provider.
- Supported values are:
- `basic` - HTTP Basic Authentication.
- `jwt_bearer` - JWT-based authentication (private key and client secret signing).
- `mtls` - Mutual TLS or X.509 certificate validation.
- Any other value posts the client ID and secret in the request body.
- If not specified, this value defaults to `basic`.
- `<uid_field>` (optional) is the field name from `user_info.raw_attributes`
that defines the value for `uid` (for example, `preferred_username`).
If you do not provide this value, or the field with the configured value is missing
from the `user_info.raw_attributes` details, `uid` uses the `sub` field.
- `send_scope_to_token_endpoint` is `true` by default, so the `scope` parameter
is usually included in requests to the token endpoint.
However, if your OpenID Connect provider does not accept the `scope` parameter
in such requests, set this to `false`.
- `pkce` (optional): Enable [Proof Key for Code Exchange](https://www.rfc-editor.org/rfc/rfc7636). Available in [GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/109557).
- `client_options` are the OpenID Connect client-specific options. Specifically:
- `identifier` is the client identifier as configured in the OpenID Connect service provider.
- `secret` is the client secret as configured in the OpenID Connect service provider. For example,
[OmniAuth OpenID Connect](https://github.com/omniauth/omniauth_openid_connect) requires this. If the service provider doesn't require a secret,
provide any value and it is ignored.
- `redirect_uri` is the GitLab URL to redirect the user to after successful login
(for example, `http://example.com/users/auth/openid_connect/callback`).
- `end_session_endpoint` (optional) is the URL to the endpoint that ends the
session. You can provide this URL if auto-discovery is disabled or unsuccessful.
- The following `client_options` are optional unless auto-discovery is disabled or unsuccessful:
- `authorization_endpoint` is the URL to the endpoint that authorizes the end user.
- `token_endpoint` is the URL to the endpoint that provides Access Token.
- `userinfo_endpoint` is the URL to the endpoint that provides the user information.
- `jwks_uri` is the URL to the endpoint where the Token signer publishes its keys.
1. Save the configuration file.
1. For changes to take effect, if you:
- Used the Linux package to install GitLab, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- Self-compiled your GitLab installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign in page, you have an OpenID Connect option below the regular sign in form.
Select this option to begin the authentication process. The OpenID Connect provider
asks you to sign in and authorize the GitLab application if confirmation is required
by the client. You are redirected to GitLab and signed in.
## Example configurations
The following configurations illustrate how to set up OpenID with
different providers when using the Linux package installation.
### Configure Google
See the [Google documentation](https://developers.google.com/identity/openid-connect/openid-connect)
for more details:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Google OpenID", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://accounts.google.com",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR PROJECT CLIENT ID>",
secret: "<YOUR PROJECT CLIENT SECRET>",
redirect_uri: "https://example.com/users/auth/openid_connect/callback",
}
}
}
]
```
### Configure Microsoft Azure
The OpenID Connect (OIDC) protocol for Microsoft Azure uses the [Microsoft identity platform (v2) endpoints](https://learn.microsoft.com/en-us/previous-versions/azure/active-directory/azuread-dev/azure-ad-endpoint-comparison).
To get started, sign in to the [Azure Portal](https://portal.azure.com). For your app,
you need the following information:
- A tenant ID. You may already have one. For more information, see the
[Microsoft Azure Tenant](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-create-new-tenant) documentation.
- A client ID and a client secret. Follow the instructions in the
[Microsoft Quickstart Register an Application](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app) documentation
to obtain the tenant ID, client ID, and client secret for your app.
When you register a Microsoft Azure application, you must grant API permissions to allow GitLab to
retrieve required details. You must provide at least the `openid`, `profile`, and `email` permissions.
For more information, see the [Microsoft documentation for configuring app permissions for a web API](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-configure-app-access-web-apis#add-permissions-to-access-microsoft-graph).
{{< alert type="note" >}}
All accounts provisioned by Azure must have an email address defined. If an email address is not defined, Azure assigns a randomly generated address. If you've configured [domain sign-up restrictions](../settings/sign_up_restrictions.md#allow-or-deny-sign-ups-using-specific-email-domains), this random address might prevent the account from being created.
{{< /alert >}}
Example configuration block for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
Microsoft has documented how its platform works with [the OIDC protocol](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc).
#### Microsoft Entra custom signing keys
If your application has custom signing keys because you use the
[SAML claims-mapping feature](https://learn.microsoft.com/en-us/entra/identity-platform/saml-claims-customization),
you must configure the OpenID provider in the following ways:
- Disable OpenID Connect Discovery by omitting `args.discovery`, or setting it to `false`.
- In `client_options`, specify the following:
- A `jwks_uri` with the `appid` query parameter: `https://login.microsoftonline.com/<YOUR-TENANT-ID>/discovery/v2.0/keys?appid=<YOUR APP CLIENT ID>`.
- `end_session_endpoint`.
- `authorization_endpoint`.
- `userinfo_endpoint`.
Example configuration for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "basic",
discovery: false,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback",
end_session_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/logout",
authorization_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/authorize",
token_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/token",
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
jwks_uri: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/discovery/v2.0/keys?appid=<YOUR APP CLIENT ID>"
}
}
}
]
```
If you see authentication failures with a `KidNotFound` message, this
is probably because of a missing or incorrect `appid` query
parameter. GitLab raises that error if the ID token returned by
Microsoft cannot be validated with the keys provided by the `jwks_uri`
endpoint.
For more information, see the [Microsoft Entra documentation on validating tokens](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#validate-tokens).
#### Migrate to Generic OpenID Connect configuration
You can migrate to the Generic OpenID Connect configuration from both `azure_activedirectory_v2` and `azure_oauth2`.
First, set the `uid_field`. Both the `uid_field` and the `sub` claim that you can select as a `uid_field` vary depending on the provider. Signing in without setting the `uid_field` results in additional identities being created within GitLab that have to be manually modified:
| Provider | `uid_field` | Supporting information |
|-----------------------------------------------------------------------------------------------------------------|-------|-----------------------------------------------------------------------|
| [`omniauth-azure-oauth2`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/vendor/gems/omniauth-azure-oauth2) | `sub` | Additional attributes `oid` and `tid` are offered within the `info` object. |
| [`omniauth-azure-activedirectory-v2`](https://github.com/RIPAGlobal/omniauth-azure-activedirectory-v2/) | `oid` | You must configure `oid` as `uid_field` when migrating. |
| [`omniauth_openid_connect`](https://github.com/omniauth/omniauth_openid_connect/) | `sub` | Specify `uid_field` to use another field. |
To migrate to the Generic OpenID Connect configuration, you must update the configuration.
For Linux package installations, update the configuration as follows:
{{< tabs >}}
{{< tab title="Azure OAuth 2.0" >}}
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "azure_oauth2",
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "azure_oauth2", # this matches the existing azure_oauth2 provider name, and only the strategy_class immediately below configures OpenID Connect
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "sub",
send_scope_to_token_endpoint: "false",
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/azure_oauth2/callback"
}
}
}
]
```
{{< /tab >}}
{{< tab title="Azure Active Directory v2" >}}
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "azure_activedirectory_v2",
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "azure_activedirectory_v2",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "oid",
send_scope_to_token_endpoint: "false",
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/azure_activedirectory_v2/callback"
}
}
}
]
```
{{< /tab >}}
{{< /tabs >}}
For Helm installations:
Add the [provider's configuration](https://docs.gitlab.com/charts/charts/globals.html#providers) in a YAML file (for example, `provider.yaml`):
{{< tabs >}}
{{< tab title="Azure OAuth 2.0" >}}
```ruby
{
"name": "azure_oauth2",
"args": {
"name": "azure_oauth2",
"strategy_class": "OmniAuth::Strategies::OpenIDConnect",
"scope": [
"openid",
"profile",
"email"
],
"response_type": "code",
"issuer": "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
"client_auth_method": "query",
"discovery": true,
"uid_field": "sub",
"send_scope_to_token_endpoint": false,
"client_options": {
"identifier": "<YOUR APP CLIENT ID>",
"secret": "<YOUR APP CLIENT SECRET>",
"redirect_uri": "https://gitlab.example.com/users/auth/azure_oauth2/callback"
}
}
}
```
{{< /tab >}}
{{< tab title="Azure Active Directory v2" >}}
```ruby
{
"name": "azure_activedirectory_v2",
"args": {
"name": "azure_activedirectory_v2",
"strategy_class": "OmniAuth::Strategies::OpenIDConnect",
"scope": [
"openid",
"profile",
"email"
],
"response_type": "code",
"issuer": "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
"client_auth_method": "query",
"discovery": true,
"uid_field": "sub",
"send_scope_to_token_endpoint": false,
"client_options": {
"identifier": "<YOUR APP CLIENT ID>",
"secret": "<YOUR APP CLIENT SECRET>",
"redirect_uri": "https://gitlab.example.com/users/auth/activedirectory_v2/callback"
}
}
}
```
{{< /tab >}}
{{< /tabs >}}
As you migrate from `azure_oauth2` to `omniauth_openid_connect` as part of upgrading to GitLab 17.0 or later, the `sub` claim value set for your organization can vary. `azure_oauth2` uses Microsoft V1 endpoint while `azure_activedirectory_v2` and `omniauth_openid_connect` both use Microsoft V2 endpoint with a common `sub` value.
- **For users with an email address in Entra ID**, to allow falling back to email address and updating the user's identity,
configure the following:
- In a Linux package installation, [`omniauth_auto_link_user`](../../integration/omniauth.md#link-existing-users-to-omniauth-users).
- In a Helm installation, [`autoLinkUser`](https://docs.gitlab.com/charts/charts/globals.html#omniauth).
- **For users with no email address**, administrators must take one of the following actions:
- Set up another authentication method or enable sign-in using GitLab username and password. The user can then sign in and link their Azure identity manually using their profile.
- Implement OpenID Connect as a new provider alongside the existing `azure_oauth2` so the user can sign in through OAuth2, and link their OpenID Connect identity (similar to the previous method). This method would also work for users with email addresses, as long as `auto_link_user` is enabled.
- Update `extern_uid` manually. To do this, use the [API or Rails console](../../integration/omniauth.md#change-apps-or-configuration) to update the `extern_uid` for each user.
This method may be required if the instance has already been upgraded to 17.0 or later, and users have attempted to sign in.
{{< alert type="note" >}}
`azure_oauth2` might have used Entra ID's `upn` claim as the email address, if the `email` claim was missing or blank when provisioning GitLab accounts.
{{< /alert >}}
### Configure Microsoft Azure Active Directory B2C
GitLab requires special
configuration to work with [Azure Active Directory B2C](https://learn.microsoft.com/en-us/azure/active-directory-b2c/overview). To get started, sign in to the [Azure Portal](https://portal.azure.com).
For your app, you need the following information from Azure:
- A tenant ID. You may already have one. For more information, review the
[Microsoft Azure Tenant](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-create-new-tenant) documentation.
- A client ID and a client secret. Follow the instructions in the
[Microsoft tutorial](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=app-reg-ga) documentation to obtain the
client ID and client secret for your app.
- The user flow or policy name. Follow the instructions in the [Microsoft tutorial](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-user-flow).
Configure the app:
1. Set the app `Redirect URI`. For example, If your GitLab domain is `gitlab.example.com`,
set the app `Redirect URI` to `https://gitlab.example.com/users/auth/openid_connect/callback`.
1. [Enable the ID tokens](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=app-reg-ga#enable-id-token-implicit-grant).
1. Add the following API permissions to the app:
- `openid`
- `offline_access`
#### Configure custom policies
Azure B2C [offers two ways of defining the business logic for logging in a user](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview):
- [User flows](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview#user-flows)
- [Custom policies](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview#custom-policies)
Custom policies are required because standard Azure B2C user flows
[do not send the OpenID `email` claim](https://github.com/MicrosoftDocs/azure-docs/issues/16566).
Therefore, the standard user flows do not work with the
[`allow_single_sign_on` or `auto_link_user` parameters](../../integration/omniauth.md#configure-common-settings).
With a standard Azure B2C policy, GitLab cannot create a new account or
link to an existing account with an email address.
First, [create a custom policy](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy).
The Microsoft instructions use `SocialAndLocalAccounts` in the [custom policy starter pack](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#custom-policy-starter-pack),
but `LocalAccounts` authenticates against local Active Directory accounts. Before you [upload the polices](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#upload-the-policies), do the following:
1. To export the `email` claim, modify the `SignUpOrSignin.xml`. Replace the following line:
```xml
<OutputClaim ClaimTypeReferenceId="email" />
```
with:
```xml
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="email" />
```
1. For OIDC discovery to work with B2C, configure the policy with an issuer compatible with the
[OIDC specification](https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.4.3).
See the [token compatibility settings](https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-tokens?pivots=b2c-custom-policy#token-compatibility-settings).
In `TrustFrameworkBase.xml` under `JwtIssuer`, set `IssuanceClaimPattern` to `AuthorityWithTfp`:
```xml
<ClaimsProvider>
<DisplayName>Token Issuer</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="JwtIssuer">
<DisplayName>JWT Issuer</DisplayName>
<Protocol Name="None" />
<OutputTokenFormat>JWT</OutputTokenFormat>
<Metadata>
<Item Key="IssuanceClaimPattern">AuthorityWithTfp</Item>
...
```
1. [Upload the policy](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#upload-the-policies). Overwrite
the existing files if you are updating an existing policy.
1. To determine the issuer URL, use the sign-in policy. The issuer URL is in the form:
```markdown
https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/<YOUR-SIGN-IN-POLICY-NAME>/v2.0/
```
The policy name is lowercase in the URL. For example, `B2C_1A_signup_signin`
policy appears as `b2c_1a_signup_sigin`.
Ensure you include the trailing forward slash.
1. Verify the operation of the OIDC discovery URL and issuer URL and append
`.well-known/openid-configuration` to the issuer URL:
```markdown
https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/<YOUR-SIGN-IN-POLICY-NAME>/v2.0/.well-known/openid-configuration
```
For example, if `domain` is `example.b2clogin.com` and tenant ID is
`fc40c736-476c-4da1-b489-ee48cee84386`, you can use `curl` and `jq` to extract the issuer:
```shell
$ curl --silent "https://example.b2clogin.com/tfp/fc40c736-476c-4da1-b489-ee48cee84386/b2c_1a_signup_signin/v2.0/.well-known/openid-configuration" | jq .issuer
"https://example.b2clogin.com/tfp/fc40c736-476c-4da1-b489-ee48cee84386/b2c_1a_signup_signin/v2.0/"
```
1. Configure the issuer URL with the custom policy used for `signup_signin`. For example, this is
the configuration with a custom policy for `b2c_1a_signup_signin` for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure B2C OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid"],
response_mode: "query",
response_type: "id_token",
issuer: "https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/b2c_1a_signup_signin/v2.0/",
client_auth_method: "query",
discovery: true,
send_scope_to_token_endpoint: true,
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}]
```
#### Troubleshooting Azure B2C
- Ensure all occurrences of `yourtenant.onmicrosoft.com`, `ProxyIdentityExperienceFrameworkAppId`, and `IdentityExperienceFrameworkAppId` match your B2C tenant hostname and
the respective client IDs in the XML policy files.
- Add `https://jwt.ms` as a redirect URI to the app, and use the [custom policy tester](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#test-the-custom-policy).
Ensure the payload includes `email` that matches the user's email access.
- After you enable the custom policy, users might see `Invalid username or password`
after they try to sign in. This might be a configuration issue with the `IdentityExperienceFramework`
app. See [this Microsoft comment](https://learn.microsoft.com/en-us/answers/questions/50355/unable-to-sign-on-using-custom-policy?childtoview=122370#comment-122370) that suggests you check that the app manifest
contains these settings:
- `"accessTokenAcceptedVersion": null`
- `"signInAudience": "AzureADMyOrg"`
This configuration corresponds with the `Supported account types` setting used when
creating the `IdentityExperienceFramework` app.
### Configure Keycloak
GitLab works with OpenID providers that use HTTPS. Although you can set up a
Keycloak server that uses HTTP, GitLab can only communicate with a Keycloak server
that uses HTTPS.
Configure Keycloak to use public key encryption algorithms (for example,
RSA256 or RSA512) instead of symmetric key encryption algorithms (for example,
HS256 or HS358) to sign tokens. Public key encryption algorithms are:
- Easier to configure.
- More secure because leaking the private key has severe security consequences.
1. Open the Keycloak administration console.
1. Select **Realm Settings > Tokens > Default Signature Algorithm**.
1. Configure the signature algorithm.
Example configuration block for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Keycloak", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://keycloak.example.com/realms/myrealm",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
#### Configure Keycloak with a symmetric key algorithm
{{< alert type="warning" >}}
The following instructions are included for completeness, but only use symmetric key
encryption if absolutely necessary.
{{< /alert >}}
To use symmetric key encryption:
1. Extract the secret key from the Keycloak database. Keycloak does not expose this
value in the web interface. The client secret seen in the web interface is the
OAuth 2.0 client secret, which is different from the secret used to sign JSON Web Tokens.
For example, if you use PostgreSQL as the backend database for Keycloak:
- Sign in to the database console.
- Run the following SQL query to extract the key:
```sql
$ psql -U keycloak
psql (13.3 (Debian 13.3-1.pgdg100+1))
Type "help" for help.
keycloak=# SELECT c.name, value FROM component_config CC INNER JOIN component C ON(CC.component_id = C.id) WHERE C.realm_id = 'master' and provider_id = 'hmac-generated' AND CC.name = 'secret';
-[ RECORD 1 ]---------------------------------------------------------------------------------
name | hmac-generated
value | lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62-sqGc8drp3XW-wr93zru8PFsQokHZZuJJbaUXvmiOftCZM3C4KW3-g
-[ RECORD 2 ]---------------------------------------------------------------------------------
name | fallback-HS384
value | UfVqmIs--U61UYsRH-NYBH3_mlluLONpg_zN7CXEwkJcO9xdRNlzZfmfDLPtf2xSTMvqu08R2VhLr-8G-oZ47A
```
In this example, there are two private keys: one for HS256 (`hmac-generated`)
and another for HS384 (`fallback-HS384`). We use the first `value` to configure GitLab.
1. Convert `value` to standard base64. As discussed in the [**Invalid signature with HS256 token** post](https://keycloak.discourse.group/t/invalid-signature-with-hs256-token/3228/9),
`value` is encoded in the [**Base 64 Encoding with URL and Filename Safe Alphabet** section](https://datatracker.ietf.org/doc/html/rfc4648#section-5) of RFC 4648.
This must be converted to [standard base64 as defined in RFC 2045](https://datatracker.ietf.org/doc/html/rfc2045).
The following Ruby script does this:
```ruby
require 'base64'
value = "lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62-sqGc8drp3XW-wr93zru8PFsQokHZZuJJbaUXvmiOftCZM3C4KW3-g"
Base64.encode64(Base64.urlsafe_decode64(value))
```
This results in the following value:
```markdown
lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62+sqGc8drp3XW+wr93zru8PFsQokH\nZZuJJbaUXvmiOftCZM3C4KW3+g==\n
```
1. Specify this base64-encoded secret in `jwt_secret_base64`. For example:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Keycloak", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://keycloak.example.com/auth/realms/myrealm",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
jwt_secret_base64: "<YOUR BASE64-ENCODED SECRET>",
pkce: true,
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
If you see a `JSON::JWS::VerificationFailed` error,
you have specified the wrong secret.
### Casdoor
GitLab works with OpenID providers that use HTTPS. Use HTTPS to connect to GitLab
through OpenID with Casdoor.
For your app, complete the following steps on Casdoor:
1. Get a client ID and a client secret.
1. Add your GitLab redirect URL. For example, if your GitLab domain is `gitlab.example.com`,
ensure the Casdoor app has the following
`Redirect URI`: `https://gitlab.example.com/users/auth/openid_connect/callback`.
See the [Casdoor documentation](https://casdoor.org/docs/integration/ruby/gitlab/) for more details.
Example configuration for Linux package installations (file path: `/etc/gitlab/gitlab.rb`):
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Casdoor", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://<CASDOOR_HOSTNAME>",
client_auth_method: "query",
discovery: true,
uid_field: "sub",
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
Example configuration for self-compiled installations (file path: `config/gitlab.yml`):
```yaml
- { name: 'openid_connect', # do not change this parameter
label: 'Casdoor', # optional label for login button, defaults to "Openid Connect"
args: {
name: 'openid_connect',
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: 'https://<CASDOOR_HOSTNAME>',
discovery: true,
client_auth_method: 'query',
uid_field: 'sub',
client_options: {
identifier: '<YOUR CLIENT ID>',
secret: '<YOUR CLIENT SECRET>',
redirect_uri: 'https://gitlab.example.com/users/auth/openid_connect/callback'
}
}
}
```
## Configure multiple OpenID Connect providers
You can configure your application to use multiple OpenID Connect (OIDC) providers. You do this by explicitly setting the `strategy_class` in your configuration file.
You should do this in either of the following scenarios:
- [Migrating to the OpenID Connect protocol](#migrate-to-generic-openid-connect-configuration).
- Offering different levels of authentication.
The following example configurations show how to offer different levels of authentication, one option with 2FA and one without 2FA.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback"
}
}
},
{
name: "openid_connect_2fa",
label: "Provider name 2FA", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect_2fa",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect_2fa/callback"
}
}
}
]
```
For self-compiled installations:
```yaml
- { name: 'openid_connect',
label: 'Provider name', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect',
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback'
}
}
}
- { name: 'openid_connect_2fa',
label: 'Provider name 2FA', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect_2fa',
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect_2fa/callback'
}
}
}
```
In this use case, you might want to synchronize the `extern_uid` across the
different providers based on an existing known identifier in your
corporate directory.
To do this, you set the `uid_field`. The following example code shows how to
do this:
```python
def sync_missing_provider(self, user: User, extern_uid: str)
existing_identities = []
for identity in user.identities:
existing_identities.append(identity.get("provider"))
local_extern_uid = extern_uid.lower()
for provider in ("openid_connect_2fa", "openid_connect"):
identity = [
identity
for identity in user.identities
if identity.get("provider") == provider
and identity.get("extern_uid").lower() != local_extern_uid
]
if provider not in existing_identities or identity:
if identity and identity[0].get("extern_uid") != "":
logger.error(f"Found different identity for provider {provider} for user {user.id}")
continue
else:
logger.info(f"Add identity 'provider': {provider}, 'extern_uid': {extern_uid} for user {user.id}")
user.provider = provider
user.extern_uid = extern_uid
user = self.save_user(user)
return user
```
For more information, see the [GitLab API user method documentation](https://python-gitlab.readthedocs.io/en/stable/gl_objects/users.html#examples).
## Configure users based on OIDC group membership
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/209898) in GitLab 15.10.
{{< /history >}}
You can configure OIDC group membership to:
- Require users to be members of a certain group.
- Assign users [external](../external_users.md), administrator or
[auditor](../auditor_users.md) roles based on group membership.
GitLab checks these groups on each sign in and updates user attributes as necessary.
This feature **does not** allow you to automatically add users to GitLab
[groups](../../user/group/_index.md).
### Required groups
Your identity provider (IdP) must pass group information to GitLab in the OIDC response. To use this
response to require users to be members of a certain group, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group membership is required to sign in, using the `required_groups` setting.
If you do not set `required_groups` or leave the setting empty, any user authenticated by the IdP through OIDC can use GitLab.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
required_groups: ["Developer"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
required_groups: ["Developer"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### External groups
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to identify users as [external users](../external_users.md)
based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships should identify a user as an
[external user](../external_users.md), using the
`external_groups` setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
external_groups: ["Freelancer"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
external_groups: ["Freelancer"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Auditor groups
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to assign users as auditors based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships grant the user auditor access, using the `auditor_groups`
setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email","groups"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
auditor_groups: ["Auditor"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email','groups'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
auditor_groups: ["Auditor"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Administrator groups
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to assign users as administrator based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships grant the user administrator access, using the
`admin_groups` setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
admin_groups: ["Admin"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
admin_groups: ["Admin"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Configure a custom duration for ID Tokens
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/377654) in GitLab 17.8.
{{< /history >}}
By default, GitLab ID tokens expire after 120 seconds.
To configure a custom duration for your ID tokens:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['oidc_provider_openid_id_token_expire_in_seconds'] = 3600
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
oidc_provider:
openid_id_token_expire_in_seconds: 3600
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
## Step-up authentication for Admin Mode
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/474650) in GitLab 17.11 [with a flag](../feature_flags/_index.md) named `omniauth_step_up_auth_for_admin_mode`. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
In some cases, default authentication methods don't sufficiently protect critical resources or
high-risk actions. Step-up authentication adds an extra authentication layer for privileged actions
or sensitive operations, such as accessing the Admin area.
With step-up authentication, users must provide additional credentials before they can access
certain features or perform specific actions. These additional methods can include methods such
as two-factor authentication (2FA), biometric authentication, or one-time passwords (OTP).
The OIDC standard includes authentication context class references (`ACR`). The `ACR` concept
helps configure and implement step-up authentication for different scenarios, such as Admin Mode.
This feature is an [experiment](../../policy/development_stages_support.md) and subject to change without notice. This feature is not ready for production use. If you want to use this feature, you should test outside of production first.
### Enable step-up authentication for Admin Mode
To enable step-up authentication for Admin Mode:
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication for an specific OmniAuth provider.
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"], # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
# The `id_token` field defines the claims that must be included with the token.
# You can specify claims in one or both of the `required` or `included` fields.
# The token must include matching values for every claim you define in these fields.
id_token: {
# The `required` field defines key-value pairs that must be included with the ID token.
# The values must match exactly what is defined.
# In this example, the 'acr' (Authentication Context Class Reference) claim
# must have the value 'gold' to pass the step-up authentication challenge.
# This ensures a specific level of authentication assurance.
required: {
acr: 'gold'
},
# The `included` field also defines key-value pairs that must be included with the ID token.
# Multiple accepted values can be defined in an array. If an array is not used, the value must match exactly.
# In this example, the 'amr' (Authentication Method References) claim
# must have a value of either 'mfa' or 'fpt' to pass the step-up authentication challenge.
# This is useful for scenarios where the user must provide additional authentication factors.
included: {
amr: ['mfa', 'fpt']
},
},
# The `params` field defines any additional parameters that are sent during the authentication process.
# In this example, the `claims` parameter is added to the authorization request and instructs the
# identity provider to include an 'acr' claim with the value 'gold' in the ID token.
# The 'essential: true' indicates that this claim is required for successful authentication.
params: {
claims: {
id_token: {
acr: {
essential: true,
values: ['gold']
}
}
}
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
{{< alert type="note" >}}
Although OIDC is standardized, different Identity Providers (IdPs) might have unique requirements.
The `params` setting allows a flexible hash to define necessary parameters for step-up authentication.
These values can vary based on the requirements for each IdP.
{{< /alert >}}
#### Enable step-up authentication for Admin Mode using Keycloak
Keycloak supports step-up authentication by defining levels of authentication and custom browser login flows.
To configure step-up authentication for Admin Mode in GitLab using Keycloak:
1. [Configure Keycloak](#configure-keycloak) in GitLab.
1. Follow the steps in the Keycloak documentation to [create a browser login flow with step-up authentication in Keycloak](https://www.keycloak.org/docs/latest/server_admin/#_step-up-flow).
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication in the Keycloak OIDC provider configuration.
Keycloak defines two different authentication levels: `silver` and `gold`. The following example
uses `gold` to represent the increased security level.
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Keycloak',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"] # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
id_token: {
# In this example, the 'acr' claim must have the value 'gold' that is also defined in the Keycloak documentation.
required: {
acr: 'gold'
}
},
params: {
claims: { id_token: { acr: { essential: true, values: ['gold'] } } }
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
#### Enable step-up authentication for Admin Mode using Microsoft Entra ID
Microsoft Entra ID (formerly known as Azure Active Directory) supports step-up authentication
through [conditional access authentication context](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context).
You should work with your Microsoft Entra ID administrators to define the correct configuration.
Consider the following aspects:
- Authentication context IDs are requested through the `acrs` claim only, not through the ID token
claim `acr` used for other identity providers.
- Authentication context IDs use fixed values from `c1` to `c99`, each representing a specific
authentication context with conditional access policies.
- By default, Microsoft Entra ID does not include the `acrs` claim in the ID token. To enable this, you must
[configure optional claims](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims?tabs=appui#configure-optional-claims-in-your-application).
- When step-up authentication succeeds, the response returns the [`acrs` claim](https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference#payload-claims) as a JSON array
of strings. For example: `acrs: ["c1", "c2", "c3"]`.
To configure step-up authentication for Admin Mode in GitLab using Microsoft Entra ID:
1. [Configure Microsoft Entra ID](#configure-microsoft-azure) in GitLab.
1. Follow the steps in the Microsoft Entra ID documentation to
[define conditional access authentication contexts in Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context).
1. In Microsoft Entra ID, define [the optional claim `acrs` to include in the ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken).
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication in the Microsoft Entra ID provider configuration:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Azure OIDC',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"] # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
id_token: {
# In this example, the Microsoft Entra ID administrators have definded `c20`
# as the authentication context ID with the desired security level and
# an optional claim `acrs` to be included in the ID token.
# The `included` field declares that the id token claim `acrs` must include the value `c20`.
included: {
acrs: ["c20"],
},
},
params: {
claims: {
id_token: {
acrs: { essential: true, value: 'c20' }
}
},
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
## Troubleshooting
1. Ensure `discovery` is set to `true`. If you set it to `false`, you must
specify all the URLs and keys required to make OpenID work.
1. Check your system clock to ensure the time is synchronized properly.
1. As mentioned in [the OmniAuth OpenID Connect documentation](https://github.com/omniauth/omniauth_openid_connect),
make sure `issuer` corresponds to the base URL of the Discovery URL. For
example, `https://accounts.google.com` is used for the URL
`https://accounts.google.com/.well-known/openid-configuration`.
1. The OpenID Connect client uses HTTP Basic Authentication to send the
OAuth 2.0 access token if `client_auth_method` is not defined or if set to `basic`.
If you see 401 errors when retrieving the `userinfo` endpoint, check
your OpenID web server configuration. For example, for
[`oauth2-server-php`](https://github.com/bshaffer/oauth2-server-php), you may have to
[add a configuration parameter to Apache](https://github.com/bshaffer/oauth2-server-php/issues/926#issuecomment-387502778).
1. **Step-up authentication only**: Ensure that any parameters defined in
`step_up_auth => admin_mode => params` are also defined in `args => allow_authorize_params`.
This includes the parameters in the request query parameters used to
redirect to the IdP authorization endpoint.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use OpenID Connect as an authentication provider
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can use GitLab as a client application with [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html)
as an OmniAuth provider.
To enable the OpenID Connect OmniAuth provider, you must register your application
with an OpenID Connect provider.
The OpenID Connect provider provides you with a client's details and secret for you to use.
1. On your GitLab server, open the configuration file.
For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
For self-compiled installations:
```shell
cd /home/git/gitlab
sudo -u git -H editor config/gitlab.yml
```
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `openid_connect` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. Add the provider configuration.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Provider name", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback"
}
}
}
]
```
For Linux package installations with multiple identity providers:
```ruby
{ 'name' => 'openid_connect',
'label' => '...',
'icon' => '...',
'args' => {
'name' => 'openid_connect',
'strategy_class': 'OmniAuth::Strategies::OpenIDConnect',
'scope' => ['openid', 'profile', 'email'],
'discovery' => true,
'response_type' => 'code',
'issuer' => 'https://...',
'client_auth_method' => 'query',
'uid_field' => '...',
'client_options' => {
`identifier`: "<your_oidc_client_id>",
`secret`: "<your_oidc_client_secret>",
'redirect_uri' => 'https://.../users/auth/openid_connect/callback'
}
}
},
{ 'name' => 'openid_connect_2fa',
'label' => '...',
'icon' => '...',
'args' => {
'name' => 'openid_connect_2fa',
'strategy_class': 'OmniAuth::Strategies::OpenIDConnect',
'scope' => ['openid', 'profile', 'email'],
'discovery' => true,
'response_type' => 'code',
'issuer' => 'https://...',
'client_auth_method' => 'query',
'uid_field' => '...',
'client_options' => {
...
'redirect_uri' => 'https://.../users/auth/openid_connect_2fa/callback'
}
}
}
```
For self-compiled installations:
```yaml
- { name: 'openid_connect', # do not change this parameter
label: 'Provider name', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback'
}
}
}
```
{{< alert type="note" >}}
For more information on each configuration option, refer to the [OmniAuth OpenID Connect usage documentation](https://github.com/omniauth/omniauth_openid_connect#usage) and [OpenID Connect Core 1.0 specification](https://openid.net/specs/openid-connect-core-1_0.html).
{{< /alert >}}
1. For the provider configuration, change the values for the provider to match your
OpenID Connect client setup. Use the following as a guide:
- `<your_oidc_label>` is the label that appears on the login page.
- `<custom_provider_icon>` (optional) is the icon that appears on the login page.
Icons for the major social login platforms are built into GitLab,
but you can override these icons by specifying this parameter. GitLab accepts both
local paths and absolute URLs.
GitLab includes icons for most major social login platforms,
but you can override these icons by specifying an external URL or
an absolute or relative path to your own icon file.
- For local absolute paths, configure the provider settings as `icon: <path>/<to>/<your-icon>`.
- Store the icon file in `/opt/gitlab/embedded/service/gitlab-rails/public/<path>/<to>/<your-icon>`.
- Access the icon file at `https://gitlab.example/<path>/<to>/<your-icon>`.
- For local relative paths, configure the provider settings as `icon: <your-icon>`.
- Store the icon file in `/opt/gitlab/embedded/service/gitlab-rails/public/images/<your-icon>`.
- Access the icon file at `https://gitlab.example.com/images/<your-icon>`.
- `<your_oidc_url>` (optional) is the URL that points to the OpenID Connect
provider (for example, `https://example.com/auth/realms/your-realm`).
If this value is not provided, the URL is constructed from `client_options`
in the following format: `<client_options.scheme>://<client_options.host>:<client_options.port>`.
- If `discovery` is set to `true`, the OpenID Connect provider attempts to automatically
discover the client options using `<your_oidc_url>/.well-known/openid-configuration`.
Defaults to `false`.
- `client_auth_method` (optional) specifies the method used for authenticating
the client with the OpenID Connect provider.
- Supported values are:
- `basic` - HTTP Basic Authentication.
- `jwt_bearer` - JWT-based authentication (private key and client secret signing).
- `mtls` - Mutual TLS or X.509 certificate validation.
- Any other value posts the client ID and secret in the request body.
- If not specified, this value defaults to `basic`.
- `<uid_field>` (optional) is the field name from `user_info.raw_attributes`
that defines the value for `uid` (for example, `preferred_username`).
If you do not provide this value, or the field with the configured value is missing
from the `user_info.raw_attributes` details, `uid` uses the `sub` field.
- `send_scope_to_token_endpoint` is `true` by default, so the `scope` parameter
is usually included in requests to the token endpoint.
However, if your OpenID Connect provider does not accept the `scope` parameter
in such requests, set this to `false`.
- `pkce` (optional): Enable [Proof Key for Code Exchange](https://www.rfc-editor.org/rfc/rfc7636). Available in [GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/109557).
- `client_options` are the OpenID Connect client-specific options. Specifically:
- `identifier` is the client identifier as configured in the OpenID Connect service provider.
- `secret` is the client secret as configured in the OpenID Connect service provider. For example,
[OmniAuth OpenID Connect](https://github.com/omniauth/omniauth_openid_connect) requires this. If the service provider doesn't require a secret,
provide any value and it is ignored.
- `redirect_uri` is the GitLab URL to redirect the user to after successful login
(for example, `http://example.com/users/auth/openid_connect/callback`).
- `end_session_endpoint` (optional) is the URL to the endpoint that ends the
session. You can provide this URL if auto-discovery is disabled or unsuccessful.
- The following `client_options` are optional unless auto-discovery is disabled or unsuccessful:
- `authorization_endpoint` is the URL to the endpoint that authorizes the end user.
- `token_endpoint` is the URL to the endpoint that provides Access Token.
- `userinfo_endpoint` is the URL to the endpoint that provides the user information.
- `jwks_uri` is the URL to the endpoint where the Token signer publishes its keys.
1. Save the configuration file.
1. For changes to take effect, if you:
- Used the Linux package to install GitLab, [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation).
- Self-compiled your GitLab installation, [restart GitLab](../restart_gitlab.md#self-compiled-installations).
On the sign in page, you have an OpenID Connect option below the regular sign in form.
Select this option to begin the authentication process. The OpenID Connect provider
asks you to sign in and authorize the GitLab application if confirmation is required
by the client. You are redirected to GitLab and signed in.
## Example configurations
The following configurations illustrate how to set up OpenID with
different providers when using the Linux package installation.
### Configure Google
See the [Google documentation](https://developers.google.com/identity/openid-connect/openid-connect)
for more details:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Google OpenID", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://accounts.google.com",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR PROJECT CLIENT ID>",
secret: "<YOUR PROJECT CLIENT SECRET>",
redirect_uri: "https://example.com/users/auth/openid_connect/callback",
}
}
}
]
```
### Configure Microsoft Azure
The OpenID Connect (OIDC) protocol for Microsoft Azure uses the [Microsoft identity platform (v2) endpoints](https://learn.microsoft.com/en-us/previous-versions/azure/active-directory/azuread-dev/azure-ad-endpoint-comparison).
To get started, sign in to the [Azure Portal](https://portal.azure.com). For your app,
you need the following information:
- A tenant ID. You may already have one. For more information, see the
[Microsoft Azure Tenant](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-create-new-tenant) documentation.
- A client ID and a client secret. Follow the instructions in the
[Microsoft Quickstart Register an Application](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app) documentation
to obtain the tenant ID, client ID, and client secret for your app.
When you register a Microsoft Azure application, you must grant API permissions to allow GitLab to
retrieve required details. You must provide at least the `openid`, `profile`, and `email` permissions.
For more information, see the [Microsoft documentation for configuring app permissions for a web API](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-configure-app-access-web-apis#add-permissions-to-access-microsoft-graph).
{{< alert type="note" >}}
All accounts provisioned by Azure must have an email address defined. If an email address is not defined, Azure assigns a randomly generated address. If you've configured [domain sign-up restrictions](../settings/sign_up_restrictions.md#allow-or-deny-sign-ups-using-specific-email-domains), this random address might prevent the account from being created.
{{< /alert >}}
Example configuration block for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
Microsoft has documented how its platform works with [the OIDC protocol](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc).
#### Microsoft Entra custom signing keys
If your application has custom signing keys because you use the
[SAML claims-mapping feature](https://learn.microsoft.com/en-us/entra/identity-platform/saml-claims-customization),
you must configure the OpenID provider in the following ways:
- Disable OpenID Connect Discovery by omitting `args.discovery`, or setting it to `false`.
- In `client_options`, specify the following:
- A `jwks_uri` with the `appid` query parameter: `https://login.microsoftonline.com/<YOUR-TENANT-ID>/discovery/v2.0/keys?appid=<YOUR APP CLIENT ID>`.
- `end_session_endpoint`.
- `authorization_endpoint`.
- `userinfo_endpoint`.
Example configuration for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "basic",
discovery: false,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback",
end_session_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/logout",
authorization_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/authorize",
token_endpoint: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/oauth2/v2.0/token",
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
jwks_uri: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/discovery/v2.0/keys?appid=<YOUR APP CLIENT ID>"
}
}
}
]
```
If you see authentication failures with a `KidNotFound` message, this
is probably because of a missing or incorrect `appid` query
parameter. GitLab raises that error if the ID token returned by
Microsoft cannot be validated with the keys provided by the `jwks_uri`
endpoint.
For more information, see the [Microsoft Entra documentation on validating tokens](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#validate-tokens).
#### Migrate to Generic OpenID Connect configuration
You can migrate to the Generic OpenID Connect configuration from both `azure_activedirectory_v2` and `azure_oauth2`.
First, set the `uid_field`. Both the `uid_field` and the `sub` claim that you can select as a `uid_field` vary depending on the provider. Signing in without setting the `uid_field` results in additional identities being created within GitLab that have to be manually modified:
| Provider | `uid_field` | Supporting information |
|-----------------------------------------------------------------------------------------------------------------|-------|-----------------------------------------------------------------------|
| [`omniauth-azure-oauth2`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/vendor/gems/omniauth-azure-oauth2) | `sub` | Additional attributes `oid` and `tid` are offered within the `info` object. |
| [`omniauth-azure-activedirectory-v2`](https://github.com/RIPAGlobal/omniauth-azure-activedirectory-v2/) | `oid` | You must configure `oid` as `uid_field` when migrating. |
| [`omniauth_openid_connect`](https://github.com/omniauth/omniauth_openid_connect/) | `sub` | Specify `uid_field` to use another field. |
To migrate to the Generic OpenID Connect configuration, you must update the configuration.
For Linux package installations, update the configuration as follows:
{{< tabs >}}
{{< tab title="Azure OAuth 2.0" >}}
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "azure_oauth2",
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "azure_oauth2", # this matches the existing azure_oauth2 provider name, and only the strategy_class immediately below configures OpenID Connect
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "sub",
send_scope_to_token_endpoint: "false",
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/azure_oauth2/callback"
}
}
}
]
```
{{< /tab >}}
{{< tab title="Azure Active Directory v2" >}}
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "azure_activedirectory_v2",
label: "Azure OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "azure_activedirectory_v2",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
client_auth_method: "query",
discovery: true,
uid_field: "oid",
send_scope_to_token_endpoint: "false",
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/azure_activedirectory_v2/callback"
}
}
}
]
```
{{< /tab >}}
{{< /tabs >}}
For Helm installations:
Add the [provider's configuration](https://docs.gitlab.com/charts/charts/globals.html#providers) in a YAML file (for example, `provider.yaml`):
{{< tabs >}}
{{< tab title="Azure OAuth 2.0" >}}
```ruby
{
"name": "azure_oauth2",
"args": {
"name": "azure_oauth2",
"strategy_class": "OmniAuth::Strategies::OpenIDConnect",
"scope": [
"openid",
"profile",
"email"
],
"response_type": "code",
"issuer": "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
"client_auth_method": "query",
"discovery": true,
"uid_field": "sub",
"send_scope_to_token_endpoint": false,
"client_options": {
"identifier": "<YOUR APP CLIENT ID>",
"secret": "<YOUR APP CLIENT SECRET>",
"redirect_uri": "https://gitlab.example.com/users/auth/azure_oauth2/callback"
}
}
}
```
{{< /tab >}}
{{< tab title="Azure Active Directory v2" >}}
```ruby
{
"name": "azure_activedirectory_v2",
"args": {
"name": "azure_activedirectory_v2",
"strategy_class": "OmniAuth::Strategies::OpenIDConnect",
"scope": [
"openid",
"profile",
"email"
],
"response_type": "code",
"issuer": "https://login.microsoftonline.com/<YOUR-TENANT-ID>/v2.0",
"client_auth_method": "query",
"discovery": true,
"uid_field": "sub",
"send_scope_to_token_endpoint": false,
"client_options": {
"identifier": "<YOUR APP CLIENT ID>",
"secret": "<YOUR APP CLIENT SECRET>",
"redirect_uri": "https://gitlab.example.com/users/auth/activedirectory_v2/callback"
}
}
}
```
{{< /tab >}}
{{< /tabs >}}
As you migrate from `azure_oauth2` to `omniauth_openid_connect` as part of upgrading to GitLab 17.0 or later, the `sub` claim value set for your organization can vary. `azure_oauth2` uses Microsoft V1 endpoint while `azure_activedirectory_v2` and `omniauth_openid_connect` both use Microsoft V2 endpoint with a common `sub` value.
- **For users with an email address in Entra ID**, to allow falling back to email address and updating the user's identity,
configure the following:
- In a Linux package installation, [`omniauth_auto_link_user`](../../integration/omniauth.md#link-existing-users-to-omniauth-users).
- In a Helm installation, [`autoLinkUser`](https://docs.gitlab.com/charts/charts/globals.html#omniauth).
- **For users with no email address**, administrators must take one of the following actions:
- Set up another authentication method or enable sign-in using GitLab username and password. The user can then sign in and link their Azure identity manually using their profile.
- Implement OpenID Connect as a new provider alongside the existing `azure_oauth2` so the user can sign in through OAuth2, and link their OpenID Connect identity (similar to the previous method). This method would also work for users with email addresses, as long as `auto_link_user` is enabled.
- Update `extern_uid` manually. To do this, use the [API or Rails console](../../integration/omniauth.md#change-apps-or-configuration) to update the `extern_uid` for each user.
This method may be required if the instance has already been upgraded to 17.0 or later, and users have attempted to sign in.
{{< alert type="note" >}}
`azure_oauth2` might have used Entra ID's `upn` claim as the email address, if the `email` claim was missing or blank when provisioning GitLab accounts.
{{< /alert >}}
### Configure Microsoft Azure Active Directory B2C
GitLab requires special
configuration to work with [Azure Active Directory B2C](https://learn.microsoft.com/en-us/azure/active-directory-b2c/overview). To get started, sign in to the [Azure Portal](https://portal.azure.com).
For your app, you need the following information from Azure:
- A tenant ID. You may already have one. For more information, review the
[Microsoft Azure Tenant](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-create-new-tenant) documentation.
- A client ID and a client secret. Follow the instructions in the
[Microsoft tutorial](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=app-reg-ga) documentation to obtain the
client ID and client secret for your app.
- The user flow or policy name. Follow the instructions in the [Microsoft tutorial](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-user-flow).
Configure the app:
1. Set the app `Redirect URI`. For example, If your GitLab domain is `gitlab.example.com`,
set the app `Redirect URI` to `https://gitlab.example.com/users/auth/openid_connect/callback`.
1. [Enable the ID tokens](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=app-reg-ga#enable-id-token-implicit-grant).
1. Add the following API permissions to the app:
- `openid`
- `offline_access`
#### Configure custom policies
Azure B2C [offers two ways of defining the business logic for logging in a user](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview):
- [User flows](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview#user-flows)
- [Custom policies](https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview#custom-policies)
Custom policies are required because standard Azure B2C user flows
[do not send the OpenID `email` claim](https://github.com/MicrosoftDocs/azure-docs/issues/16566).
Therefore, the standard user flows do not work with the
[`allow_single_sign_on` or `auto_link_user` parameters](../../integration/omniauth.md#configure-common-settings).
With a standard Azure B2C policy, GitLab cannot create a new account or
link to an existing account with an email address.
First, [create a custom policy](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy).
The Microsoft instructions use `SocialAndLocalAccounts` in the [custom policy starter pack](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#custom-policy-starter-pack),
but `LocalAccounts` authenticates against local Active Directory accounts. Before you [upload the polices](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#upload-the-policies), do the following:
1. To export the `email` claim, modify the `SignUpOrSignin.xml`. Replace the following line:
```xml
<OutputClaim ClaimTypeReferenceId="email" />
```
with:
```xml
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" PartnerClaimType="email" />
```
1. For OIDC discovery to work with B2C, configure the policy with an issuer compatible with the
[OIDC specification](https://openid.net/specs/openid-connect-discovery-1_0.html#rfc.section.4.3).
See the [token compatibility settings](https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-tokens?pivots=b2c-custom-policy#token-compatibility-settings).
In `TrustFrameworkBase.xml` under `JwtIssuer`, set `IssuanceClaimPattern` to `AuthorityWithTfp`:
```xml
<ClaimsProvider>
<DisplayName>Token Issuer</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="JwtIssuer">
<DisplayName>JWT Issuer</DisplayName>
<Protocol Name="None" />
<OutputTokenFormat>JWT</OutputTokenFormat>
<Metadata>
<Item Key="IssuanceClaimPattern">AuthorityWithTfp</Item>
...
```
1. [Upload the policy](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#upload-the-policies). Overwrite
the existing files if you are updating an existing policy.
1. To determine the issuer URL, use the sign-in policy. The issuer URL is in the form:
```markdown
https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/<YOUR-SIGN-IN-POLICY-NAME>/v2.0/
```
The policy name is lowercase in the URL. For example, `B2C_1A_signup_signin`
policy appears as `b2c_1a_signup_sigin`.
Ensure you include the trailing forward slash.
1. Verify the operation of the OIDC discovery URL and issuer URL and append
`.well-known/openid-configuration` to the issuer URL:
```markdown
https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/<YOUR-SIGN-IN-POLICY-NAME>/v2.0/.well-known/openid-configuration
```
For example, if `domain` is `example.b2clogin.com` and tenant ID is
`fc40c736-476c-4da1-b489-ee48cee84386`, you can use `curl` and `jq` to extract the issuer:
```shell
$ curl --silent "https://example.b2clogin.com/tfp/fc40c736-476c-4da1-b489-ee48cee84386/b2c_1a_signup_signin/v2.0/.well-known/openid-configuration" | jq .issuer
"https://example.b2clogin.com/tfp/fc40c736-476c-4da1-b489-ee48cee84386/b2c_1a_signup_signin/v2.0/"
```
1. Configure the issuer URL with the custom policy used for `signup_signin`. For example, this is
the configuration with a custom policy for `b2c_1a_signup_signin` for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Azure B2C OIDC", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid"],
response_mode: "query",
response_type: "id_token",
issuer: "https://<YOUR-DOMAIN>/tfp/<YOUR-TENANT-ID>/b2c_1a_signup_signin/v2.0/",
client_auth_method: "query",
discovery: true,
send_scope_to_token_endpoint: true,
pkce: true,
client_options: {
identifier: "<YOUR APP CLIENT ID>",
secret: "<YOUR APP CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}]
```
#### Troubleshooting Azure B2C
- Ensure all occurrences of `yourtenant.onmicrosoft.com`, `ProxyIdentityExperienceFrameworkAppId`, and `IdentityExperienceFrameworkAppId` match your B2C tenant hostname and
the respective client IDs in the XML policy files.
- Add `https://jwt.ms` as a redirect URI to the app, and use the [custom policy tester](https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows?pivots=b2c-custom-policy#test-the-custom-policy).
Ensure the payload includes `email` that matches the user's email access.
- After you enable the custom policy, users might see `Invalid username or password`
after they try to sign in. This might be a configuration issue with the `IdentityExperienceFramework`
app. See [this Microsoft comment](https://learn.microsoft.com/en-us/answers/questions/50355/unable-to-sign-on-using-custom-policy?childtoview=122370#comment-122370) that suggests you check that the app manifest
contains these settings:
- `"accessTokenAcceptedVersion": null`
- `"signInAudience": "AzureADMyOrg"`
This configuration corresponds with the `Supported account types` setting used when
creating the `IdentityExperienceFramework` app.
### Configure Keycloak
GitLab works with OpenID providers that use HTTPS. Although you can set up a
Keycloak server that uses HTTP, GitLab can only communicate with a Keycloak server
that uses HTTPS.
Configure Keycloak to use public key encryption algorithms (for example,
RSA256 or RSA512) instead of symmetric key encryption algorithms (for example,
HS256 or HS358) to sign tokens. Public key encryption algorithms are:
- Easier to configure.
- More secure because leaking the private key has severe security consequences.
1. Open the Keycloak administration console.
1. Select **Realm Settings > Tokens > Default Signature Algorithm**.
1. Configure the signature algorithm.
Example configuration block for Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Keycloak", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://keycloak.example.com/realms/myrealm",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
pkce: true,
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
#### Configure Keycloak with a symmetric key algorithm
{{< alert type="warning" >}}
The following instructions are included for completeness, but only use symmetric key
encryption if absolutely necessary.
{{< /alert >}}
To use symmetric key encryption:
1. Extract the secret key from the Keycloak database. Keycloak does not expose this
value in the web interface. The client secret seen in the web interface is the
OAuth 2.0 client secret, which is different from the secret used to sign JSON Web Tokens.
For example, if you use PostgreSQL as the backend database for Keycloak:
- Sign in to the database console.
- Run the following SQL query to extract the key:
```sql
$ psql -U keycloak
psql (13.3 (Debian 13.3-1.pgdg100+1))
Type "help" for help.
keycloak=# SELECT c.name, value FROM component_config CC INNER JOIN component C ON(CC.component_id = C.id) WHERE C.realm_id = 'master' and provider_id = 'hmac-generated' AND CC.name = 'secret';
-[ RECORD 1 ]---------------------------------------------------------------------------------
name | hmac-generated
value | lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62-sqGc8drp3XW-wr93zru8PFsQokHZZuJJbaUXvmiOftCZM3C4KW3-g
-[ RECORD 2 ]---------------------------------------------------------------------------------
name | fallback-HS384
value | UfVqmIs--U61UYsRH-NYBH3_mlluLONpg_zN7CXEwkJcO9xdRNlzZfmfDLPtf2xSTMvqu08R2VhLr-8G-oZ47A
```
In this example, there are two private keys: one for HS256 (`hmac-generated`)
and another for HS384 (`fallback-HS384`). We use the first `value` to configure GitLab.
1. Convert `value` to standard base64. As discussed in the [**Invalid signature with HS256 token** post](https://keycloak.discourse.group/t/invalid-signature-with-hs256-token/3228/9),
`value` is encoded in the [**Base 64 Encoding with URL and Filename Safe Alphabet** section](https://datatracker.ietf.org/doc/html/rfc4648#section-5) of RFC 4648.
This must be converted to [standard base64 as defined in RFC 2045](https://datatracker.ietf.org/doc/html/rfc2045).
The following Ruby script does this:
```ruby
require 'base64'
value = "lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62-sqGc8drp3XW-wr93zru8PFsQokHZZuJJbaUXvmiOftCZM3C4KW3-g"
Base64.encode64(Base64.urlsafe_decode64(value))
```
This results in the following value:
```markdown
lo6cqjD6Ika8pk7qc3fpFx9ysrhf7E62+sqGc8drp3XW+wr93zru8PFsQokH\nZZuJJbaUXvmiOftCZM3C4KW3+g==\n
```
1. Specify this base64-encoded secret in `jwt_secret_base64`. For example:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Keycloak", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://keycloak.example.com/auth/realms/myrealm",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
jwt_secret_base64: "<YOUR BASE64-ENCODED SECRET>",
pkce: true,
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
If you see a `JSON::JWS::VerificationFailed` error,
you have specified the wrong secret.
### Casdoor
GitLab works with OpenID providers that use HTTPS. Use HTTPS to connect to GitLab
through OpenID with Casdoor.
For your app, complete the following steps on Casdoor:
1. Get a client ID and a client secret.
1. Add your GitLab redirect URL. For example, if your GitLab domain is `gitlab.example.com`,
ensure the Casdoor app has the following
`Redirect URI`: `https://gitlab.example.com/users/auth/openid_connect/callback`.
See the [Casdoor documentation](https://casdoor.org/docs/integration/ruby/gitlab/) for more details.
Example configuration for Linux package installations (file path: `/etc/gitlab/gitlab.rb`):
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect", # do not change this parameter
label: "Casdoor", # optional label for login button, defaults to "Openid Connect"
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://<CASDOOR_HOSTNAME>",
client_auth_method: "query",
discovery: true,
uid_field: "sub",
client_options: {
identifier: "<YOUR CLIENT ID>",
secret: "<YOUR CLIENT SECRET>",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
```
Example configuration for self-compiled installations (file path: `config/gitlab.yml`):
```yaml
- { name: 'openid_connect', # do not change this parameter
label: 'Casdoor', # optional label for login button, defaults to "Openid Connect"
args: {
name: 'openid_connect',
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: 'https://<CASDOOR_HOSTNAME>',
discovery: true,
client_auth_method: 'query',
uid_field: 'sub',
client_options: {
identifier: '<YOUR CLIENT ID>',
secret: '<YOUR CLIENT SECRET>',
redirect_uri: 'https://gitlab.example.com/users/auth/openid_connect/callback'
}
}
}
```
## Configure multiple OpenID Connect providers
You can configure your application to use multiple OpenID Connect (OIDC) providers. You do this by explicitly setting the `strategy_class` in your configuration file.
You should do this in either of the following scenarios:
- [Migrating to the OpenID Connect protocol](#migrate-to-generic-openid-connect-configuration).
- Offering different levels of authentication.
The following example configurations show how to offer different levels of authentication, one option with 2FA and one without 2FA.
For Linux package installations:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback"
}
}
},
{
name: "openid_connect_2fa",
label: "Provider name 2FA", # optional label for login button, defaults to "Openid Connect"
icon: "<custom_provider_icon>",
args: {
name: "openid_connect_2fa",
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
send_scope_to_token_endpoint: "false",
pkce: true,
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect_2fa/callback"
}
}
}
]
```
For self-compiled installations:
```yaml
- { name: 'openid_connect',
label: 'Provider name', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect',
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback'
}
}
}
- { name: 'openid_connect_2fa',
label: 'Provider name 2FA', # optional label for login button, defaults to "Openid Connect"
icon: '<custom_provider_icon>',
args: {
name: 'openid_connect_2fa',
strategy_class: "OmniAuth::Strategies::OpenIDConnect",
scope: ['openid', 'profile', 'email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
send_scope_to_token_endpoint: false,
pkce: true,
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect_2fa/callback'
}
}
}
```
In this use case, you might want to synchronize the `extern_uid` across the
different providers based on an existing known identifier in your
corporate directory.
To do this, you set the `uid_field`. The following example code shows how to
do this:
```python
def sync_missing_provider(self, user: User, extern_uid: str)
existing_identities = []
for identity in user.identities:
existing_identities.append(identity.get("provider"))
local_extern_uid = extern_uid.lower()
for provider in ("openid_connect_2fa", "openid_connect"):
identity = [
identity
for identity in user.identities
if identity.get("provider") == provider
and identity.get("extern_uid").lower() != local_extern_uid
]
if provider not in existing_identities or identity:
if identity and identity[0].get("extern_uid") != "":
logger.error(f"Found different identity for provider {provider} for user {user.id}")
continue
else:
logger.info(f"Add identity 'provider': {provider}, 'extern_uid': {extern_uid} for user {user.id}")
user.provider = provider
user.extern_uid = extern_uid
user = self.save_user(user)
return user
```
For more information, see the [GitLab API user method documentation](https://python-gitlab.readthedocs.io/en/stable/gl_objects/users.html#examples).
## Configure users based on OIDC group membership
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/209898) in GitLab 15.10.
{{< /history >}}
You can configure OIDC group membership to:
- Require users to be members of a certain group.
- Assign users [external](../external_users.md), administrator or
[auditor](../auditor_users.md) roles based on group membership.
GitLab checks these groups on each sign in and updates user attributes as necessary.
This feature **does not** allow you to automatically add users to GitLab
[groups](../../user/group/_index.md).
### Required groups
Your identity provider (IdP) must pass group information to GitLab in the OIDC response. To use this
response to require users to be members of a certain group, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group membership is required to sign in, using the `required_groups` setting.
If you do not set `required_groups` or leave the setting empty, any user authenticated by the IdP through OIDC can use GitLab.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
required_groups: ["Developer"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
required_groups: ["Developer"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### External groups
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to identify users as [external users](../external_users.md)
based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships should identify a user as an
[external user](../external_users.md), using the
`external_groups` setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
external_groups: ["Freelancer"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
external_groups: ["Freelancer"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Auditor groups
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to assign users as auditors based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships grant the user auditor access, using the `auditor_groups`
setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email","groups"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
auditor_groups: ["Auditor"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email','groups'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
auditor_groups: ["Auditor"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Administrator groups
Your IdP must pass group information to GitLab in the OIDC response. To use this
response to assign users as administrator based on group membership, configure GitLab to identify:
- Where to look for the groups in the OIDC response, using the `groups_attribute` setting.
- Which group memberships grant the user administrator access, using the
`admin_groups` setting.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Provider name",
args: {
name: "openid_connect",
scope: ["openid","profile","email"],
response_type: "code",
issuer: "<your_oidc_url>",
discovery: true,
client_auth_method: "query",
uid_field: "<uid_field>",
client_options: {
identifier: "<your_oidc_client_id>",
secret: "<your_oidc_client_secret>",
redirect_uri: "<your_gitlab_url>/users/auth/openid_connect/callback",
gitlab: {
groups_attribute: "groups",
admin_groups: ["Admin"]
}
}
}
}
]
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation)
for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
scope: ['openid','profile','email'],
response_type: 'code',
issuer: '<your_oidc_url>',
discovery: true,
client_auth_method: 'query',
uid_field: '<uid_field>',
client_options: {
identifier: '<your_oidc_client_id>',
secret: '<your_oidc_client_secret>',
redirect_uri: '<your_gitlab_url>/users/auth/openid_connect/callback',
gitlab: {
groups_attribute: "groups",
admin_groups: ["Admin"]
}
}
}
}
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
### Configure a custom duration for ID Tokens
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/377654) in GitLab 17.8.
{{< /history >}}
By default, GitLab ID tokens expire after 120 seconds.
To configure a custom duration for your ID tokens:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['oidc_provider_openid_id_token_expire_in_seconds'] = 3600
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
oidc_provider:
openid_id_token_expire_in_seconds: 3600
```
1. Save the file and [reconfigure GitLab](../restart_gitlab.md#self-compiled-installations)
for the changes to take effect.
{{< /tab >}}
{{< /tabs >}}
## Step-up authentication for Admin Mode
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/474650) in GitLab 17.11 [with a flag](../feature_flags/_index.md) named `omniauth_step_up_auth_for_admin_mode`. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
In some cases, default authentication methods don't sufficiently protect critical resources or
high-risk actions. Step-up authentication adds an extra authentication layer for privileged actions
or sensitive operations, such as accessing the Admin area.
With step-up authentication, users must provide additional credentials before they can access
certain features or perform specific actions. These additional methods can include methods such
as two-factor authentication (2FA), biometric authentication, or one-time passwords (OTP).
The OIDC standard includes authentication context class references (`ACR`). The `ACR` concept
helps configure and implement step-up authentication for different scenarios, such as Admin Mode.
This feature is an [experiment](../../policy/development_stages_support.md) and subject to change without notice. This feature is not ready for production use. If you want to use this feature, you should test outside of production first.
### Enable step-up authentication for Admin Mode
To enable step-up authentication for Admin Mode:
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication for an specific OmniAuth provider.
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Provider name',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"], # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
# The `id_token` field defines the claims that must be included with the token.
# You can specify claims in one or both of the `required` or `included` fields.
# The token must include matching values for every claim you define in these fields.
id_token: {
# The `required` field defines key-value pairs that must be included with the ID token.
# The values must match exactly what is defined.
# In this example, the 'acr' (Authentication Context Class Reference) claim
# must have the value 'gold' to pass the step-up authentication challenge.
# This ensures a specific level of authentication assurance.
required: {
acr: 'gold'
},
# The `included` field also defines key-value pairs that must be included with the ID token.
# Multiple accepted values can be defined in an array. If an array is not used, the value must match exactly.
# In this example, the 'amr' (Authentication Method References) claim
# must have a value of either 'mfa' or 'fpt' to pass the step-up authentication challenge.
# This is useful for scenarios where the user must provide additional authentication factors.
included: {
amr: ['mfa', 'fpt']
},
},
# The `params` field defines any additional parameters that are sent during the authentication process.
# In this example, the `claims` parameter is added to the authorization request and instructs the
# identity provider to include an 'acr' claim with the value 'gold' in the ID token.
# The 'essential: true' indicates that this claim is required for successful authentication.
params: {
claims: {
id_token: {
acr: {
essential: true,
values: ['gold']
}
}
}
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
{{< alert type="note" >}}
Although OIDC is standardized, different Identity Providers (IdPs) might have unique requirements.
The `params` setting allows a flexible hash to define necessary parameters for step-up authentication.
These values can vary based on the requirements for each IdP.
{{< /alert >}}
#### Enable step-up authentication for Admin Mode using Keycloak
Keycloak supports step-up authentication by defining levels of authentication and custom browser login flows.
To configure step-up authentication for Admin Mode in GitLab using Keycloak:
1. [Configure Keycloak](#configure-keycloak) in GitLab.
1. Follow the steps in the Keycloak documentation to [create a browser login flow with step-up authentication in Keycloak](https://www.keycloak.org/docs/latest/server_admin/#_step-up-flow).
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication in the Keycloak OIDC provider configuration.
Keycloak defines two different authentication levels: `silver` and `gold`. The following example
uses `gold` to represent the increased security level.
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Keycloak',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"] # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
id_token: {
# In this example, the 'acr' claim must have the value 'gold' that is also defined in the Keycloak documentation.
required: {
acr: 'gold'
}
},
params: {
claims: { id_token: { acr: { essential: true, values: ['gold'] } } }
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
#### Enable step-up authentication for Admin Mode using Microsoft Entra ID
Microsoft Entra ID (formerly known as Azure Active Directory) supports step-up authentication
through [conditional access authentication context](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context).
You should work with your Microsoft Entra ID administrators to define the correct configuration.
Consider the following aspects:
- Authentication context IDs are requested through the `acrs` claim only, not through the ID token
claim `acr` used for other identity providers.
- Authentication context IDs use fixed values from `c1` to `c99`, each representing a specific
authentication context with conditional access policies.
- By default, Microsoft Entra ID does not include the `acrs` claim in the ID token. To enable this, you must
[configure optional claims](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims?tabs=appui#configure-optional-claims-in-your-application).
- When step-up authentication succeeds, the response returns the [`acrs` claim](https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference#payload-claims) as a JSON array
of strings. For example: `acrs: ["c1", "c2", "c3"]`.
To configure step-up authentication for Admin Mode in GitLab using Microsoft Entra ID:
1. [Configure Microsoft Entra ID](#configure-microsoft-azure) in GitLab.
1. Follow the steps in the Microsoft Entra ID documentation to
[define conditional access authentication contexts in Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context).
1. In Microsoft Entra ID, define [the optional claim `acrs` to include in the ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken).
1. Edit your GitLab configuration file (`gitlab.yml` or `/etc/gitlab/gitlab.rb`) to enable
step-up authentication in the Microsoft Entra ID provider configuration:
```yaml
production: &base
omniauth:
providers:
- { name: 'openid_connect',
label: 'Azure OIDC',
args: {
name: 'openid_connect',
# ...
allow_authorize_params: ["claims"] # Match this to the parameters defined in `step_up_auth => admin_mode => params`
},
step_up_auth: {
admin_mode: {
id_token: {
# In this example, the Microsoft Entra ID administrators have definded `c20`
# as the authentication context ID with the desired security level and
# an optional claim `acrs` to be included in the ID token.
# The `included` field declares that the id token claim `acrs` must include the value `c20`.
included: {
acrs: ["c20"],
},
},
params: {
claims: {
id_token: {
acrs: { essential: true, value: 'c20' }
}
},
}
},
}
}
```
1. Save the configuration file and restart GitLab for the changes to take effect.
## Troubleshooting
1. Ensure `discovery` is set to `true`. If you set it to `false`, you must
specify all the URLs and keys required to make OpenID work.
1. Check your system clock to ensure the time is synchronized properly.
1. As mentioned in [the OmniAuth OpenID Connect documentation](https://github.com/omniauth/omniauth_openid_connect),
make sure `issuer` corresponds to the base URL of the Discovery URL. For
example, `https://accounts.google.com` is used for the URL
`https://accounts.google.com/.well-known/openid-configuration`.
1. The OpenID Connect client uses HTTP Basic Authentication to send the
OAuth 2.0 access token if `client_auth_method` is not defined or if set to `basic`.
If you see 401 errors when retrieving the `userinfo` endpoint, check
your OpenID web server configuration. For example, for
[`oauth2-server-php`](https://github.com/bshaffer/oauth2-server-php), you may have to
[add a configuration parameter to Apache](https://github.com/bshaffer/oauth2-server-php/issues/926#issuecomment-387502778).
1. **Step-up authentication only**: Ensure that any parameters defined in
`step_up_auth => admin_mode => params` are also defined in `args => allow_authorize_params`.
This includes the parameters in the request query parameters used to
redirect to the IdP authorization endpoint.
|
https://docs.gitlab.com/administration/cognito
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/cognito.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
cognito.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use AWS Cognito as an OAuth 2.0 authentication provider
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Amazon Web Services (AWS) Cognito lets you add user sign-up, sign-in, and access control to your GitLab instance.
The following documentation enables AWS Cognito as an OAuth 2.0 provider.
## Configure AWS Cognito
To enable the [AWS Cognito](https://aws.amazon.com/cognito/) OAuth 2.0 OmniAuth provider, register your application with Cognito. This process generates a Client ID and Client Secret for your application.
To enable AWS Cognito as an authentication provider, complete the following steps. You can modify any settings you configure later.
1. Sign in to the [AWS console](https://console.aws.amazon.com/console/home).
1. From the **Services** menu, select **Cognito**.
1. Select **Manage User Pools** and then in the upper-right corner, select **Create a user pool**.
1. Enter the user pool name and then select **Step through settings**.
1. Under **How do you want your end users to sign in?**, select **Email address or phone number** and **Allow email addresses**.
1. Under **Which standard attributes do you want to require?**, select **email**.
1. Configure the remaining settings to suit your needs. In the basic setup, these settings do not affect GitLab configuration.
1. In the **App clients** settings:
1. Select **Add an app client**.
1. Add the **App client name**.
1. Select the **Enable username password based authentication** checkbox.
1. Select **Create app client**.
1. Set up the AWS Lambda functions for sending emails and finish creating the user pool.
1. After creating the user pool, go to **App client settings** and provide the required information:
- **Enabled Identity Providers** - select all
- **Callback URL** - `https://<your_gitlab_instance_url>/users/auth/cognito/callback`
- **Allowed OAuth Flows** - Authorization code grant
- **Allowed OAuth 2.0 Scopes** - `email`, `openid`, and `profile`
1. Save changes for the app client settings.
1. Under **Domain name**, include the AWS domain name for your AWS Cognito application.
1. Under **App Clients**, find your app client ID. Select **Show details** to display the app client secret. These values correspond to the OAuth 2.0 Client ID and Client Secret. Save these values.
## Configure GitLab
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `cognito` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. On your GitLab server, open the configuration file. For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
1. In the following code block, enter your AWS Cognito application information in the following parameters:
- `app_id`: Your client ID.
- `app_secret`: Your client secret.
- `site`: Your Amazon domain and region.
Include the code block in the `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['omniauth_allow_single_sign_on'] = ['cognito']
gitlab_rails['omniauth_providers'] = [
{
name: "cognito",
label: "Provider name", # optional label for login button, defaults to "Cognito"
icon: nil, # Optional icon URL
app_id: "<client_id>",
app_secret: "<client_secret>",
args: {
scope: "openid profile email",
client_options: {
site: "https://<your_domain>.auth.<your_region>.amazoncognito.com",
authorize_url: "/oauth2/authorize",
token_url: "/oauth2/token",
user_info_url: "/oauth2/userInfo"
},
user_response_structure: {
root_path: [],
id_path: ["sub"],
attributes: { nickname: "email", name: "email", email: "email" }
},
name: "cognito",
strategy_class: "OmniAuth::Strategies::OAuth2Generic"
}
}
]
```
1. Save the configuration file.
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
Your sign-in page should now display a Cognito option below the regular sign-in form.
Select this option to begin the authentication process.
AWS Cognito then asks you to sign in and authorize the GitLab application.
If the authorization is successful, you're redirected and signed in to your GitLab instance.
For more information, see [Configure common settings](../../integration/omniauth.md#configure-common-settings).
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use AWS Cognito as an OAuth 2.0 authentication provider
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Amazon Web Services (AWS) Cognito lets you add user sign-up, sign-in, and access control to your GitLab instance.
The following documentation enables AWS Cognito as an OAuth 2.0 provider.
## Configure AWS Cognito
To enable the [AWS Cognito](https://aws.amazon.com/cognito/) OAuth 2.0 OmniAuth provider, register your application with Cognito. This process generates a Client ID and Client Secret for your application.
To enable AWS Cognito as an authentication provider, complete the following steps. You can modify any settings you configure later.
1. Sign in to the [AWS console](https://console.aws.amazon.com/console/home).
1. From the **Services** menu, select **Cognito**.
1. Select **Manage User Pools** and then in the upper-right corner, select **Create a user pool**.
1. Enter the user pool name and then select **Step through settings**.
1. Under **How do you want your end users to sign in?**, select **Email address or phone number** and **Allow email addresses**.
1. Under **Which standard attributes do you want to require?**, select **email**.
1. Configure the remaining settings to suit your needs. In the basic setup, these settings do not affect GitLab configuration.
1. In the **App clients** settings:
1. Select **Add an app client**.
1. Add the **App client name**.
1. Select the **Enable username password based authentication** checkbox.
1. Select **Create app client**.
1. Set up the AWS Lambda functions for sending emails and finish creating the user pool.
1. After creating the user pool, go to **App client settings** and provide the required information:
- **Enabled Identity Providers** - select all
- **Callback URL** - `https://<your_gitlab_instance_url>/users/auth/cognito/callback`
- **Allowed OAuth Flows** - Authorization code grant
- **Allowed OAuth 2.0 Scopes** - `email`, `openid`, and `profile`
1. Save changes for the app client settings.
1. Under **Domain name**, include the AWS domain name for your AWS Cognito application.
1. Under **App Clients**, find your app client ID. Select **Show details** to display the app client secret. These values correspond to the OAuth 2.0 Client ID and Client Secret. Save these values.
## Configure GitLab
1. Configure the [common settings](../../integration/omniauth.md#configure-common-settings)
to add `cognito` as a single sign-on provider. This enables Just-In-Time
account provisioning for users who do not have an existing GitLab account.
1. On your GitLab server, open the configuration file. For Linux package installations:
```shell
sudo editor /etc/gitlab/gitlab.rb
```
1. In the following code block, enter your AWS Cognito application information in the following parameters:
- `app_id`: Your client ID.
- `app_secret`: Your client secret.
- `site`: Your Amazon domain and region.
Include the code block in the `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['omniauth_allow_single_sign_on'] = ['cognito']
gitlab_rails['omniauth_providers'] = [
{
name: "cognito",
label: "Provider name", # optional label for login button, defaults to "Cognito"
icon: nil, # Optional icon URL
app_id: "<client_id>",
app_secret: "<client_secret>",
args: {
scope: "openid profile email",
client_options: {
site: "https://<your_domain>.auth.<your_region>.amazoncognito.com",
authorize_url: "/oauth2/authorize",
token_url: "/oauth2/token",
user_info_url: "/oauth2/userInfo"
},
user_response_structure: {
root_path: [],
id_path: ["sub"],
attributes: { nickname: "email", name: "email", email: "email" }
},
name: "cognito",
strategy_class: "OmniAuth::Strategies::OAuth2Generic"
}
}
]
```
1. Save the configuration file.
1. Save the file and [reconfigure](../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
Your sign-in page should now display a Cognito option below the regular sign-in form.
Select this option to begin the authentication process.
AWS Cognito then asks you to sign in and authorize the GitLab application.
If the authorization is successful, you're redirected and signed in to your GitLab instance.
For more information, see [Configure common settings](../../integration/omniauth.md#configure-common-settings).
|
https://docs.gitlab.com/administration/test_oidc_oauth
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/test_oidc_oauth.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
test_oidc_oauth.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Test OIDC/OAuth in GitLab
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To test OIDC/OAuth in GitLab, you must:
1. [Enable OIDC/OAuth](#enable-oidcoauth-in-gitlab)
1. [Test OIDC/OAuth with your client application](#test-oidcoauth-with-your-client-application)
1. [Verify OIDC/OAuth authentication](#verify-oidcoauth-authentication)
## Prerequisites
Before you can test OIDC/OAuth on GitLab, you must:
- Have a publicly accessible instance.
- Be an administrator for that instance.
- Have a client application that you want to use to test OIDC/OAuth.
## Enable OIDC/OAuth in GitLab
First, you must create OIDC/OAuth application on your GitLab instance. To do this:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications**.
1. Select **Add new application**.
1. Fill in the details for your client application, including the name, redirect URI, and allowed scopes.
1. Make sure the `openid` scope is enabled.
1. Select **Save application** to create the new OAuth application.
## Test OIDC/OAuth with your client application
After you've created your OAuth application in GitLab, you can use it to test OIDC/OAuth:
1. You can use <https://openidconnect.net> as the OIDC/OAuth playground.
1. Sign out of GitLab.
1. Visit your client application and initiate the OIDC/OAuth flow, using the GitLab OAuth application you created in the previous step.
1. Follow the prompts to sign in to GitLab and authorize the client application to access your GitLab account.
1. After you've completed the OIDC/OAuth flow, your client application should have received an access token that it can use to authenticate with GitLab.
## Verify OIDC/OAuth authentication
To verify that OIDC/OAuth authentication is working correctly on GitLab, you can perform the following checks:
1. Check that the access token you received in the previous step is valid and can be used to authenticate with GitLab. You can do this by making a test API request to GitLab, using the access token to authenticate. For example:
```shell
curl --header "Authorization: Bearer <access_token>" https://mygitlabinstance.com/api/v4/user
```
Replace `<access_token>` with the actual access token you received in the previous step. If the API request succeeds and returns information about the authenticated user, then OIDC/OAuth authentication is working correctly.
1. Check that the scopes you specified in your OAuth application are being enforced correctly. You can do this by making API requests that require the specific scopes and checking that they succeed or fail as expected.
That's it! With these steps, you should be able to test OIDC/OAuth authentication on your GitLab instance using your client application.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Test OIDC/OAuth in GitLab
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To test OIDC/OAuth in GitLab, you must:
1. [Enable OIDC/OAuth](#enable-oidcoauth-in-gitlab)
1. [Test OIDC/OAuth with your client application](#test-oidcoauth-with-your-client-application)
1. [Verify OIDC/OAuth authentication](#verify-oidcoauth-authentication)
## Prerequisites
Before you can test OIDC/OAuth on GitLab, you must:
- Have a publicly accessible instance.
- Be an administrator for that instance.
- Have a client application that you want to use to test OIDC/OAuth.
## Enable OIDC/OAuth in GitLab
First, you must create OIDC/OAuth application on your GitLab instance. To do this:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Applications**.
1. Select **Add new application**.
1. Fill in the details for your client application, including the name, redirect URI, and allowed scopes.
1. Make sure the `openid` scope is enabled.
1. Select **Save application** to create the new OAuth application.
## Test OIDC/OAuth with your client application
After you've created your OAuth application in GitLab, you can use it to test OIDC/OAuth:
1. You can use <https://openidconnect.net> as the OIDC/OAuth playground.
1. Sign out of GitLab.
1. Visit your client application and initiate the OIDC/OAuth flow, using the GitLab OAuth application you created in the previous step.
1. Follow the prompts to sign in to GitLab and authorize the client application to access your GitLab account.
1. After you've completed the OIDC/OAuth flow, your client application should have received an access token that it can use to authenticate with GitLab.
## Verify OIDC/OAuth authentication
To verify that OIDC/OAuth authentication is working correctly on GitLab, you can perform the following checks:
1. Check that the access token you received in the previous step is valid and can be used to authenticate with GitLab. You can do this by making a test API request to GitLab, using the access token to authenticate. For example:
```shell
curl --header "Authorization: Bearer <access_token>" https://mygitlabinstance.com/api/v4/user
```
Replace `<access_token>` with the actual access token you received in the previous step. If the API request succeeds and returns information about the authenticated user, then OIDC/OAuth authentication is working correctly.
1. Check that the scopes you specified in your OAuth application are being enforced correctly. You can do this by making API requests that require the specific scopes and checking that they succeed or fail as expected.
That's it! With these steps, you should be able to test OIDC/OAuth authentication on your GitLab instance using your client application.
|
https://docs.gitlab.com/administration/auth
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/auth
|
[
"doc",
"administration",
"auth"
] |
_index.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab authentication and authorization
|
Third-party authentication providers.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab integrates with a number of [OmniAuth providers](../../integration/omniauth.md#supported-providers),
and the following external authentication and authorization providers:
- [LDAP](ldap/_index.md): Includes Active Directory, Apple Open Directory, OpenLDAP,
and 389 Server.
- [Google Secure LDAP](ldap/google_secure_ldap.md)
- [SAML for GitLab.com groups](../../user/group/saml_sso/_index.md)
- [Smart card](smartcard.md)
{{< alert type="note" >}}
UltraAuth has removed their software which supports OmniAuth integration. We have therefore removed all references to UltraAuth integration.
{{< /alert >}}
## GitLab.com compared to GitLab Self-Managed
The external authentication and authorization providers may support the following capabilities.
For more information, see the links shown on this page for each external provider.
| Capability | GitLab.com | GitLab Self-Managed |
|-------------------------------------------------|-----------------------------------------|------------------------------------|
| **User Provisioning** | SCIM<br>SAML <sup>1</sup> | LDAP <sup>1</sup><br>SAML <sup>1</sup><br>[OmniAuth Providers](../../integration/omniauth.md#supported-providers) <sup>1</sup><br>SCIM |
| **User Detail Updating** (not group management) | Not Available | LDAP Sync |
| **Authentication** | SAML at top-level group (1 provider) | LDAP (multiple providers)<br>Generic OAuth 2.0<br>SAML (only 1 permitted per unique provider)<br>Kerberos<br>JWT<br>Smart card<br>[OmniAuth Providers](../../integration/omniauth.md#supported-providers) (only 1 permitted per unique provider) |
| **Provider-to-GitLab Role Sync** | SAML Group Sync | LDAP Group Sync<br>SAML Group Sync ([GitLab 15.1](https://gitlab.com/gitlab-org/gitlab/-/issues/285150) and later) |
| **User Removal** | SCIM (remove user from top-level group) | LDAP (remove user from groups and block from the instance)<br>SCIM |
**Footnotes**:
1. Using Just-In-Time (JIT) provisioning, user accounts are created when the user first signs in.
## Test OIDC/OAuth in GitLab
See [Test OIDC/OAuth in GitLab](test_oidc_oauth.md) to learn how to test OIDC/OAuth authentication in your GitLab instance using your client application.
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Third-party authentication providers.
title: GitLab authentication and authorization
breadcrumbs:
- doc
- administration
- auth
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab integrates with a number of [OmniAuth providers](../../integration/omniauth.md#supported-providers),
and the following external authentication and authorization providers:
- [LDAP](ldap/_index.md): Includes Active Directory, Apple Open Directory, OpenLDAP,
and 389 Server.
- [Google Secure LDAP](ldap/google_secure_ldap.md)
- [SAML for GitLab.com groups](../../user/group/saml_sso/_index.md)
- [Smart card](smartcard.md)
{{< alert type="note" >}}
UltraAuth has removed their software which supports OmniAuth integration. We have therefore removed all references to UltraAuth integration.
{{< /alert >}}
## GitLab.com compared to GitLab Self-Managed
The external authentication and authorization providers may support the following capabilities.
For more information, see the links shown on this page for each external provider.
| Capability | GitLab.com | GitLab Self-Managed |
|-------------------------------------------------|-----------------------------------------|------------------------------------|
| **User Provisioning** | SCIM<br>SAML <sup>1</sup> | LDAP <sup>1</sup><br>SAML <sup>1</sup><br>[OmniAuth Providers](../../integration/omniauth.md#supported-providers) <sup>1</sup><br>SCIM |
| **User Detail Updating** (not group management) | Not Available | LDAP Sync |
| **Authentication** | SAML at top-level group (1 provider) | LDAP (multiple providers)<br>Generic OAuth 2.0<br>SAML (only 1 permitted per unique provider)<br>Kerberos<br>JWT<br>Smart card<br>[OmniAuth Providers](../../integration/omniauth.md#supported-providers) (only 1 permitted per unique provider) |
| **Provider-to-GitLab Role Sync** | SAML Group Sync | LDAP Group Sync<br>SAML Group Sync ([GitLab 15.1](https://gitlab.com/gitlab-org/gitlab/-/issues/285150) and later) |
| **User Removal** | SCIM (remove user from top-level group) | LDAP (remove user from groups and block from the instance)<br>SCIM |
**Footnotes**:
1. Using Just-In-Time (JIT) provisioning, user accounts are created when the user first signs in.
## Test OIDC/OAuth in GitLab
See [Test OIDC/OAuth in GitLab](test_oidc_oauth.md) to learn how to test OIDC/OAuth authentication in your GitLab instance using your client application.
|
https://docs.gitlab.com/administration/auth/ldap_synchronization
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/auth/ldap_synchronization.md
|
2025-08-13
|
doc/administration/auth/ldap
|
[
"doc",
"administration",
"auth",
"ldap"
] |
ldap_synchronization.md
|
Fulfillment
|
Seat Management
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
LDAP synchronization
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you have [configured LDAP to work with GitLab](_index.md), GitLab can automatically synchronize
users and groups.
LDAP synchronization updates user and group information for existing GitLab users that have an LDAP identity assigned. It does not create new GitLab users through LDAP.
You can change when synchronization occurs.
## LDAP servers with rate limits
Some LDAP servers have rate limits configured.
GitLab queries the LDAP server once for every:
- User during the scheduled [user sync](#user-sync) process.
- Group during the scheduled [group sync](#group-sync) process.
In some cases, more queries to the LDAP server may be triggered. For example, when a [group sync query returns a `memberuid` attribute](#queries).
If the LDAP server has a rate limit configured and that limit is reached during the:
- User sync process, the LDAP server responds with an error code and GitLab blocks that user.
- Group sync process, the LDAP server responds with an error code and GitLab removes that user's group memberships.
You must consider your LDAP server's rate limits when configuring LDAP synchronization to prevent unwanted user blocks and group membership removals.
## User sync
{{< history >}}
- Preventing LDAP user's profile name synchronization [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/11336) in GitLab 15.11.
{{< /history >}}
Once per day, GitLab runs a worker to check and update GitLab
users against LDAP.
The process executes the following access checks:
- Ensure the user is still present in LDAP.
- If the LDAP server is Active Directory, ensure the user is active (not
blocked/disabled state). This check is performed only if
`active_directory: true` is set in the LDAP configuration.
In Active Directory, a user is marked as disabled/blocked if the user
account control attribute (`userAccountControl:1.2.840.113556.1.4.803`)
has bit 2 set.
<!-- vale gitlab_base.Spelling = NO -->
For more information, see [Bitmask Searches in LDAP](https://ctovswild.com/2009/09/03/bitmask-searches-in-ldap/).
<!-- vale gitlab_base.Spelling = YES -->
The process also updates the following user information:
- Name. Because of a [sync issue](https://gitlab.com/gitlab-org/gitlab/-/issues/342598), `name` is not synchronized if
[**Prevent users from changing their profile name**](../../settings/account_and_limit_settings.md#disable-user-profile-name-changes) is enabled or `sync_name` is set to `false`.
- Email address.
- SSH public keys if `sync_ssh_keys` is set.
- Kerberos identity if Kerberos is enabled.
{{< alert type="note" >}}
If your LDAP server has a rate limit, that limit might be reached during the user sync process. Check the [rate limit documentation](#ldap-servers-with-rate-limits) for more information.
{{< /alert >}}
### Synchronize LDAP user's profile name
By default, GitLab synchronizes the LDAP user's profile name field.
To prevent this synchronization, you can set `sync_name` to `false`.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'sync_name' => false,
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
sync_name: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'sync_name' => false,
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
sync_name: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Blocked users
A user is blocked if either the:
- [Access check fails](#user-sync) and that user is set to an `ldap_blocked` state in GitLab.
- LDAP server is not available when that user signs in.
If a user is blocked, that user cannot sign in or push or pull code.
A blocked user is unblocked when they sign in with LDAP if all of the following are true:
- All the access check conditions are true.
- The LDAP server is available when the user signs in.
**All users** are blocked if the LDAP server is unavailable when an LDAP user synchronization is run.
{{< alert type="note" >}}
If all users are blocked due to the LDAP server not being available when an LDAP user synchronization is run,
a subsequent LDAP user synchronization does not automatically unblock those users.
{{< /alert >}}
## Group sync
If your LDAP supports the `memberof` property, when the user signs in for the
first time GitLab triggers a sync for groups the user should be a member of.
That way they don't have to wait for the hourly sync to be granted
access to their groups and projects.
A group sync process runs every hour on the hour, and `group_base` must be set
in LDAP configuration for LDAP synchronizations based on group CN to work. This allows
GitLab group membership to be automatically updated based on LDAP group members.
The `group_base` configuration should be a base LDAP 'container', such as an
'organization' or 'organizational unit', that contains LDAP groups that should
be available to GitLab. For example, `group_base` could be
`ou=groups,dc=example,dc=com`. In the configuration file, it looks like the
following.
{{< alert type="note" >}}
If your LDAP server has a rate limit, that limit might be reached during the group sync process. Check the [rate limit documentation](#ldap-servers-with-rate-limits) for more information.
{{< /alert >}}
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
To take advantage of group sync, group Owners or users with the [Maintainer role](../../../user/permissions.md) must
[create one or more LDAP group links](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
{{< alert type="note" >}}
If you frequently experience connection issues between your LDAP server and GitLab instance, try reducing the frequency with which GitLab performs an LDAP group sync by
[setting the group sync worker interval](#adjust-ldap-group-sync-schedule) to be greater than the 1 hour default.
{{< /alert >}}
### Add group links
For information on adding group links by using CNs and filters, refer to the
[GitLab groups documentation](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
### Link a custom admin role with an LDAP group
For information on adding custom admin role links by using CNs and filters, refer to the
[manage users using LDAP documentation](../../../user/custom_roles/_index.md#sync-ldap-groups-to-admin-roles).
### Administrator sync
As an extension of group sync, you can automatically manage your global GitLab
administrators. Specify a group CN for `admin_group` and all members of the
LDAP group are given administrator privileges. The configuration looks
like the following.
{{< alert type="note" >}}
Administrators are not synced unless `group_base` is also
specified alongside `admin_group`. Also, only specify the CN of the `admin_group`,
as opposed to the full DN.
Additionally, if an LDAP user has an `admin` role, but is not a member of the `admin_group`
group, GitLab revokes their `admin` role when syncing.
{{< /alert >}}
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
'admin_group' => 'my_admin_group',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
admin_group: my_admin_group
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
'admin_group' => 'my_admin_group',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
admin_group: my_admin_group
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Global group memberships lock
GitLab administrators can prevent group members from inviting new members to subgroups that have their membership synchronized with LDAP.
Global group membership lock only applies to subgroups of the top-level group where LDAP synchronization is configured. No user can modify the
membership of a top-level group configured for LDAP synchronization.
When global group memberships lock is enabled:
- Only an administrator can manage memberships of any group including access levels.
- Users are not allowed to share a project with other groups or invite members to
a project created in a group.
To enable global group memberships lock:
1. [Configure LDAP](_index.md#configure-ldap).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > General**.
1. Expand **Visibility and access controls**.
1. Ensure the **Lock memberships to LDAP synchronization** checkbox is selected.
### Change LDAP group synchronization settings management
By default, group members with the Owner role can manage [LDAP group synchronization settings](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
GitLab administrators can remove this permission from group Owners:
1. [Configure LDAP](_index.md#configure-ldap).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > General**.
1. Expand **Visibility and access controls**.
1. Ensure the **Allow group owners to manage LDAP-related settings** checkbox is not checked.
When **Allow group owners to manage LDAP-related settings** is disabled:
- Group Owners cannot change LDAP synchronization settings for either top-level groups and subgroups.
- Instance administrators can manage LDAP group synchronization settings on all groups on an instance.
### External groups
Using the `external_groups` setting allows you to mark all users belonging
to these groups as [external users](../../external_users.md).
Group membership is checked periodically through the `LdapGroupSync` background
task.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'external_groups' => ['interns', 'contractors'],
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
external_groups: ['interns', 'contractors']
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'external_groups' => ['interns', 'contractors'],
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
external_groups: ['interns', 'contractors']
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### GitLab Duo add-on for groups
The `duo_add_on_groups` setting automatically [manages Duo add-on seats](../../duo_add_on_seat_management_with_ldap.md) for users who authenticate through LDAP. This feature helps organizations to streamline their **GitLab Duo** seat allocation process based on LDAP group memberships.
To enable add-on seat management for groups, you must configure the `duo_add_on_groups` setting in your GitLab instance:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'duo_add_on_groups' => ['duo_group_1', 'duo_group_2'],
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
duo_add_on_groups: ['duo_group_1', 'duo_group_2']
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'duo_add_on_groups' => ['duo_group_1', 'duo_group_2'],
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
duo_add_on_groups: ['duo_group_1', 'duo_group_2']
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Group sync technical details
This section outlines what LDAP queries are executed and what behavior you
can expect from group sync.
Group member access are downgraded from a higher level if their LDAP group
membership changes. For example, if a user the Owner role in a group and the
next group sync reveals they should only have the Developer role, their
access is adjusted accordingly. The only exception is if the user is the
last owner in a group. Groups need at least one owner to fulfill
administrative duties.
#### Supported LDAP group types/attributes
GitLab supports LDAP groups that use member attributes:
- `member`
- `submember`
- `uniquemember`
- `memberof`
- `memberuid`
This means group sync supports (at least) LDAP groups with the following object
classes:
- `groupOfNames`
- `posixGroup`
- `groupOfUniqueNames`
Other object classes should work if members are defined as one of the
mentioned attributes.
Active Directory supports nested groups. Group sync recursively resolves
membership if `active_directory: true` is set in the configuration file.
##### Nested group memberships
Nested group memberships are resolved only if the nested group
is found in the configured `group_base`. For example, if GitLab sees a
nested group with DN `cn=nested_group,ou=special_groups,dc=example,dc=com` but
the configured `group_base` is `ou=groups,dc=example,dc=com`, `cn=nested_group`
is ignored.
#### Queries
- Each LDAP group is queried a maximum of one time with base `group_base` and
filter `(cn=<cn_from_group_link>)`.
- If the LDAP group has the `memberuid` attribute, GitLab executes another
LDAP query per member to obtain each user's full DN. These queries are
executed with base `base`, scope 'base object', and a filter depending on
whether `user_filter` is set. Filter may be `(uid=<uid_from_group>)` or a
joining of `user_filter`.
#### Benchmarks
Group sync was written to be as performant as possible. Data is cached, database
queries are optimized, and LDAP queries are minimized. The last benchmark run
revealed the following metrics:
For 20,000 LDAP users, 11,000 LDAP groups, and 1,000 GitLab groups with 10
LDAP group links each:
- Initial sync (no existing members assigned in GitLab) took 1.8 hours
- Subsequent syncs (checking membership, no writes) took 15 minutes
These metrics are meant to provide a baseline and performance may vary based on
any number of factors. This benchmark was extreme and most instances don't
have near this many users or groups. Disk speed, database performance,
network and LDAP server response time affects these metrics.
### Adjust LDAP user sync schedule
By default, GitLab runs a worker once per day at 01:30 AM server time to
check and update GitLab users against LDAP.
{{< alert type="warning" >}}
Do not run the sync process too frequently as this could lead to multiple syncs running concurrently. Most installations do not need to modify the sync schedule. For more information, see the [LDAP Security documentation](_index.md#security).
{{< /alert >}}
You can manually configure LDAP user sync times by setting the
following configuration values, in cron format. If needed, you can
use a [crontab generator](https://it-tools.tech/crontab-generator).
The example below shows how to set LDAP user
sync to run once every 12 hours at the top of the hour.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_sync_worker_cron'] = "0 */12 * * *"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
cron_jobs:
ldap_sync_worker:
cron: "0 */12 * * *"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_sync_worker_cron'] = "0 */12 * * *"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
ldap_sync_worker:
cron: "0 */12 * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Adjust LDAP group sync schedule
By default, GitLab runs a group sync process every hour, on the hour.
The values shown are in cron format. If needed, you can use a
[crontab generator](https://it-tools.tech/crontab-generator).
{{< alert type="warning" >}}
Do not start the sync process too frequently as this could lead to multiple syncs running concurrently. Most installations do not need to modify the sync schedule.
{{< /alert >}}
You can manually configure LDAP group sync times by setting the
following configuration values. The example below shows how to set group
sync to run once every two hours at the top of the hour.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_group_sync_worker_cron'] = "0 */2 * * *"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
cron_jobs:
ldap_group_sync_worker:
cron: "*/30 * * * *"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_group_sync_worker_cron'] = "0 */2 * * *"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
ldap_group_sync_worker:
cron: "*/30 * * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Troubleshooting
See our [administrator guide to troubleshooting LDAP](ldap-troubleshooting.md).
|
---
stage: Fulfillment
group: Seat Management
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: LDAP synchronization
breadcrumbs:
- doc
- administration
- auth
- ldap
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you have [configured LDAP to work with GitLab](_index.md), GitLab can automatically synchronize
users and groups.
LDAP synchronization updates user and group information for existing GitLab users that have an LDAP identity assigned. It does not create new GitLab users through LDAP.
You can change when synchronization occurs.
## LDAP servers with rate limits
Some LDAP servers have rate limits configured.
GitLab queries the LDAP server once for every:
- User during the scheduled [user sync](#user-sync) process.
- Group during the scheduled [group sync](#group-sync) process.
In some cases, more queries to the LDAP server may be triggered. For example, when a [group sync query returns a `memberuid` attribute](#queries).
If the LDAP server has a rate limit configured and that limit is reached during the:
- User sync process, the LDAP server responds with an error code and GitLab blocks that user.
- Group sync process, the LDAP server responds with an error code and GitLab removes that user's group memberships.
You must consider your LDAP server's rate limits when configuring LDAP synchronization to prevent unwanted user blocks and group membership removals.
## User sync
{{< history >}}
- Preventing LDAP user's profile name synchronization [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/11336) in GitLab 15.11.
{{< /history >}}
Once per day, GitLab runs a worker to check and update GitLab
users against LDAP.
The process executes the following access checks:
- Ensure the user is still present in LDAP.
- If the LDAP server is Active Directory, ensure the user is active (not
blocked/disabled state). This check is performed only if
`active_directory: true` is set in the LDAP configuration.
In Active Directory, a user is marked as disabled/blocked if the user
account control attribute (`userAccountControl:1.2.840.113556.1.4.803`)
has bit 2 set.
<!-- vale gitlab_base.Spelling = NO -->
For more information, see [Bitmask Searches in LDAP](https://ctovswild.com/2009/09/03/bitmask-searches-in-ldap/).
<!-- vale gitlab_base.Spelling = YES -->
The process also updates the following user information:
- Name. Because of a [sync issue](https://gitlab.com/gitlab-org/gitlab/-/issues/342598), `name` is not synchronized if
[**Prevent users from changing their profile name**](../../settings/account_and_limit_settings.md#disable-user-profile-name-changes) is enabled or `sync_name` is set to `false`.
- Email address.
- SSH public keys if `sync_ssh_keys` is set.
- Kerberos identity if Kerberos is enabled.
{{< alert type="note" >}}
If your LDAP server has a rate limit, that limit might be reached during the user sync process. Check the [rate limit documentation](#ldap-servers-with-rate-limits) for more information.
{{< /alert >}}
### Synchronize LDAP user's profile name
By default, GitLab synchronizes the LDAP user's profile name field.
To prevent this synchronization, you can set `sync_name` to `false`.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'sync_name' => false,
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
sync_name: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'sync_name' => false,
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
sync_name: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Blocked users
A user is blocked if either the:
- [Access check fails](#user-sync) and that user is set to an `ldap_blocked` state in GitLab.
- LDAP server is not available when that user signs in.
If a user is blocked, that user cannot sign in or push or pull code.
A blocked user is unblocked when they sign in with LDAP if all of the following are true:
- All the access check conditions are true.
- The LDAP server is available when the user signs in.
**All users** are blocked if the LDAP server is unavailable when an LDAP user synchronization is run.
{{< alert type="note" >}}
If all users are blocked due to the LDAP server not being available when an LDAP user synchronization is run,
a subsequent LDAP user synchronization does not automatically unblock those users.
{{< /alert >}}
## Group sync
If your LDAP supports the `memberof` property, when the user signs in for the
first time GitLab triggers a sync for groups the user should be a member of.
That way they don't have to wait for the hourly sync to be granted
access to their groups and projects.
A group sync process runs every hour on the hour, and `group_base` must be set
in LDAP configuration for LDAP synchronizations based on group CN to work. This allows
GitLab group membership to be automatically updated based on LDAP group members.
The `group_base` configuration should be a base LDAP 'container', such as an
'organization' or 'organizational unit', that contains LDAP groups that should
be available to GitLab. For example, `group_base` could be
`ou=groups,dc=example,dc=com`. In the configuration file, it looks like the
following.
{{< alert type="note" >}}
If your LDAP server has a rate limit, that limit might be reached during the group sync process. Check the [rate limit documentation](#ldap-servers-with-rate-limits) for more information.
{{< /alert >}}
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
To take advantage of group sync, group Owners or users with the [Maintainer role](../../../user/permissions.md) must
[create one or more LDAP group links](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
{{< alert type="note" >}}
If you frequently experience connection issues between your LDAP server and GitLab instance, try reducing the frequency with which GitLab performs an LDAP group sync by
[setting the group sync worker interval](#adjust-ldap-group-sync-schedule) to be greater than the 1 hour default.
{{< /alert >}}
### Add group links
For information on adding group links by using CNs and filters, refer to the
[GitLab groups documentation](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
### Link a custom admin role with an LDAP group
For information on adding custom admin role links by using CNs and filters, refer to the
[manage users using LDAP documentation](../../../user/custom_roles/_index.md#sync-ldap-groups-to-admin-roles).
### Administrator sync
As an extension of group sync, you can automatically manage your global GitLab
administrators. Specify a group CN for `admin_group` and all members of the
LDAP group are given administrator privileges. The configuration looks
like the following.
{{< alert type="note" >}}
Administrators are not synced unless `group_base` is also
specified alongside `admin_group`. Also, only specify the CN of the `admin_group`,
as opposed to the full DN.
Additionally, if an LDAP user has an `admin` role, but is not a member of the `admin_group`
group, GitLab revokes their `admin` role when syncing.
{{< /alert >}}
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
'admin_group' => 'my_admin_group',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
admin_group: my_admin_group
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'group_base' => 'ou=groups,dc=example,dc=com',
'admin_group' => 'my_admin_group',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
group_base: ou=groups,dc=example,dc=com
admin_group: my_admin_group
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Global group memberships lock
GitLab administrators can prevent group members from inviting new members to subgroups that have their membership synchronized with LDAP.
Global group membership lock only applies to subgroups of the top-level group where LDAP synchronization is configured. No user can modify the
membership of a top-level group configured for LDAP synchronization.
When global group memberships lock is enabled:
- Only an administrator can manage memberships of any group including access levels.
- Users are not allowed to share a project with other groups or invite members to
a project created in a group.
To enable global group memberships lock:
1. [Configure LDAP](_index.md#configure-ldap).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > General**.
1. Expand **Visibility and access controls**.
1. Ensure the **Lock memberships to LDAP synchronization** checkbox is selected.
### Change LDAP group synchronization settings management
By default, group members with the Owner role can manage [LDAP group synchronization settings](../../../user/group/access_and_permissions.md#manage-group-memberships-with-ldap).
GitLab administrators can remove this permission from group Owners:
1. [Configure LDAP](_index.md#configure-ldap).
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > General**.
1. Expand **Visibility and access controls**.
1. Ensure the **Allow group owners to manage LDAP-related settings** checkbox is not checked.
When **Allow group owners to manage LDAP-related settings** is disabled:
- Group Owners cannot change LDAP synchronization settings for either top-level groups and subgroups.
- Instance administrators can manage LDAP group synchronization settings on all groups on an instance.
### External groups
Using the `external_groups` setting allows you to mark all users belonging
to these groups as [external users](../../external_users.md).
Group membership is checked periodically through the `LdapGroupSync` background
task.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'external_groups' => ['interns', 'contractors'],
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
external_groups: ['interns', 'contractors']
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'external_groups' => ['interns', 'contractors'],
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
external_groups: ['interns', 'contractors']
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### GitLab Duo add-on for groups
The `duo_add_on_groups` setting automatically [manages Duo add-on seats](../../duo_add_on_seat_management_with_ldap.md) for users who authenticate through LDAP. This feature helps organizations to streamline their **GitLab Duo** seat allocation process based on LDAP group memberships.
To enable add-on seat management for groups, you must configure the `duo_add_on_groups` setting in your GitLab instance:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'duo_add_on_groups' => ['duo_group_1', 'duo_group_2'],
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
duo_add_on_groups: ['duo_group_1', 'duo_group_2']
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'duo_add_on_groups' => ['duo_group_1', 'duo_group_2'],
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
duo_add_on_groups: ['duo_group_1', 'duo_group_2']
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Group sync technical details
This section outlines what LDAP queries are executed and what behavior you
can expect from group sync.
Group member access are downgraded from a higher level if their LDAP group
membership changes. For example, if a user the Owner role in a group and the
next group sync reveals they should only have the Developer role, their
access is adjusted accordingly. The only exception is if the user is the
last owner in a group. Groups need at least one owner to fulfill
administrative duties.
#### Supported LDAP group types/attributes
GitLab supports LDAP groups that use member attributes:
- `member`
- `submember`
- `uniquemember`
- `memberof`
- `memberuid`
This means group sync supports (at least) LDAP groups with the following object
classes:
- `groupOfNames`
- `posixGroup`
- `groupOfUniqueNames`
Other object classes should work if members are defined as one of the
mentioned attributes.
Active Directory supports nested groups. Group sync recursively resolves
membership if `active_directory: true` is set in the configuration file.
##### Nested group memberships
Nested group memberships are resolved only if the nested group
is found in the configured `group_base`. For example, if GitLab sees a
nested group with DN `cn=nested_group,ou=special_groups,dc=example,dc=com` but
the configured `group_base` is `ou=groups,dc=example,dc=com`, `cn=nested_group`
is ignored.
#### Queries
- Each LDAP group is queried a maximum of one time with base `group_base` and
filter `(cn=<cn_from_group_link>)`.
- If the LDAP group has the `memberuid` attribute, GitLab executes another
LDAP query per member to obtain each user's full DN. These queries are
executed with base `base`, scope 'base object', and a filter depending on
whether `user_filter` is set. Filter may be `(uid=<uid_from_group>)` or a
joining of `user_filter`.
#### Benchmarks
Group sync was written to be as performant as possible. Data is cached, database
queries are optimized, and LDAP queries are minimized. The last benchmark run
revealed the following metrics:
For 20,000 LDAP users, 11,000 LDAP groups, and 1,000 GitLab groups with 10
LDAP group links each:
- Initial sync (no existing members assigned in GitLab) took 1.8 hours
- Subsequent syncs (checking membership, no writes) took 15 minutes
These metrics are meant to provide a baseline and performance may vary based on
any number of factors. This benchmark was extreme and most instances don't
have near this many users or groups. Disk speed, database performance,
network and LDAP server response time affects these metrics.
### Adjust LDAP user sync schedule
By default, GitLab runs a worker once per day at 01:30 AM server time to
check and update GitLab users against LDAP.
{{< alert type="warning" >}}
Do not run the sync process too frequently as this could lead to multiple syncs running concurrently. Most installations do not need to modify the sync schedule. For more information, see the [LDAP Security documentation](_index.md#security).
{{< /alert >}}
You can manually configure LDAP user sync times by setting the
following configuration values, in cron format. If needed, you can
use a [crontab generator](https://it-tools.tech/crontab-generator).
The example below shows how to set LDAP user
sync to run once every 12 hours at the top of the hour.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_sync_worker_cron'] = "0 */12 * * *"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
cron_jobs:
ldap_sync_worker:
cron: "0 */12 * * *"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_sync_worker_cron'] = "0 */12 * * *"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
ldap_sync_worker:
cron: "0 */12 * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Adjust LDAP group sync schedule
By default, GitLab runs a group sync process every hour, on the hour.
The values shown are in cron format. If needed, you can use a
[crontab generator](https://it-tools.tech/crontab-generator).
{{< alert type="warning" >}}
Do not start the sync process too frequently as this could lead to multiple syncs running concurrently. Most installations do not need to modify the sync schedule.
{{< /alert >}}
You can manually configure LDAP group sync times by setting the
following configuration values. The example below shows how to set group
sync to run once every two hours at the top of the hour.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_group_sync_worker_cron'] = "0 */2 * * *"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
cron_jobs:
ldap_group_sync_worker:
cron: "*/30 * * * *"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_group_sync_worker_cron'] = "0 */2 * * *"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ee_cron_jobs:
ldap_group_sync_worker:
cron: "*/30 * * * *"
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Troubleshooting
See our [administrator guide to troubleshooting LDAP](ldap-troubleshooting.md).
|
https://docs.gitlab.com/administration/auth/ldap-troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/auth/ldap-troubleshooting.md
|
2025-08-13
|
doc/administration/auth/ldap
|
[
"doc",
"administration",
"auth",
"ldap"
] |
ldap-troubleshooting.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting LDAP
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you are an administrator, use the following information to troubleshoot LDAP.
## Common Problems & Workflows
### Connection
#### Connection refused
If you're getting `Connection Refused` error messages when attempting to
connect to the LDAP server, review the LDAP `port` and `encryption` settings
used by GitLab. Common combinations are `encryption: 'plain'` and `port: 389`,
or `encryption: 'simple_tls'` and `port: 636`.
#### Connection times out
If GitLab cannot reach your LDAP endpoint, you see a message like this:
```plaintext
Could not authenticate you from Ldapmain because "Connection timed out - user specified timeout".
```
If your configured LDAP provider and/or endpoint is offline or otherwise
unreachable by GitLab, no LDAP user is able to authenticate and sign-in.
GitLab does not cache or store credentials for LDAP users to provide authentication
during an LDAP outage.
Contact your LDAP provider or administrator if you are seeing this error.
#### Referral error
If you see `LDAP search error: Referral` in the logs, or when troubleshooting
LDAP Group Sync, this error may indicate a configuration problem. The LDAP
configuration `/etc/gitlab/gitlab.rb` (Omnibus) or `config/gitlab.yml` (source)
is in YAML format and is sensitive to indentation. Check that `group_base` and
`admin_group` configuration keys are indented 2 spaces past the server
identifier. The default identifier is `main` and an example snippet looks like
the following:
```yaml
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: 'ldap.example.com'
# ...
group_base: 'cn=my_group,ou=groups,dc=example,dc=com'
admin_group: 'my_admin_group'
```
#### Query LDAP
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following allows you to perform a search in LDAP using the rails console.
Depending on what you're trying to do, it may make more sense to query [a user](#query-a-user-in-ldap)
or [a group](#query-a-group-in-ldap) directly, or even [use `ldapsearch`](#ldapsearch) instead.
```ruby
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
# :base is required
# use .base or .group_base
base: adapter.config.group_base,
# :filter is optional
# 'cn' looks for all "cn"s under :base
# '*' is the search string - here, it's a wildcard
filter: Net::LDAP::Filter.eq('cn', '*'),
# :attributes is optional
# the attributes we want to get returned
attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)
```
When using OIDs in the filter, replace `Net::LDAP::Filter.eq` with `Net::LDAP::Filter.construct`:
```ruby
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
# :base is required
# use .base or .group_base
base: adapter.config.base,
# :filter is optional
# This filter includes OID 1.2.840.113556.1.4.1941
# It will search for all direct and nested members of the group gitlab_grp in the LDAP directory
filter: Net::LDAP::Filter.construct("(memberOf:1.2.840.113556.1.4.1941:=CN=gitlab_grp,DC=example,DC=com)"),
# :attributes is optional
# the attributes we want to get returned
attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)
```
For examples of how this is run,
[review the `Adapter` module](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/lib/ee/gitlab/auth/ldap/adapter.rb).
### User sign-ins
#### No users are found
If [you've confirmed](#ldap-check) that a connection to LDAP can be
established but GitLab doesn't show you LDAP users in the output, one of the
following is most likely true:
- The `bind_dn` user doesn't have enough permissions to traverse the user tree.
- The users don't fall under the [configured `base`](_index.md#configure-ldap).
- The [configured `user_filter`](_index.md#set-up-ldap-user-filter) blocks access to the users.
In this case, you can confirm which of the previous is true using
[ldapsearch](#ldapsearch) with the existing LDAP configuration in your
`/etc/gitlab/gitlab.rb`.
#### Users cannot sign-in
A user can have trouble signing in for any number of reasons. To get started,
here are some questions to ask yourself:
- Does the user fall under the [configured `base`](_index.md#configure-ldap) in
LDAP? The user must fall under this `base` to sign in.
- Does the user pass through the [configured `user_filter`](_index.md#set-up-ldap-user-filter)?
If one is not configured, this question can be ignored. If it is, then the
user must also pass through this filter to be allowed to sign in.
- Refer to our documentation on [debugging the `user_filter`](#debug-ldap-user-filter).
If the previous questions are both okay, the next place to look for the problem is
the logs themselves while reproducing the issue.
- Ask the user to sign in and let it fail.
- [Look through the output](#gitlab-logs) for any errors or other
messages about the sign-in. You may see one of the other error messages on
this page, in which case that section can help resolve the issue.
If the logs don't lead to the root of the problem, use the
[rails console](#rails-console) to [query this user](#query-a-user-in-ldap)
to see if GitLab can read this user on the LDAP server.
It can also be helpful to
[debug a user sync](#sync-all-users) to
investigate further.
#### Users see an error "Invalid login or password."
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/438144) in GitLab 16.10.
{{< /history >}}
If users see this error, it might be because they are trying to sign in using the **Standard** sign-in form instead of the **LDAP** sign-in form.
To resolve, ask the user to enter their LDAP username and password into the **LDAP** sign-in form.
#### Invalid credentials on sign-in
If that the sign-in credentials used are accurate on LDAP, ensure the following
are true for the user in question:
- Make sure the user you are binding with has enough permissions to read the user's
tree and traverse it.
- Check that the `user_filter` is not blocking otherwise valid users.
- Run [an LDAP check command](#ldap-check) to make sure that the LDAP settings
are correct and [GitLab can see your users](#no-users-are-found).
#### Access denied for your LDAP account
There is [a bug](https://gitlab.com/gitlab-org/gitlab/-/issues/235930) that
may affect users with [Auditor level access](../../auditor_users.md). When
downgrading from Premium/Ultimate, Auditor users who try to sign in
may see the following message: `Access denied for your LDAP account`.
We have a workaround, based on toggling the access level of affected users:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Overview** > **Users**.
1. Select the name of the affected user.
1. In the upper-right corner, select **Edit**.
1. Change the user's access level from `Regular` to `Administrator` (or vice versa).
1. At the bottom of the page, select **Save changes**.
1. In the upper-right corner, select **Edit** again.
1. Restore the user's original access level (`Regular` or `Administrator`)
and select **Save changes** again.
The user should now be able to sign in.
#### Email has already been taken
A user tries to sign in with the correct LDAP credentials, is denied access,
and the [production.log](../../logs/_index.md#productionlog) shows an error that looks like this:
```plaintext
(LDAP) Error saving user <USER DN> (email@example.com): ["Email has already been taken"]
```
This error is referring to the email address in LDAP, `email@example.com`. Email
addresses must be unique in GitLab and LDAP links to a user's primary email (as opposed
to any of their possibly-numerous secondary emails). Another user (or even the
same user) has the email `email@example.com` set as a secondary email, which
is throwing this error.
We can check where this conflicting email address is coming from using the
[rails console](#rails-console). In the console, run the following:
```ruby
# This searches for an email among the primary AND secondary emails
user = User.find_by_any_email('email@example.com')
user.username
```
This shows you which user has this email address. One of two steps must be taken here:
- To create a new GitLab user/username for this user when signing in with LDAP,
remove the secondary email to remove the conflict.
- To use an existing GitLab user/username for this user to use with LDAP,
remove this email as a secondary email and make it a primary one so GitLab
associates this profile to the LDAP identity.
The user can do either of these steps
[in their profile](../../../user/profile/_index.md#access-your-user-profile) or an administrator can do it.
#### Projects limit errors
The following errors indicate that a limit or restriction is activated, but an associated data
field contains no data:
- `Projects limit can't be blank`.
- `Projects limit is not a number`.
To resolve this:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings** > **General**.
1. Expand both of the following:
- **Account and limit**.
- **Sign-up restrictions**.
1. Check, for example, the **Default projects limit** or **Allowed domains for sign-ups**
fields and ensure that a relevant value is configured.
#### Debug LDAP user filter
[`ldapsearch`](#ldapsearch) allows you to test your configured
[user filter](_index.md#set-up-ldap-user-filter)
to confirm that it returns the users you expect it to return.
```shell
ldapsearch -H ldaps://$host:$port -D "$bind_dn" -y bind_dn_password.txt -b "$base" "$user_filter" sAMAccountName
```
- Variables beginning with a `$` refer to a variable from the LDAP section of
your configuration file.
- Replace `ldaps://` with `ldap://` if you are using the plain authentication method.
Port `389` is the default `ldap://` port and `636` is the default `ldaps://`
port.
- We are assuming the password for the `bind_dn` user is in `bind_dn_password.txt`.
#### Sync all users
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The output from a manual [user sync](ldap_synchronization.md#user-sync) can show you what happens when
GitLab tries to sync its users against LDAP. Enter the [rails console](#rails-console)
and then run:
```ruby
Rails.logger.level = Logger::DEBUG
LdapSyncWorker.new.perform
```
Next, [learn how to read the output](#example-console-output-after-a-user-sync).
##### Example console output after a user sync
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The output from a [manual user sync](#sync-all-users) is very verbose, and a
single user's successful sync can look like this:
```shell
Syncing user John, email@example.com
Identity Load (0.9ms) SELECT "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1
Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John
UserSyncedAttributesMetadata Load (0.9ms) SELECT "user_synced_attributes_metadata".* FROM "user_synced_attributes_metadata" WHERE "user_synced_attributes_metadata"."user_id" = 20 LIMIT 1
(0.3ms) BEGIN
Namespace Load (1.0ms) SELECT "namespaces".* FROM "namespaces" WHERE "namespaces"."owner_id" = 20 AND "namespaces"."type" IS NULL LIMIT 1
Route Load (0.8ms) SELECT "routes".* FROM "routes" WHERE "routes"."source_id" = 27 AND "routes"."source_type" = 'Namespace' LIMIT 1
Ci::Runner Load (1.1ms) SELECT "ci_runners".* FROM "ci_runners" INNER JOIN "ci_runner_namespaces" ON "ci_runners"."id" = "ci_runner_namespaces"."runner_id" WHERE "ci_runner_namespaces"."namespace_id" = 27
(0.7ms) COMMIT
(0.4ms) BEGIN
Route Load (0.8ms) SELECT "routes".* FROM "routes" WHERE (LOWER("routes"."path") = LOWER('John'))
Namespace Load (1.0ms) SELECT "namespaces".* FROM "namespaces" WHERE "namespaces"."id" = 27 LIMIT 1
Route Exists (0.9ms) SELECT 1 AS one FROM "routes" WHERE LOWER("routes"."path") = LOWER('John') AND "routes"."id" != 50 LIMIT 1
User Update (1.1ms) UPDATE "users" SET "updated_at" = '2019-10-17 14:40:59.751685', "last_credential_check_at" = '2019-10-17 14:40:59.738714' WHERE "users"."id" = 20
```
There's a lot here, so let's go over what could be helpful when debugging.
First, GitLab looks for all users that have previously
signed in with LDAP and iterate on them. Each user's sync starts with
the following line that contains the user's username and email, as they
exist in GitLab now:
```shell
Syncing user John, email@example.com
```
If you don't find a particular user's GitLab email in the output, then that
user hasn't signed in with LDAP yet.
Next, GitLab searches its `identities` table for the existing
link between this user and the configured LDAP providers:
```sql
Identity Load (0.9ms) SELECT "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1
```
The identity object has the DN that GitLab uses to look for the user
in LDAP. If the DN isn't found, the email is used instead. We can see that
this user is found in LDAP:
```shell
Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John
```
If the user wasn't found in LDAP with either the DN or email, you might see the
following message instead:
```shell
LDAP search error: No Such Object
```
In this case, the user is blocked:
```shell
User Update (0.4ms) UPDATE "users" SET "state" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["state", "ldap_blocked"], ["updated_at", "2019-10-18 15:46:22.902177"], ["id", 20]]
```
After the user is found in LDAP, the rest of the output updates the GitLab
database with any changes.
#### Query a user in LDAP
This tests that GitLab can reach out to LDAP and read a particular user.
It can expose potential errors connecting to and/or querying LDAP
that may seem to fail silently in the GitLab UI.
```ruby
Rails.logger.level = Logger::DEBUG
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
Gitlab::Auth::Ldap::Person.find_by_uid('<uid>', adapter)
```
### Group memberships
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
#### Memberships not granted
Sometimes you may think a particular user should be added to a GitLab group through
LDAP group sync, but for some reason it's not happening. You can check several
things to debug the situation.
- Ensure LDAP configuration has a `group_base` specified.
[This configuration](ldap_synchronization.md#group-sync) is required for group sync to work properly.
- Ensure the correct [LDAP group link is added to the GitLab group](ldap_synchronization.md#add-group-links).
- Check that the user has an LDAP identity:
1. Sign in to GitLab as an administrator user.
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Overview** > **Users**.
1. Search for the user.
1. Open the user by selecting their name. Do not select **Edit**.
1. Select the **Identities** tab. There should be an LDAP identity with
an LDAP DN as the `Identifier`. If not, this user hasn't signed in with
LDAP yet and must do so first.
- You've waited an hour or [the configured interval](ldap_synchronization.md#adjust-ldap-group-sync-schedule) for
the group to sync. To speed up the process, either go to the GitLab group **Manage** > **Members**
and press **Sync now** (sync one group) or [run the group sync Rake task](../../raketasks/ldap.md#run-a-group-sync)
(sync all groups).
If all of the checks looks good, jump in to a little more advanced debugging in
the rails console.
1. Enter the [rails console](#rails-console).
1. Choose a GitLab group to test with. This group should have an LDAP group link
already configured.
1. Enable debug logging, find the chosen GitLab group, and [sync it with LDAP](#sync-one-group).
1. Look through the output of the sync. See [example log output](#example-console-output-after-a-group-sync)
for how to read the output.
1. If you still aren't able to see why the user isn't being added, [query the LDAP group directly](#query-a-group-in-ldap)
to see what members are listed.
1. Is the user's DN or UID in one of the lists from the queried group? One of the DNs or
UIDs here should match the 'Identifier' from the LDAP identity checked earlier. If it doesn't,
the user does not appear to be in the LDAP group.
#### Cannot add service account user to group when LDAP sync is enabled
When LDAP sync is enabled for a group, you cannot use the "invite" dialog to invite new group members.
To resolve this issue in GitLab 16.8 and later, you can invite service accounts to and remove them from a group using the [group members API endpoints](../../../api/members.md#add-a-member-to-a-group-or-project).
#### Administrator privileges not granted
When [Administrator sync](ldap_synchronization.md#administrator-sync) has been configured
but the configured users aren't granted the correct administrator privileges, confirm
that the following conditions are true:
- A [`group_base` is also configured](ldap_synchronization.md#group-sync).
- The configured `admin_group` in the `gitlab.rb` is a CN, rather than a DN or an array.
- This CN falls under the scope of the configured `group_base`.
- The members of the `admin_group` have already signed into GitLab with their LDAP
credentials. GitLab only grants administrator access to the users whose
accounts are already connected to LDAP.
If all the previous conditions are true and the users are still not getting access,
[run a manual group sync](#sync-all-groups) in the rails console and
[look through the output](#example-console-output-after-a-group-sync) to see what happens when
GitLab syncs the `admin_group`.
#### Sync now button stuck in the UI
The **Sync now** button on the **Group** > **Members** page of a group can become stuck. The button becomes stuck after it is pressed and the page is reloaded. The button then
cannot be selected again.
The **Sync now** button can become stuck for many reasons and requires debugging for specific cases. The following are two possible causes and possible solutions to the problem.
##### Invalid memberships
The **Sync now** button becomes stuck if some of the group's members or requesting members are invalid. You can track progress on improving the visibility of this problem in
a [relevant issue](https://gitlab.com/gitlab-org/gitlab/-/issues/348226). You can use a [Rails console](#rails-console) to confirm if this problem is causing the **Sync now**
button to be stuck:
```ruby
# Find the group in question
group = Group.find_by(name: 'my_gitlab_group')
# Look for errors on the Group itself
group.valid?
group.errors.map(&:full_messages)
# Look for errors among the group's members and requesters
group.requesters.map(&:valid?)
group.requesters.map(&:errors).map(&:full_messages)
group.members.map(&:valid?)
group.members.map(&:errors).map(&:full_messages)
```
A displayed error can identify the problem and point to a solution. For example, the Support Team has seen the following error:
```ruby
irb(main):018:0> group.members.map(&:errors).map(&:full_messages)
=> [["The member's email address is not allowed for this group. Go to the group's 'Settings > General' page, and check 'Restrict membership by email domain'."]]
```
This error showed that an Administrator chose to [restrict group membership by email domain](../../../user/group/access_and_permissions.md#restrict-group-access-by-domain),
but there was a typo in the domain. After the domain setting was fixed, the **Sync now** button functioned again.
##### Missing LDAP configuration on Sidekiq nodes
The **Sync now** button becomes stuck when GitLab is scaled over multiple nodes and the LDAP configuration is missing from
[the `/etc/gitlab/gitlab.rb` on the nodes running Sidekiq](../../sidekiq/_index.md#configure-ldap-and-user-or-group-synchronization).
In this case, the Sidekiq jobs seem to disappear.
LDAP is required on the Sidekiq nodes because LDAP has multiple jobs that are
run asynchronously that require a local LDAP configuration:
- [User sync](ldap_synchronization.md#user-sync).
- [Group sync](ldap_synchronization.md#group-sync).
You can test whether missing LDAP configuration is the problem by running [the Rake task to check LDAP](#ldap-check)
on each node that is running Sidekiq. If LDAP is set up correctly on this node, it connects to the LDAP server and returns users.
To solve this issue, [configure LDAP](../../sidekiq/_index.md#configure-ldap-and-user-or-group-synchronization) on the Sidekiq nodes.
When configured, run [the Rake task to check LDAP](#ldap-check) to confirm
that the GitLab node can connect to LDAP.
#### Sync all groups
{{< alert type="note" >}}
To sync all groups manually when debugging is unnecessary,
[use the Rake task](../../raketasks/ldap.md#run-a-group-sync) instead.
{{< /alert >}}
The output from a manual [group sync](ldap_synchronization.md#group-sync) can show you what happens
when GitLab syncs its LDAP group memberships against LDAP. Enter the [rails console](#rails-console)
and then run:
```ruby
Rails.logger.level = Logger::DEBUG
LdapAllGroupsSyncWorker.new.perform
```
Next, [learn how to read the output](#example-console-output-after-a-group-sync).
##### Example console output after a group sync
Like the output from the user sync, the output from the
[manual group sync](#sync-all-groups) is also very verbose. However, it contains lots
of helpful information.
Indicates the point where syncing actually begins:
```shell
Started syncing 'ldapmain' provider for 'my_group' group
```
The following entry shows an array of all user DNs GitLab sees in the LDAP server.
These DNs are the users for a single LDAP group, not a GitLab group. If
you have multiple LDAP groups linked to this GitLab group, you see multiple
log entries like this - one for each LDAP group. If you don't see an LDAP user
DN in this log entry, LDAP is not returning the user when we do the lookup.
Verify the user is actually in the LDAP group.
```shell
Members in 'ldap_group_1' LDAP group: ["uid=john0,ou=people,dc=example,dc=com",
"uid=mary0,ou=people,dc=example,dc=com", "uid=john1,ou=people,dc=example,dc=com",
"uid=mary1,ou=people,dc=example,dc=com", "uid=john2,ou=people,dc=example,dc=com",
"uid=mary2,ou=people,dc=example,dc=com", "uid=john3,ou=people,dc=example,dc=com",
"uid=mary3,ou=people,dc=example,dc=com", "uid=john4,ou=people,dc=example,dc=com",
"uid=mary4,ou=people,dc=example,dc=com"]
```
Shortly after each of the entries, you see a hash of resolved member
access levels. This hash represents all user DNs GitLab thinks should have
access to this group, and at which access level (role). This hash is additive,
and more DNs may be added, or existing entries modified, based on additional
LDAP group lookups. The very last occurrence of this entry should indicate
exactly which users GitLab believes should be added to the group.
{{< alert type="note" >}}
10 is `Guest`, 20 is `Reporter`, 30 is `Developer`, 40 is `Maintainer`
and 50 is `Owner`.
{{< /alert >}}
```shell
Resolved 'my_group' group member access: {"uid=john0,ou=people,dc=example,dc=com"=>30,
"uid=mary0,ou=people,dc=example,dc=com"=>30, "uid=john1,ou=people,dc=example,dc=com"=>30,
"uid=mary1,ou=people,dc=example,dc=com"=>30, "uid=john2,ou=people,dc=example,dc=com"=>30,
"uid=mary2,ou=people,dc=example,dc=com"=>30, "uid=john3,ou=people,dc=example,dc=com"=>30,
"uid=mary3,ou=people,dc=example,dc=com"=>30, "uid=john4,ou=people,dc=example,dc=com"=>30,
"uid=mary4,ou=people,dc=example,dc=com"=>30}
```
It's not uncommon to see warnings like the following. These indicate that GitLab
would have added the user to a group, but the user could not be found in GitLab.
Usually this is not a cause for concern.
If you think a particular user should already exist in GitLab, but you're seeing
this entry, it could be due to a mismatched DN stored in GitLab. See
[User DN and email have changed](#user-dn-and-email-have-changed) to update the user's LDAP identity.
```shell
User with DN `uid=john0,ou=people,dc=example,dc=com` should have access
to 'my_group' group but there is no user in GitLab with that
identity. Membership will be updated when the user signs in for
the first time.
```
Finally, the following entry says syncing has finished for this group:
```shell
Finished syncing all providers for 'my_group' group
```
When all the configured group links have been synchronized, GitLab looks
for any Administrators or External users to sync:
```shell
Syncing admin users for 'ldapmain' provider
```
The output looks similar to what happens with a single group, and then
this line indicates the sync is finished:
```shell
Finished syncing admin users for 'ldapmain' provider
```
If [administrator sync](ldap_synchronization.md#administrator-sync) is not configured, you see a message
stating as such:
```shell
No `admin_group` configured for 'ldapmain' provider. Skipping
```
#### Sync one group
[Syncing all groups](#sync-all-groups) can produce a lot of noise in the output, which can be
distracting when you're only interested in troubleshooting the memberships of
a single GitLab group. In that case, here's how you can just sync this group
and see its debug output:
```ruby
Rails.logger.level = Logger::DEBUG
# Find the GitLab group.
# If the output is `nil`, the group could not be found.
# If a bunch of group attributes are in the output, your group was found successfully.
group = Group.find_by(name: 'my_gitlab_group')
# Sync this group against LDAP
EE::Gitlab::Auth::Ldap::Sync::Group.execute_all_providers(group)
```
The output is similar to
[that you get from syncing all groups](#example-console-output-after-a-group-sync).
#### Query a group in LDAP
When you'd like to confirm that GitLab can read a LDAP group and see all its members,
you can run the following:
```ruby
# Find the adapter and the group itself
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
ldap_group = EE::Gitlab::Auth::Ldap::Group.find_by_cn('group_cn_here', adapter)
# Find the members of the LDAP group
ldap_group.member_dns
ldap_group.member_uids
```
#### LDAP synchronization does not remove group creator from group
[LDAP synchronization](ldap_synchronization.md) should remove an LDAP group's creator
from that group, if that user does not exist in the group. If running LDAP synchronization
does not do this:
1. Add the user to the LDAP group.
1. Wait until LDAP group synchronization has finished running.
1. Remove the user from the LDAP group.
### User DN and email have changed
If both the primary email **and** the DN change in LDAP, GitLab cannot identify the correct LDAP record of a user. As a
result, GitLab blocks that user. So that GitLab can find the LDAP record, update the user's existing GitLab profile with
at least either:
- The new primary email.
- DN values.
The following script updates the emails for all provided users so they aren't blocked or unable to access their accounts.
{{< alert type="note" >}}
The following script requires that any new accounts with the new
email address are removed first. Email addresses must be unique in GitLab.
{{< /alert >}}
Go to the [rails console](#rails-console) and then run:
```ruby
# Each entry must include the old username and the new email
emails = {
'ORIGINAL_USERNAME' => 'NEW_EMAIL_ADDRESS',
...
}
emails.each do |username, email|
user = User.find_by_username(username)
user.email = email
user.skip_reconfirmation!
user.save!
end
```
You can then [run a UserSync](#sync-all-users) to sync the latest DN
for each of these users.
## Could not authenticate from AzureActivedirectoryV2 because "Invalid grant"
When converting from LDAP to SAML you might get an error in Azure that states the following:
```plaintext
Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant.
```
This issue occurs when both of the following are true:
- LDAP identities still exist for users after SAML has been configured for those users.
- You disable LDAP for those users.
You would receive both LDAP and Azure metadata in the logs, which generates the error in Azure.
The workaround for a single user is to remove the LDAP identity from the user in **Admin** > **Identities**.
To remove multiple LDAP identities, use either of the workarounds for the [`Could not authenticate you from Ldapmain because "Unknown provider"` error](#could-not-authenticate-you-from-ldapmain-because-unknown-provider).
## `Could not authenticate you from Ldapmain because "Unknown provider"`
You can receive the following error when authenticating with an LDAP server:
```plaintext
Could not authenticate you from Ldapmain because "Unknown provider (ldapsecondary). available providers: ["ldapmain"]".
```
This error is caused when using an account that previously authenticated with an LDAP server that is renamed or removed from your GitLab configuration. For example:
- Initially, `main` and `secondary` are set in `ldap_servers` in GitLab configuration.
- The `secondary` setting is removed or renamed to `main`.
- A user attempting to sign in has an `identify` record for `secondary`, but that is no longer configured.
Use the [Rails console](../../operations/rails_console.md) to list affected users and check what LDAP servers they have identities for:
```ruby
ldap_identities = Identity.where(provider: "ldapsecondary")
ldap_identities.each do |identity|
u=User.find_by_id(identity.user_id)
ui=Identity.where(user_id: identity.user_id)
puts "user: #{u.username}\n #{u.email}\n last activity: #{u.last_activity_on}\n #{identity.provider} ID: #{identity.id} external: #{identity.extern_uid}"
puts " all identities:"
ui.each do |alli|
puts " - #{alli.provider} ID: #{alli.id} external: #{alli.extern_uid}"
end
end;nil
```
You can solve this error in two ways.
### Rename references to the LDAP server
This solution is suitable when the LDAP servers are replicas of each other, and the affected users should be able to sign in using a configured LDAP server.
For example, if a load balancer is now used to manage LDAP high availability and a separate secondary sign-in option is no longer needed.
{{< alert type="note" >}}
If the LDAP servers aren't replicas of each other, this solution stops affected users from being able to sign in.
{{< /alert >}}
To [rename references to the LDAP server](../../raketasks/ldap.md#other-options) that is no longer configured, run:
```shell
sudo gitlab-rake gitlab:ldap:rename_provider[ldapsecondary,ldapmain]
```
### Remove the `identity` records that relate to the removed LDAP server
Prerequisites:
- Ensure that `auto_link_ldap_user` is enabled.
With this solution, after the identity is deleted, affected users can sign in with the
configured LDAP servers and a new `identity` record is created by GitLab.
Because the LDAP server that was removed was `ldapsecondary`, in a [Rails console](../../operations/rails_console.md), delete all the `ldapsecondary` identities:
```ruby
ldap_identities = Identity.where(provider: "ldapsecondary")
ldap_identities.each do |identity|
puts "Destroying identity: #{identity.id} #{identity.provider}: #{identity.extern_uid}"
identity.destroy!
rescue => e
puts 'Error generated when destroying identity:\n ' + e.to_s
end; nil
```
## Expired license causes errors with multiple LDAP servers
Using [multiple LDAP servers](_index.md#use-multiple-ldap-servers) requires a valid license. An expired license can
cause:
- `502` errors in the web interface.
- The following error in logs (the actual strategy name depends on the name configured in `/etc/gitlab/gitlab.rb`):
```plaintext
Could not find a strategy with name `Ldapsecondary'. Please ensure it is required or explicitly set it using the :strategy_class option. (Devise::OmniAuth::StrategyNotFound)
```
To resolve this error, you must apply a new license to the GitLab instance without the web interface:
1. Remove or comment out the GitLab configuration lines for all non-primary LDAP servers.
1. [Reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so that it temporarily uses only one LDAP server.
1. Enter the [Rails console and add the license key](../../license_file.md#add-a-license-through-the-console).
1. Re-enable the additional LDAP servers in the GitLab configuration and reconfigure GitLab again.
## Users are being removed from group and re-added again
If a user has been added to a group during group sync, and removed at the next sync, and this has happened repeatedly, make sure that the user doesn't have
multiple or redundant LDAP identities.
If one of those identities was added for an older LDAP provider that is no longer in use, [remove the `identity` records that relate to the removed LDAP server](#remove-the-identity-records-that-relate-to-the-removed-ldap-server).
## Debugging Tools
### LDAP check
The [Rake task to check LDAP](../../raketasks/ldap.md#check) is a valuable tool
to help determine whether GitLab can successfully establish a connection to
LDAP and can get so far as to even read users.
If a connection can't be established, it is likely either because of a problem
with your configuration or a firewall blocking the connection.
- Ensure you don't have a firewall blocking the
connection, and that the LDAP server is accessible to the GitLab host.
- Look for an error message in the Rake check output, which may lead to your LDAP configuration to
confirm that the configuration values (specifically `host`, `port`, `bind_dn`, and
`password`) are correct.
- Look for [errors](#connection) in [the logs](#gitlab-logs) to further debug connection failures.
If GitLab can successfully connect to LDAP but doesn't return any
users, [see what to do when no users are found](#no-users-are-found).
### GitLab logs
If a user account is blocked or unblocked due to the LDAP configuration, a
message is [logged to `application_json.log`](../../logs/_index.md#application_jsonlog).
If there is an unexpected error during an LDAP lookup (configuration error,
timeout), the sign-in is rejected and a message is [logged to `production.log`](../../logs/_index.md#productionlog).
### ldapsearch
`ldapsearch` is a utility that allows you to query your LDAP server. You can
use it to test your LDAP settings and ensure that the settings you're using
get you the results you expect.
When using `ldapsearch`, be sure to use the same settings you've already
specified in your `gitlab.rb` configuration so you can confirm what happens
when those exact settings are used.
Running this command on the GitLab host also helps confirm that there's no
obstruction between the GitLab host and LDAP.
For example, consider the following GitLab configuration:
```shell
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # remember to close this block with 'EOS' below
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: '127.0.0.1'
port: 389
uid: 'uid'
encryption: 'plain'
bind_dn: 'cn=admin,dc=ldap-testing,dc=example,dc=com'
password: 'Password1'
active_directory: true
allow_username_or_email_login: false
block_auto_created_users: false
base: 'dc=ldap-testing,dc=example,dc=com'
user_filter: ''
attributes:
username: ['uid', 'userid', 'sAMAccountName']
email: ['mail', 'email', 'userPrincipalName']
name: 'cn'
first_name: 'givenName'
last_name: 'sn'
group_base: 'ou=groups,dc=ldap-testing,dc=example,dc=com'
admin_group: 'gitlab_admin'
EOS
```
You would run the following `ldapsearch` to find the `bind_dn` user:
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-p 389 \
-h 127.0.0.1 \
-b "dc=ldap-testing,dc=example,dc=com"
```
The `bind_dn`, `password`, `port`, `host`, and `base` are all
identical to what's configured in the `gitlab.rb`.
#### Use ldapsearch with `start_tls` encryption
The previous example performs an LDAP test in plaintext to port 389. If you are using [`start_tls` encryption](_index.md#basic-configuration-settings), in
the `ldapsearch` command include:
- The `-Z` flag.
- The FQDN of the LDAP server.
You must include these because, during TLS negotiation, the FQDN of the LDAP server is evaluated against its certificate:
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-p 389 \
-h "testing.ldap.com" \
-b "dc=ldap-testing,dc=example,dc=com" -Z
```
#### Use ldapsearch with `simple_tls` encryption
If you are using [`simple_tls` encryption](_index.md#basic-configuration-settings) (usually on port 636), include the following in the `ldapsearch` command:
- The LDAP server FQDN with the `-H` flag and the port.
- The full constructed URI.
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-H "ldaps://testing.ldap.com:636" \
-b "dc=ldap-testing,dc=example,dc=com"
```
For more information, see the [official `ldapsearch` documentation](https://linux.die.net/man/1/ldapsearch).
### Using **AdFind** (Windows)
You can use the [`AdFind`](https://learn.microsoft.com/en-us/archive/technet-wiki/7535.adfind-command-examples) utility (on Windows based systems) to test that your LDAP server is accessible and authentication is working correctly. AdFind is a freeware utility built by [Joe Richards](https://www.joeware.net/freetools/tools/adfind/index.htm).
**Return all objects**
You can use the filter `objectclass=*` to return all directory objects.
```shell
adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f (objectClass=*)
```
**Return single object using filter**
You can also retrieve a single object by **specifying** the object name or full **DN**. In this example we specify the object name only `CN=Leroy Fox`.
```shell
adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f "(&(objectcategory=person)(CN=Leroy Fox))"
```
### Rails console
{{< alert type="warning" >}}
It is very easy to create, read, modify, and destroy data with the rails
console. Be sure to run commands exactly as listed.
{{< /alert >}}
The rails console is a valuable tool to help debug LDAP problems. It allows you to
directly interact with the application by running commands and seeing how GitLab
responds to them.
For instructions about how to use the rails console, refer to this
[guide](../../operations/rails_console.md#starting-a-rails-console-session).
#### Enable debug output
This provides debug output that shows what GitLab is doing and with what.
This value is not persisted, and is only enabled for this session in the Rails console.
To enable debug output in the rails console, [enter the rails console](#rails-console) and run:
```ruby
Rails.logger.level = Logger::DEBUG
```
#### Get all error messages associated with groups, subgroups, members, and requesters
Collect error messages associated with groups, subgroups, members, and requesters. This
captures error messages that may not appear in the Web interface. This can be especially helpful
for troubleshooting issues with [LDAP group sync](ldap_synchronization.md#group-sync)
and unexpected behavior with users and their membership in groups and subgroups.
```ruby
# Find the group and subgroup
group = Group.find_by_full_path("parent_group")
subgroup = Group.find_by_full_path("parent_group/child_group")
# Group and subgroup errors
group.valid?
group.errors.map(&:full_messages)
subgroup.valid?
subgroup.errors.map(&:full_messages)
# Group and subgroup errors for the members AND requesters
group.requesters.map(&:valid?)
group.requesters.map(&:errors).map(&:full_messages)
group.members.map(&:valid?)
group.members.map(&:errors).map(&:full_messages)
group.members_and_requesters.map(&:errors).map(&:full_messages)
subgroup.requesters.map(&:valid?)
subgroup.requesters.map(&:errors).map(&:full_messages)
subgroup.members.map(&:valid?)
subgroup.members.map(&:errors).map(&:full_messages)
subgroup.members_and_requesters.map(&:errors).map(&:full_messages)
```
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting LDAP
breadcrumbs:
- doc
- administration
- auth
- ldap
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you are an administrator, use the following information to troubleshoot LDAP.
## Common Problems & Workflows
### Connection
#### Connection refused
If you're getting `Connection Refused` error messages when attempting to
connect to the LDAP server, review the LDAP `port` and `encryption` settings
used by GitLab. Common combinations are `encryption: 'plain'` and `port: 389`,
or `encryption: 'simple_tls'` and `port: 636`.
#### Connection times out
If GitLab cannot reach your LDAP endpoint, you see a message like this:
```plaintext
Could not authenticate you from Ldapmain because "Connection timed out - user specified timeout".
```
If your configured LDAP provider and/or endpoint is offline or otherwise
unreachable by GitLab, no LDAP user is able to authenticate and sign-in.
GitLab does not cache or store credentials for LDAP users to provide authentication
during an LDAP outage.
Contact your LDAP provider or administrator if you are seeing this error.
#### Referral error
If you see `LDAP search error: Referral` in the logs, or when troubleshooting
LDAP Group Sync, this error may indicate a configuration problem. The LDAP
configuration `/etc/gitlab/gitlab.rb` (Omnibus) or `config/gitlab.yml` (source)
is in YAML format and is sensitive to indentation. Check that `group_base` and
`admin_group` configuration keys are indented 2 spaces past the server
identifier. The default identifier is `main` and an example snippet looks like
the following:
```yaml
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: 'ldap.example.com'
# ...
group_base: 'cn=my_group,ou=groups,dc=example,dc=com'
admin_group: 'my_admin_group'
```
#### Query LDAP
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The following allows you to perform a search in LDAP using the rails console.
Depending on what you're trying to do, it may make more sense to query [a user](#query-a-user-in-ldap)
or [a group](#query-a-group-in-ldap) directly, or even [use `ldapsearch`](#ldapsearch) instead.
```ruby
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
# :base is required
# use .base or .group_base
base: adapter.config.group_base,
# :filter is optional
# 'cn' looks for all "cn"s under :base
# '*' is the search string - here, it's a wildcard
filter: Net::LDAP::Filter.eq('cn', '*'),
# :attributes is optional
# the attributes we want to get returned
attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)
```
When using OIDs in the filter, replace `Net::LDAP::Filter.eq` with `Net::LDAP::Filter.construct`:
```ruby
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
# :base is required
# use .base or .group_base
base: adapter.config.base,
# :filter is optional
# This filter includes OID 1.2.840.113556.1.4.1941
# It will search for all direct and nested members of the group gitlab_grp in the LDAP directory
filter: Net::LDAP::Filter.construct("(memberOf:1.2.840.113556.1.4.1941:=CN=gitlab_grp,DC=example,DC=com)"),
# :attributes is optional
# the attributes we want to get returned
attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)
```
For examples of how this is run,
[review the `Adapter` module](https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/lib/ee/gitlab/auth/ldap/adapter.rb).
### User sign-ins
#### No users are found
If [you've confirmed](#ldap-check) that a connection to LDAP can be
established but GitLab doesn't show you LDAP users in the output, one of the
following is most likely true:
- The `bind_dn` user doesn't have enough permissions to traverse the user tree.
- The users don't fall under the [configured `base`](_index.md#configure-ldap).
- The [configured `user_filter`](_index.md#set-up-ldap-user-filter) blocks access to the users.
In this case, you can confirm which of the previous is true using
[ldapsearch](#ldapsearch) with the existing LDAP configuration in your
`/etc/gitlab/gitlab.rb`.
#### Users cannot sign-in
A user can have trouble signing in for any number of reasons. To get started,
here are some questions to ask yourself:
- Does the user fall under the [configured `base`](_index.md#configure-ldap) in
LDAP? The user must fall under this `base` to sign in.
- Does the user pass through the [configured `user_filter`](_index.md#set-up-ldap-user-filter)?
If one is not configured, this question can be ignored. If it is, then the
user must also pass through this filter to be allowed to sign in.
- Refer to our documentation on [debugging the `user_filter`](#debug-ldap-user-filter).
If the previous questions are both okay, the next place to look for the problem is
the logs themselves while reproducing the issue.
- Ask the user to sign in and let it fail.
- [Look through the output](#gitlab-logs) for any errors or other
messages about the sign-in. You may see one of the other error messages on
this page, in which case that section can help resolve the issue.
If the logs don't lead to the root of the problem, use the
[rails console](#rails-console) to [query this user](#query-a-user-in-ldap)
to see if GitLab can read this user on the LDAP server.
It can also be helpful to
[debug a user sync](#sync-all-users) to
investigate further.
#### Users see an error "Invalid login or password."
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/438144) in GitLab 16.10.
{{< /history >}}
If users see this error, it might be because they are trying to sign in using the **Standard** sign-in form instead of the **LDAP** sign-in form.
To resolve, ask the user to enter their LDAP username and password into the **LDAP** sign-in form.
#### Invalid credentials on sign-in
If that the sign-in credentials used are accurate on LDAP, ensure the following
are true for the user in question:
- Make sure the user you are binding with has enough permissions to read the user's
tree and traverse it.
- Check that the `user_filter` is not blocking otherwise valid users.
- Run [an LDAP check command](#ldap-check) to make sure that the LDAP settings
are correct and [GitLab can see your users](#no-users-are-found).
#### Access denied for your LDAP account
There is [a bug](https://gitlab.com/gitlab-org/gitlab/-/issues/235930) that
may affect users with [Auditor level access](../../auditor_users.md). When
downgrading from Premium/Ultimate, Auditor users who try to sign in
may see the following message: `Access denied for your LDAP account`.
We have a workaround, based on toggling the access level of affected users:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Overview** > **Users**.
1. Select the name of the affected user.
1. In the upper-right corner, select **Edit**.
1. Change the user's access level from `Regular` to `Administrator` (or vice versa).
1. At the bottom of the page, select **Save changes**.
1. In the upper-right corner, select **Edit** again.
1. Restore the user's original access level (`Regular` or `Administrator`)
and select **Save changes** again.
The user should now be able to sign in.
#### Email has already been taken
A user tries to sign in with the correct LDAP credentials, is denied access,
and the [production.log](../../logs/_index.md#productionlog) shows an error that looks like this:
```plaintext
(LDAP) Error saving user <USER DN> (email@example.com): ["Email has already been taken"]
```
This error is referring to the email address in LDAP, `email@example.com`. Email
addresses must be unique in GitLab and LDAP links to a user's primary email (as opposed
to any of their possibly-numerous secondary emails). Another user (or even the
same user) has the email `email@example.com` set as a secondary email, which
is throwing this error.
We can check where this conflicting email address is coming from using the
[rails console](#rails-console). In the console, run the following:
```ruby
# This searches for an email among the primary AND secondary emails
user = User.find_by_any_email('email@example.com')
user.username
```
This shows you which user has this email address. One of two steps must be taken here:
- To create a new GitLab user/username for this user when signing in with LDAP,
remove the secondary email to remove the conflict.
- To use an existing GitLab user/username for this user to use with LDAP,
remove this email as a secondary email and make it a primary one so GitLab
associates this profile to the LDAP identity.
The user can do either of these steps
[in their profile](../../../user/profile/_index.md#access-your-user-profile) or an administrator can do it.
#### Projects limit errors
The following errors indicate that a limit or restriction is activated, but an associated data
field contains no data:
- `Projects limit can't be blank`.
- `Projects limit is not a number`.
To resolve this:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings** > **General**.
1. Expand both of the following:
- **Account and limit**.
- **Sign-up restrictions**.
1. Check, for example, the **Default projects limit** or **Allowed domains for sign-ups**
fields and ensure that a relevant value is configured.
#### Debug LDAP user filter
[`ldapsearch`](#ldapsearch) allows you to test your configured
[user filter](_index.md#set-up-ldap-user-filter)
to confirm that it returns the users you expect it to return.
```shell
ldapsearch -H ldaps://$host:$port -D "$bind_dn" -y bind_dn_password.txt -b "$base" "$user_filter" sAMAccountName
```
- Variables beginning with a `$` refer to a variable from the LDAP section of
your configuration file.
- Replace `ldaps://` with `ldap://` if you are using the plain authentication method.
Port `389` is the default `ldap://` port and `636` is the default `ldaps://`
port.
- We are assuming the password for the `bind_dn` user is in `bind_dn_password.txt`.
#### Sync all users
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The output from a manual [user sync](ldap_synchronization.md#user-sync) can show you what happens when
GitLab tries to sync its users against LDAP. Enter the [rails console](#rails-console)
and then run:
```ruby
Rails.logger.level = Logger::DEBUG
LdapSyncWorker.new.perform
```
Next, [learn how to read the output](#example-console-output-after-a-user-sync).
##### Example console output after a user sync
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The output from a [manual user sync](#sync-all-users) is very verbose, and a
single user's successful sync can look like this:
```shell
Syncing user John, email@example.com
Identity Load (0.9ms) SELECT "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1
Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John
UserSyncedAttributesMetadata Load (0.9ms) SELECT "user_synced_attributes_metadata".* FROM "user_synced_attributes_metadata" WHERE "user_synced_attributes_metadata"."user_id" = 20 LIMIT 1
(0.3ms) BEGIN
Namespace Load (1.0ms) SELECT "namespaces".* FROM "namespaces" WHERE "namespaces"."owner_id" = 20 AND "namespaces"."type" IS NULL LIMIT 1
Route Load (0.8ms) SELECT "routes".* FROM "routes" WHERE "routes"."source_id" = 27 AND "routes"."source_type" = 'Namespace' LIMIT 1
Ci::Runner Load (1.1ms) SELECT "ci_runners".* FROM "ci_runners" INNER JOIN "ci_runner_namespaces" ON "ci_runners"."id" = "ci_runner_namespaces"."runner_id" WHERE "ci_runner_namespaces"."namespace_id" = 27
(0.7ms) COMMIT
(0.4ms) BEGIN
Route Load (0.8ms) SELECT "routes".* FROM "routes" WHERE (LOWER("routes"."path") = LOWER('John'))
Namespace Load (1.0ms) SELECT "namespaces".* FROM "namespaces" WHERE "namespaces"."id" = 27 LIMIT 1
Route Exists (0.9ms) SELECT 1 AS one FROM "routes" WHERE LOWER("routes"."path") = LOWER('John') AND "routes"."id" != 50 LIMIT 1
User Update (1.1ms) UPDATE "users" SET "updated_at" = '2019-10-17 14:40:59.751685', "last_credential_check_at" = '2019-10-17 14:40:59.738714' WHERE "users"."id" = 20
```
There's a lot here, so let's go over what could be helpful when debugging.
First, GitLab looks for all users that have previously
signed in with LDAP and iterate on them. Each user's sync starts with
the following line that contains the user's username and email, as they
exist in GitLab now:
```shell
Syncing user John, email@example.com
```
If you don't find a particular user's GitLab email in the output, then that
user hasn't signed in with LDAP yet.
Next, GitLab searches its `identities` table for the existing
link between this user and the configured LDAP providers:
```sql
Identity Load (0.9ms) SELECT "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1
```
The identity object has the DN that GitLab uses to look for the user
in LDAP. If the DN isn't found, the email is used instead. We can see that
this user is found in LDAP:
```shell
Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John
```
If the user wasn't found in LDAP with either the DN or email, you might see the
following message instead:
```shell
LDAP search error: No Such Object
```
In this case, the user is blocked:
```shell
User Update (0.4ms) UPDATE "users" SET "state" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["state", "ldap_blocked"], ["updated_at", "2019-10-18 15:46:22.902177"], ["id", 20]]
```
After the user is found in LDAP, the rest of the output updates the GitLab
database with any changes.
#### Query a user in LDAP
This tests that GitLab can reach out to LDAP and read a particular user.
It can expose potential errors connecting to and/or querying LDAP
that may seem to fail silently in the GitLab UI.
```ruby
Rails.logger.level = Logger::DEBUG
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
Gitlab::Auth::Ldap::Person.find_by_uid('<uid>', adapter)
```
### Group memberships
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
#### Memberships not granted
Sometimes you may think a particular user should be added to a GitLab group through
LDAP group sync, but for some reason it's not happening. You can check several
things to debug the situation.
- Ensure LDAP configuration has a `group_base` specified.
[This configuration](ldap_synchronization.md#group-sync) is required for group sync to work properly.
- Ensure the correct [LDAP group link is added to the GitLab group](ldap_synchronization.md#add-group-links).
- Check that the user has an LDAP identity:
1. Sign in to GitLab as an administrator user.
1. On the left sidebar, at the bottom, select **Admin**.
1. On the left sidebar, select **Overview** > **Users**.
1. Search for the user.
1. Open the user by selecting their name. Do not select **Edit**.
1. Select the **Identities** tab. There should be an LDAP identity with
an LDAP DN as the `Identifier`. If not, this user hasn't signed in with
LDAP yet and must do so first.
- You've waited an hour or [the configured interval](ldap_synchronization.md#adjust-ldap-group-sync-schedule) for
the group to sync. To speed up the process, either go to the GitLab group **Manage** > **Members**
and press **Sync now** (sync one group) or [run the group sync Rake task](../../raketasks/ldap.md#run-a-group-sync)
(sync all groups).
If all of the checks looks good, jump in to a little more advanced debugging in
the rails console.
1. Enter the [rails console](#rails-console).
1. Choose a GitLab group to test with. This group should have an LDAP group link
already configured.
1. Enable debug logging, find the chosen GitLab group, and [sync it with LDAP](#sync-one-group).
1. Look through the output of the sync. See [example log output](#example-console-output-after-a-group-sync)
for how to read the output.
1. If you still aren't able to see why the user isn't being added, [query the LDAP group directly](#query-a-group-in-ldap)
to see what members are listed.
1. Is the user's DN or UID in one of the lists from the queried group? One of the DNs or
UIDs here should match the 'Identifier' from the LDAP identity checked earlier. If it doesn't,
the user does not appear to be in the LDAP group.
#### Cannot add service account user to group when LDAP sync is enabled
When LDAP sync is enabled for a group, you cannot use the "invite" dialog to invite new group members.
To resolve this issue in GitLab 16.8 and later, you can invite service accounts to and remove them from a group using the [group members API endpoints](../../../api/members.md#add-a-member-to-a-group-or-project).
#### Administrator privileges not granted
When [Administrator sync](ldap_synchronization.md#administrator-sync) has been configured
but the configured users aren't granted the correct administrator privileges, confirm
that the following conditions are true:
- A [`group_base` is also configured](ldap_synchronization.md#group-sync).
- The configured `admin_group` in the `gitlab.rb` is a CN, rather than a DN or an array.
- This CN falls under the scope of the configured `group_base`.
- The members of the `admin_group` have already signed into GitLab with their LDAP
credentials. GitLab only grants administrator access to the users whose
accounts are already connected to LDAP.
If all the previous conditions are true and the users are still not getting access,
[run a manual group sync](#sync-all-groups) in the rails console and
[look through the output](#example-console-output-after-a-group-sync) to see what happens when
GitLab syncs the `admin_group`.
#### Sync now button stuck in the UI
The **Sync now** button on the **Group** > **Members** page of a group can become stuck. The button becomes stuck after it is pressed and the page is reloaded. The button then
cannot be selected again.
The **Sync now** button can become stuck for many reasons and requires debugging for specific cases. The following are two possible causes and possible solutions to the problem.
##### Invalid memberships
The **Sync now** button becomes stuck if some of the group's members or requesting members are invalid. You can track progress on improving the visibility of this problem in
a [relevant issue](https://gitlab.com/gitlab-org/gitlab/-/issues/348226). You can use a [Rails console](#rails-console) to confirm if this problem is causing the **Sync now**
button to be stuck:
```ruby
# Find the group in question
group = Group.find_by(name: 'my_gitlab_group')
# Look for errors on the Group itself
group.valid?
group.errors.map(&:full_messages)
# Look for errors among the group's members and requesters
group.requesters.map(&:valid?)
group.requesters.map(&:errors).map(&:full_messages)
group.members.map(&:valid?)
group.members.map(&:errors).map(&:full_messages)
```
A displayed error can identify the problem and point to a solution. For example, the Support Team has seen the following error:
```ruby
irb(main):018:0> group.members.map(&:errors).map(&:full_messages)
=> [["The member's email address is not allowed for this group. Go to the group's 'Settings > General' page, and check 'Restrict membership by email domain'."]]
```
This error showed that an Administrator chose to [restrict group membership by email domain](../../../user/group/access_and_permissions.md#restrict-group-access-by-domain),
but there was a typo in the domain. After the domain setting was fixed, the **Sync now** button functioned again.
##### Missing LDAP configuration on Sidekiq nodes
The **Sync now** button becomes stuck when GitLab is scaled over multiple nodes and the LDAP configuration is missing from
[the `/etc/gitlab/gitlab.rb` on the nodes running Sidekiq](../../sidekiq/_index.md#configure-ldap-and-user-or-group-synchronization).
In this case, the Sidekiq jobs seem to disappear.
LDAP is required on the Sidekiq nodes because LDAP has multiple jobs that are
run asynchronously that require a local LDAP configuration:
- [User sync](ldap_synchronization.md#user-sync).
- [Group sync](ldap_synchronization.md#group-sync).
You can test whether missing LDAP configuration is the problem by running [the Rake task to check LDAP](#ldap-check)
on each node that is running Sidekiq. If LDAP is set up correctly on this node, it connects to the LDAP server and returns users.
To solve this issue, [configure LDAP](../../sidekiq/_index.md#configure-ldap-and-user-or-group-synchronization) on the Sidekiq nodes.
When configured, run [the Rake task to check LDAP](#ldap-check) to confirm
that the GitLab node can connect to LDAP.
#### Sync all groups
{{< alert type="note" >}}
To sync all groups manually when debugging is unnecessary,
[use the Rake task](../../raketasks/ldap.md#run-a-group-sync) instead.
{{< /alert >}}
The output from a manual [group sync](ldap_synchronization.md#group-sync) can show you what happens
when GitLab syncs its LDAP group memberships against LDAP. Enter the [rails console](#rails-console)
and then run:
```ruby
Rails.logger.level = Logger::DEBUG
LdapAllGroupsSyncWorker.new.perform
```
Next, [learn how to read the output](#example-console-output-after-a-group-sync).
##### Example console output after a group sync
Like the output from the user sync, the output from the
[manual group sync](#sync-all-groups) is also very verbose. However, it contains lots
of helpful information.
Indicates the point where syncing actually begins:
```shell
Started syncing 'ldapmain' provider for 'my_group' group
```
The following entry shows an array of all user DNs GitLab sees in the LDAP server.
These DNs are the users for a single LDAP group, not a GitLab group. If
you have multiple LDAP groups linked to this GitLab group, you see multiple
log entries like this - one for each LDAP group. If you don't see an LDAP user
DN in this log entry, LDAP is not returning the user when we do the lookup.
Verify the user is actually in the LDAP group.
```shell
Members in 'ldap_group_1' LDAP group: ["uid=john0,ou=people,dc=example,dc=com",
"uid=mary0,ou=people,dc=example,dc=com", "uid=john1,ou=people,dc=example,dc=com",
"uid=mary1,ou=people,dc=example,dc=com", "uid=john2,ou=people,dc=example,dc=com",
"uid=mary2,ou=people,dc=example,dc=com", "uid=john3,ou=people,dc=example,dc=com",
"uid=mary3,ou=people,dc=example,dc=com", "uid=john4,ou=people,dc=example,dc=com",
"uid=mary4,ou=people,dc=example,dc=com"]
```
Shortly after each of the entries, you see a hash of resolved member
access levels. This hash represents all user DNs GitLab thinks should have
access to this group, and at which access level (role). This hash is additive,
and more DNs may be added, or existing entries modified, based on additional
LDAP group lookups. The very last occurrence of this entry should indicate
exactly which users GitLab believes should be added to the group.
{{< alert type="note" >}}
10 is `Guest`, 20 is `Reporter`, 30 is `Developer`, 40 is `Maintainer`
and 50 is `Owner`.
{{< /alert >}}
```shell
Resolved 'my_group' group member access: {"uid=john0,ou=people,dc=example,dc=com"=>30,
"uid=mary0,ou=people,dc=example,dc=com"=>30, "uid=john1,ou=people,dc=example,dc=com"=>30,
"uid=mary1,ou=people,dc=example,dc=com"=>30, "uid=john2,ou=people,dc=example,dc=com"=>30,
"uid=mary2,ou=people,dc=example,dc=com"=>30, "uid=john3,ou=people,dc=example,dc=com"=>30,
"uid=mary3,ou=people,dc=example,dc=com"=>30, "uid=john4,ou=people,dc=example,dc=com"=>30,
"uid=mary4,ou=people,dc=example,dc=com"=>30}
```
It's not uncommon to see warnings like the following. These indicate that GitLab
would have added the user to a group, but the user could not be found in GitLab.
Usually this is not a cause for concern.
If you think a particular user should already exist in GitLab, but you're seeing
this entry, it could be due to a mismatched DN stored in GitLab. See
[User DN and email have changed](#user-dn-and-email-have-changed) to update the user's LDAP identity.
```shell
User with DN `uid=john0,ou=people,dc=example,dc=com` should have access
to 'my_group' group but there is no user in GitLab with that
identity. Membership will be updated when the user signs in for
the first time.
```
Finally, the following entry says syncing has finished for this group:
```shell
Finished syncing all providers for 'my_group' group
```
When all the configured group links have been synchronized, GitLab looks
for any Administrators or External users to sync:
```shell
Syncing admin users for 'ldapmain' provider
```
The output looks similar to what happens with a single group, and then
this line indicates the sync is finished:
```shell
Finished syncing admin users for 'ldapmain' provider
```
If [administrator sync](ldap_synchronization.md#administrator-sync) is not configured, you see a message
stating as such:
```shell
No `admin_group` configured for 'ldapmain' provider. Skipping
```
#### Sync one group
[Syncing all groups](#sync-all-groups) can produce a lot of noise in the output, which can be
distracting when you're only interested in troubleshooting the memberships of
a single GitLab group. In that case, here's how you can just sync this group
and see its debug output:
```ruby
Rails.logger.level = Logger::DEBUG
# Find the GitLab group.
# If the output is `nil`, the group could not be found.
# If a bunch of group attributes are in the output, your group was found successfully.
group = Group.find_by(name: 'my_gitlab_group')
# Sync this group against LDAP
EE::Gitlab::Auth::Ldap::Sync::Group.execute_all_providers(group)
```
The output is similar to
[that you get from syncing all groups](#example-console-output-after-a-group-sync).
#### Query a group in LDAP
When you'd like to confirm that GitLab can read a LDAP group and see all its members,
you can run the following:
```ruby
# Find the adapter and the group itself
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
ldap_group = EE::Gitlab::Auth::Ldap::Group.find_by_cn('group_cn_here', adapter)
# Find the members of the LDAP group
ldap_group.member_dns
ldap_group.member_uids
```
#### LDAP synchronization does not remove group creator from group
[LDAP synchronization](ldap_synchronization.md) should remove an LDAP group's creator
from that group, if that user does not exist in the group. If running LDAP synchronization
does not do this:
1. Add the user to the LDAP group.
1. Wait until LDAP group synchronization has finished running.
1. Remove the user from the LDAP group.
### User DN and email have changed
If both the primary email **and** the DN change in LDAP, GitLab cannot identify the correct LDAP record of a user. As a
result, GitLab blocks that user. So that GitLab can find the LDAP record, update the user's existing GitLab profile with
at least either:
- The new primary email.
- DN values.
The following script updates the emails for all provided users so they aren't blocked or unable to access their accounts.
{{< alert type="note" >}}
The following script requires that any new accounts with the new
email address are removed first. Email addresses must be unique in GitLab.
{{< /alert >}}
Go to the [rails console](#rails-console) and then run:
```ruby
# Each entry must include the old username and the new email
emails = {
'ORIGINAL_USERNAME' => 'NEW_EMAIL_ADDRESS',
...
}
emails.each do |username, email|
user = User.find_by_username(username)
user.email = email
user.skip_reconfirmation!
user.save!
end
```
You can then [run a UserSync](#sync-all-users) to sync the latest DN
for each of these users.
## Could not authenticate from AzureActivedirectoryV2 because "Invalid grant"
When converting from LDAP to SAML you might get an error in Azure that states the following:
```plaintext
Authentication failure! invalid_credentials: OAuth2::Error, invalid_grant.
```
This issue occurs when both of the following are true:
- LDAP identities still exist for users after SAML has been configured for those users.
- You disable LDAP for those users.
You would receive both LDAP and Azure metadata in the logs, which generates the error in Azure.
The workaround for a single user is to remove the LDAP identity from the user in **Admin** > **Identities**.
To remove multiple LDAP identities, use either of the workarounds for the [`Could not authenticate you from Ldapmain because "Unknown provider"` error](#could-not-authenticate-you-from-ldapmain-because-unknown-provider).
## `Could not authenticate you from Ldapmain because "Unknown provider"`
You can receive the following error when authenticating with an LDAP server:
```plaintext
Could not authenticate you from Ldapmain because "Unknown provider (ldapsecondary). available providers: ["ldapmain"]".
```
This error is caused when using an account that previously authenticated with an LDAP server that is renamed or removed from your GitLab configuration. For example:
- Initially, `main` and `secondary` are set in `ldap_servers` in GitLab configuration.
- The `secondary` setting is removed or renamed to `main`.
- A user attempting to sign in has an `identify` record for `secondary`, but that is no longer configured.
Use the [Rails console](../../operations/rails_console.md) to list affected users and check what LDAP servers they have identities for:
```ruby
ldap_identities = Identity.where(provider: "ldapsecondary")
ldap_identities.each do |identity|
u=User.find_by_id(identity.user_id)
ui=Identity.where(user_id: identity.user_id)
puts "user: #{u.username}\n #{u.email}\n last activity: #{u.last_activity_on}\n #{identity.provider} ID: #{identity.id} external: #{identity.extern_uid}"
puts " all identities:"
ui.each do |alli|
puts " - #{alli.provider} ID: #{alli.id} external: #{alli.extern_uid}"
end
end;nil
```
You can solve this error in two ways.
### Rename references to the LDAP server
This solution is suitable when the LDAP servers are replicas of each other, and the affected users should be able to sign in using a configured LDAP server.
For example, if a load balancer is now used to manage LDAP high availability and a separate secondary sign-in option is no longer needed.
{{< alert type="note" >}}
If the LDAP servers aren't replicas of each other, this solution stops affected users from being able to sign in.
{{< /alert >}}
To [rename references to the LDAP server](../../raketasks/ldap.md#other-options) that is no longer configured, run:
```shell
sudo gitlab-rake gitlab:ldap:rename_provider[ldapsecondary,ldapmain]
```
### Remove the `identity` records that relate to the removed LDAP server
Prerequisites:
- Ensure that `auto_link_ldap_user` is enabled.
With this solution, after the identity is deleted, affected users can sign in with the
configured LDAP servers and a new `identity` record is created by GitLab.
Because the LDAP server that was removed was `ldapsecondary`, in a [Rails console](../../operations/rails_console.md), delete all the `ldapsecondary` identities:
```ruby
ldap_identities = Identity.where(provider: "ldapsecondary")
ldap_identities.each do |identity|
puts "Destroying identity: #{identity.id} #{identity.provider}: #{identity.extern_uid}"
identity.destroy!
rescue => e
puts 'Error generated when destroying identity:\n ' + e.to_s
end; nil
```
## Expired license causes errors with multiple LDAP servers
Using [multiple LDAP servers](_index.md#use-multiple-ldap-servers) requires a valid license. An expired license can
cause:
- `502` errors in the web interface.
- The following error in logs (the actual strategy name depends on the name configured in `/etc/gitlab/gitlab.rb`):
```plaintext
Could not find a strategy with name `Ldapsecondary'. Please ensure it is required or explicitly set it using the :strategy_class option. (Devise::OmniAuth::StrategyNotFound)
```
To resolve this error, you must apply a new license to the GitLab instance without the web interface:
1. Remove or comment out the GitLab configuration lines for all non-primary LDAP servers.
1. [Reconfigure GitLab](../../restart_gitlab.md#reconfigure-a-linux-package-installation) so that it temporarily uses only one LDAP server.
1. Enter the [Rails console and add the license key](../../license_file.md#add-a-license-through-the-console).
1. Re-enable the additional LDAP servers in the GitLab configuration and reconfigure GitLab again.
## Users are being removed from group and re-added again
If a user has been added to a group during group sync, and removed at the next sync, and this has happened repeatedly, make sure that the user doesn't have
multiple or redundant LDAP identities.
If one of those identities was added for an older LDAP provider that is no longer in use, [remove the `identity` records that relate to the removed LDAP server](#remove-the-identity-records-that-relate-to-the-removed-ldap-server).
## Debugging Tools
### LDAP check
The [Rake task to check LDAP](../../raketasks/ldap.md#check) is a valuable tool
to help determine whether GitLab can successfully establish a connection to
LDAP and can get so far as to even read users.
If a connection can't be established, it is likely either because of a problem
with your configuration or a firewall blocking the connection.
- Ensure you don't have a firewall blocking the
connection, and that the LDAP server is accessible to the GitLab host.
- Look for an error message in the Rake check output, which may lead to your LDAP configuration to
confirm that the configuration values (specifically `host`, `port`, `bind_dn`, and
`password`) are correct.
- Look for [errors](#connection) in [the logs](#gitlab-logs) to further debug connection failures.
If GitLab can successfully connect to LDAP but doesn't return any
users, [see what to do when no users are found](#no-users-are-found).
### GitLab logs
If a user account is blocked or unblocked due to the LDAP configuration, a
message is [logged to `application_json.log`](../../logs/_index.md#application_jsonlog).
If there is an unexpected error during an LDAP lookup (configuration error,
timeout), the sign-in is rejected and a message is [logged to `production.log`](../../logs/_index.md#productionlog).
### ldapsearch
`ldapsearch` is a utility that allows you to query your LDAP server. You can
use it to test your LDAP settings and ensure that the settings you're using
get you the results you expect.
When using `ldapsearch`, be sure to use the same settings you've already
specified in your `gitlab.rb` configuration so you can confirm what happens
when those exact settings are used.
Running this command on the GitLab host also helps confirm that there's no
obstruction between the GitLab host and LDAP.
For example, consider the following GitLab configuration:
```shell
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # remember to close this block with 'EOS' below
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: '127.0.0.1'
port: 389
uid: 'uid'
encryption: 'plain'
bind_dn: 'cn=admin,dc=ldap-testing,dc=example,dc=com'
password: 'Password1'
active_directory: true
allow_username_or_email_login: false
block_auto_created_users: false
base: 'dc=ldap-testing,dc=example,dc=com'
user_filter: ''
attributes:
username: ['uid', 'userid', 'sAMAccountName']
email: ['mail', 'email', 'userPrincipalName']
name: 'cn'
first_name: 'givenName'
last_name: 'sn'
group_base: 'ou=groups,dc=ldap-testing,dc=example,dc=com'
admin_group: 'gitlab_admin'
EOS
```
You would run the following `ldapsearch` to find the `bind_dn` user:
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-p 389 \
-h 127.0.0.1 \
-b "dc=ldap-testing,dc=example,dc=com"
```
The `bind_dn`, `password`, `port`, `host`, and `base` are all
identical to what's configured in the `gitlab.rb`.
#### Use ldapsearch with `start_tls` encryption
The previous example performs an LDAP test in plaintext to port 389. If you are using [`start_tls` encryption](_index.md#basic-configuration-settings), in
the `ldapsearch` command include:
- The `-Z` flag.
- The FQDN of the LDAP server.
You must include these because, during TLS negotiation, the FQDN of the LDAP server is evaluated against its certificate:
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-p 389 \
-h "testing.ldap.com" \
-b "dc=ldap-testing,dc=example,dc=com" -Z
```
#### Use ldapsearch with `simple_tls` encryption
If you are using [`simple_tls` encryption](_index.md#basic-configuration-settings) (usually on port 636), include the following in the `ldapsearch` command:
- The LDAP server FQDN with the `-H` flag and the port.
- The full constructed URI.
```shell
ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" \
-w Password1 \
-H "ldaps://testing.ldap.com:636" \
-b "dc=ldap-testing,dc=example,dc=com"
```
For more information, see the [official `ldapsearch` documentation](https://linux.die.net/man/1/ldapsearch).
### Using **AdFind** (Windows)
You can use the [`AdFind`](https://learn.microsoft.com/en-us/archive/technet-wiki/7535.adfind-command-examples) utility (on Windows based systems) to test that your LDAP server is accessible and authentication is working correctly. AdFind is a freeware utility built by [Joe Richards](https://www.joeware.net/freetools/tools/adfind/index.htm).
**Return all objects**
You can use the filter `objectclass=*` to return all directory objects.
```shell
adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f (objectClass=*)
```
**Return single object using filter**
You can also retrieve a single object by **specifying** the object name or full **DN**. In this example we specify the object name only `CN=Leroy Fox`.
```shell
adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f "(&(objectcategory=person)(CN=Leroy Fox))"
```
### Rails console
{{< alert type="warning" >}}
It is very easy to create, read, modify, and destroy data with the rails
console. Be sure to run commands exactly as listed.
{{< /alert >}}
The rails console is a valuable tool to help debug LDAP problems. It allows you to
directly interact with the application by running commands and seeing how GitLab
responds to them.
For instructions about how to use the rails console, refer to this
[guide](../../operations/rails_console.md#starting-a-rails-console-session).
#### Enable debug output
This provides debug output that shows what GitLab is doing and with what.
This value is not persisted, and is only enabled for this session in the Rails console.
To enable debug output in the rails console, [enter the rails console](#rails-console) and run:
```ruby
Rails.logger.level = Logger::DEBUG
```
#### Get all error messages associated with groups, subgroups, members, and requesters
Collect error messages associated with groups, subgroups, members, and requesters. This
captures error messages that may not appear in the Web interface. This can be especially helpful
for troubleshooting issues with [LDAP group sync](ldap_synchronization.md#group-sync)
and unexpected behavior with users and their membership in groups and subgroups.
```ruby
# Find the group and subgroup
group = Group.find_by_full_path("parent_group")
subgroup = Group.find_by_full_path("parent_group/child_group")
# Group and subgroup errors
group.valid?
group.errors.map(&:full_messages)
subgroup.valid?
subgroup.errors.map(&:full_messages)
# Group and subgroup errors for the members AND requesters
group.requesters.map(&:valid?)
group.requesters.map(&:errors).map(&:full_messages)
group.members.map(&:valid?)
group.members.map(&:errors).map(&:full_messages)
group.members_and_requesters.map(&:errors).map(&:full_messages)
subgroup.requesters.map(&:valid?)
subgroup.requesters.map(&:errors).map(&:full_messages)
subgroup.members.map(&:valid?)
subgroup.members.map(&:errors).map(&:full_messages)
subgroup.members_and_requesters.map(&:errors).map(&:full_messages)
```
|
https://docs.gitlab.com/administration/auth/google_secure_ldap
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/auth/google_secure_ldap.md
|
2025-08-13
|
doc/administration/auth/ldap
|
[
"doc",
"administration",
"auth",
"ldap"
] |
google_secure_ldap.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Google Secure LDAP
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
[Google Cloud Identity](https://cloud.google.com/identity/) provides a Secure
LDAP service that can be configured with GitLab for authentication and group sync.
Secure LDAP requires a slightly different configuration than standard LDAP servers.
The steps below cover:
- Configuring the Secure LDAP Client in the Google administrator console.
- Required GitLab configuration.
Secure LDAP is only available on specific Google Workspace editions. For more information, see the [Google Secure LDAP service documentation](https://support.google.com/a/answer/9048516).
## Configuring Google LDAP client
1. Go to <https://admin.google.com/Dashboard> and sign in as a Google Workspace domain administrator.
1. Go to **Apps > LDAP > Add Client**.
1. Provide an **LDAP client name** and an optional **Description**. Any descriptive
values are acceptable. For example, the name could be `GitLab` and the
description could be `GitLab LDAP Client`. Select **Continue**.

1. Set **Access Permission** according to your needs. You must choose either
`Entire domain (GitLab)` or `Selected organizational units` for both **Verify user
credentials** and **Read user information**. Select **Add LDAP Client**.
{{< alert type="note" >}}
If you plan to use GitLab [LDAP Group Sync](ldap_synchronization.md#group-sync)
, turn on `Read group information`.
{{< /alert >}}

1. Download the generated certificate. This is required for GitLab to
communicate with the Google Secure LDAP service. Save the downloaded certificates
for later use. After downloading, select **Continue to Client Details**.
1. Expand the **Service Status** section and turn the LDAP client `ON for everyone`.
After selecting **Save**, select the **Service Status** bar again to collapse
and return to the rest of the settings.
1. Expand the **Authentication** section and choose **Generate New Credentials**.
Copy/note these credentials for later use. After selecting **Close**, select
the **Authentication** bar again to collapse and return to the rest of the settings.
Now the Google Secure LDAP Client configuration is finished. The screenshot below
shows an example of the final settings. Continue on to configure GitLab.

## Configuring GitLab
Edit GitLab configuration, inserting the access credentials and certificate
obtained earlier.
The following are the configuration keys that need to be modified using the
values obtained during the LDAP client configuration earlier:
- `bind_dn`: The access credentials username
- `password`: The access credentials password
- `cert`: The `.crt` file text from the downloaded certificate bundle
- `key`: The `.key` file text from the downloaded certificate bundle
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-EOS # remember to close this block with 'EOS' below
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'Google Secure LDAP'
host: 'ldap.google.com'
port: 636
uid: 'uid'
bind_dn: 'DizzyHorse'
password: 'd6V5H8nhMUW9AuDP25abXeLd'
encryption: 'simple_tls'
verify_certificates: true
retry_empty_result_with_codes: [80]
base: "DC=example,DC=com"
tls_options:
cert: |
-----BEGIN CERTIFICATE-----
MIIDbDCCAlSgAwIBAgIGAWlzxiIfMA0GCSqGSIb3DQEBCwUAMHcxFDASBgNVBAoTC0dvb2dsZSBJ
bmMuMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UE
CxMGR1N1aXRlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTAeFw0xOTAzMTIyMTE5
MThaFw0yMjAzMTEyMTE5MThaMHcxFDASBgNVBAoTC0dvb2dsZSBJbmMuMRYwFAYDVQQHEw1Nb3Vu
dGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UECxMGR1N1aXRlMQswCQYDVQQG
EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALOTy4aC38dyjESk6N8fRsKk8DN23ZX/GaNFL5OUmmA1KWzrvVC881OzNdtGm3vNOIxr9clteEG/
tQwsmsJvQT5U+GkBt+tGKF/zm7zueHUYqTP7Pg5pxAnAei90qkIRFi17ulObyRHPYv1BbCt8pxNB
4fG/gAXkFbCNxwh1eiQXXRTfruasCZ4/mHfX7MVm8JmWU9uAVIOLW+DSWOFhrDQduJdGBXJOyC2r
Gqoeg9+tkBmNH/jjxpnEkFW8q7io9DdOUqqNgoidA1h9vpKTs3084sy2DOgUvKN9uXWx14uxIyYU
Y1DnDy0wczcsuRt7l+EgtCEgpsLiLJQbKW+JS1UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAf60J
yazhbHkDKIH2gFxfm7QLhhnqsmafvl4WP7JqZt0u0KdnvbDPfokdkM87yfbKJU1MTI86M36wEC+1
P6bzklKz7kXbzAD4GggksAzxsEE64OWHC+Y64Tkxq2NiZTw/76POkcg9StiIXjG0ZcebHub9+Ux/
rTncip92nDuvgEM7lbPFKRIS/YMhLCk09B/U0F6XLsf1yYjyf5miUTDikPkov23b/YGfpc8kh6hq
1kqdi6a1cYPP34eAhtRhMqcZU9qezpJF6s9EeN/3YFfKzLODFSsVToBRAdZgGHzj//SAtLyQTD4n
KCSvK1UmaMxNaZyTHg8JnMf0ZuRpv26iSg==
-----END CERTIFICATE-----
key: |
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzk8uGgt/HcoxEpOjfH0bCpPAz
dt2V/xmjRS+TlJpgNSls671QvPNTszXbRpt7zTiMa/XJbXhBv7UMLJrCb0E+VPhpAbfrRihf85u8
7nh1GKkz+z4OacQJwHovdKpCERYte7pTm8kRz2L9QWwrfKcTQeHxv4AF5BWwjccIdXokF10U367m
rAmeP5h31+zFZvCZllPbgFSDi1vg0ljhYaw0HbiXRgVyTsgtqxqqHoPfrZAZjR/448aZxJBVvKu4
qPQ3TlKqjYKInQNYfb6Sk7N9POLMtgzoFLyjfbl1sdeLsSMmFGNQ5w8tMHM3LLkbe5fhILQhIKbC
4iyUGylviUtVAgMBAAECggEAIPb0CQy0RJoX+q/lGbRVmnyJpYDf+115WNnl+mrwjdGkeZyqw4v0
BPzkWYzUFP1esJRO6buBNFybQRFdFW0z5lvVv/zzRKq71aVUBPInxaMRyHuJ8D5lIL8nDtgVOwyE
7DOGyDtURUMzMjdUwoTe7K+O6QBU4X/1pVPZYgmissYSMmt68LiP8k0p601F4+r5xOi/QEy44aVp
aOJZBUOisKB8BmUXZqmQ4Cy05vU9Xi1rLyzkn9s7fxnZ+JO6Sd1r0Thm1mE0yuPgxkDBh/b4f3/2
GsQNKKKCiij/6TfkjnBi8ZvWR44LnKpu760g/K7psVNrKwqJG6C/8RAcgISWQQKBgQDop7BaKGhK
1QMJJ/vnlyYFTucfGLn6bM//pzTys5Gop0tpcfX/Hf6a6Dd+zBhmC3tBmhr80XOX/PiyAIbc0lOI
31rafZuD/oVx5mlIySWX35EqS14LXmdVs/5vOhsInNgNiE+EPFf1L9YZgG/zA7OUBmqtTeYIPDVC
7ViJcydItQKBgQDFmK0H0IA6W4opGQo+zQKhefooqZ+RDk9IIZMPOAtnvOM7y3rSVrfsSjzYVuMS
w/RP/vs7rwhaZejnCZ8/7uIqwg4sdUBRzZYR3PRNFeheW+BPZvb+2keRCGzOs7xkbF1mu54qtYTa
HZGZj1OsD83AoMwVLcdLDgO1kw32dkS8IQKBgFRdgoifAHqqVah7VFB9se7Y1tyi5cXWsXI+Wufr
j9U9nQ4GojK52LqpnH4hWnOelDqMvF6TQTyLIk/B+yWWK26Ft/dk9wDdSdystd8L+dLh4k0Y+Whb
+lLMq2YABw+PeJUnqdYE38xsZVHoDjBsVjFGRmbDybeQxauYT7PACy3FAoGBAK2+k9bdNQMbXp7I
j8OszHVkJdz/WXlY1cmdDAxDwXOUGVKIlxTAf7TbiijILZ5gg0Cb+hj+zR9/oI0WXtr+mAv02jWp
W8cSOLS4TnBBpTLjIpdu+BwbnvYeLF6MmEjNKEufCXKQbaLEgTQ/XNlchBSuzwSIXkbWqdhM1+gx
EjtBAoGARAdMIiDMPWIIZg3nNnFebbmtBP0qiBsYohQZ+6i/8s/vautEHBEN6Q0brIU/goo+nTHc
t9VaOkzjCmAJSLPUanuBC8pdYgLu5J20NXUZLD9AE/2bBT3OpezKcdYeI2jqoc1qlWHlNtVtdqQ2
AcZSFJQjdg5BTyvdEDhaYUKGdRw=
-----END PRIVATE KEY-----
EOS
```
1. Save the file and [reconfigure](../../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
ldap:
enabled: true
servers:
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'Google Secure LDAP'
base: "DC=example,DC=com"
host: 'ldap.google.com'
port: 636
uid: 'uid'
bind_dn: 'DizzyHorse'
password: 'd6V5H8nhMUW9AuDP25abXeLd'
encryption: 'simple_tls'
verify_certificates: true
retry_empty_result_with_codes: [80]
tls_options:
cert: |
-----BEGIN CERTIFICATE-----
MIIDbDCCAlSgAwIBAgIGAWlzxiIfMA0GCSqGSIb3DQEBCwUAMHcxFDASBgNVBAoTC0dvb2dsZSBJ
bmMuMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UE
CxMGR1N1aXRlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTAeFw0xOTAzMTIyMTE5
MThaFw0yMjAzMTEyMTE5MThaMHcxFDASBgNVBAoTC0dvb2dsZSBJbmMuMRYwFAYDVQQHEw1Nb3Vu
dGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UECxMGR1N1aXRlMQswCQYDVQQG
EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALOTy4aC38dyjESk6N8fRsKk8DN23ZX/GaNFL5OUmmA1KWzrvVC881OzNdtGm3vNOIxr9clteEG/
tQwsmsJvQT5U+GkBt+tGKF/zm7zueHUYqTP7Pg5pxAnAei90qkIRFi17ulObyRHPYv1BbCt8pxNB
4fG/gAXkFbCNxwh1eiQXXRTfruasCZ4/mHfX7MVm8JmWU9uAVIOLW+DSWOFhrDQduJdGBXJOyC2r
Gqoeg9+tkBmNH/jjxpnEkFW8q7io9DdOUqqNgoidA1h9vpKTs3084sy2DOgUvKN9uXWx14uxIyYU
Y1DnDy0wczcsuRt7l+EgtCEgpsLiLJQbKW+JS1UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAf60J
yazhbHkDKIH2gFxfm7QLhhnqsmafvl4WP7JqZt0u0KdnvbDPfokdkM87yfbKJU1MTI86M36wEC+1
P6bzklKz7kXbzAD4GggksAzxsEE64OWHC+Y64Tkxq2NiZTw/76POkcg9StiIXjG0ZcebHub9+Ux/
rTncip92nDuvgEM7lbPFKRIS/YMhLCk09B/U0F6XLsf1yYjyf5miUTDikPkov23b/YGfpc8kh6hq
1kqdi6a1cYPP34eAhtRhMqcZU9qezpJF6s9EeN/3YFfKzLODFSsVToBRAdZgGHzj//SAtLyQTD4n
KCSvK1UmaMxNaZyTHg8JnMf0ZuRpv26iSg==
-----END CERTIFICATE-----
key: |
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzk8uGgt/HcoxEpOjfH0bCpPAz
dt2V/xmjRS+TlJpgNSls671QvPNTszXbRpt7zTiMa/XJbXhBv7UMLJrCb0E+VPhpAbfrRihf85u8
7nh1GKkz+z4OacQJwHovdKpCERYte7pTm8kRz2L9QWwrfKcTQeHxv4AF5BWwjccIdXokF10U367m
rAmeP5h31+zFZvCZllPbgFSDi1vg0ljhYaw0HbiXRgVyTsgtqxqqHoPfrZAZjR/448aZxJBVvKu4
qPQ3TlKqjYKInQNYfb6Sk7N9POLMtgzoFLyjfbl1sdeLsSMmFGNQ5w8tMHM3LLkbe5fhILQhIKbC
4iyUGylviUtVAgMBAAECggEAIPb0CQy0RJoX+q/lGbRVmnyJpYDf+115WNnl+mrwjdGkeZyqw4v0
BPzkWYzUFP1esJRO6buBNFybQRFdFW0z5lvVv/zzRKq71aVUBPInxaMRyHuJ8D5lIL8nDtgVOwyE
7DOGyDtURUMzMjdUwoTe7K+O6QBU4X/1pVPZYgmissYSMmt68LiP8k0p601F4+r5xOi/QEy44aVp
aOJZBUOisKB8BmUXZqmQ4Cy05vU9Xi1rLyzkn9s7fxnZ+JO6Sd1r0Thm1mE0yuPgxkDBh/b4f3/2
GsQNKKKCiij/6TfkjnBi8ZvWR44LnKpu760g/K7psVNrKwqJG6C/8RAcgISWQQKBgQDop7BaKGhK
1QMJJ/vnlyYFTucfGLn6bM//pzTys5Gop0tpcfX/Hf6a6Dd+zBhmC3tBmhr80XOX/PiyAIbc0lOI
31rafZuD/oVx5mlIySWX35EqS14LXmdVs/5vOhsInNgNiE+EPFf1L9YZgG/zA7OUBmqtTeYIPDVC
7ViJcydItQKBgQDFmK0H0IA6W4opGQo+zQKhefooqZ+RDk9IIZMPOAtnvOM7y3rSVrfsSjzYVuMS
w/RP/vs7rwhaZejnCZ8/7uIqwg4sdUBRzZYR3PRNFeheW+BPZvb+2keRCGzOs7xkbF1mu54qtYTa
HZGZj1OsD83AoMwVLcdLDgO1kw32dkS8IQKBgFRdgoifAHqqVah7VFB9se7Y1tyi5cXWsXI+Wufr
j9U9nQ4GojK52LqpnH4hWnOelDqMvF6TQTyLIk/B+yWWK26Ft/dk9wDdSdystd8L+dLh4k0Y+Whb
+lLMq2YABw+PeJUnqdYE38xsZVHoDjBsVjFGRmbDybeQxauYT7PACy3FAoGBAK2+k9bdNQMbXp7I
j8OszHVkJdz/WXlY1cmdDAxDwXOUGVKIlxTAf7TbiijILZ5gg0Cb+hj+zR9/oI0WXtr+mAv02jWp
W8cSOLS4TnBBpTLjIpdu+BwbnvYeLF6MmEjNKEufCXKQbaLEgTQ/XNlchBSuzwSIXkbWqdhM1+gx
EjtBAoGARAdMIiDMPWIIZg3nNnFebbmtBP0qiBsYohQZ+6i/8s/vautEHBEN6Q0brIU/goo+nTHc
t9VaOkzjCmAJSLPUanuBC8pdYgLu5J20NXUZLD9AE/2bBT3OpezKcdYeI2jqoc1qlWHlNtVtdqQ2
AcZSFJQjdg5BTyvdEDhaYUKGdRw=
-----END PRIVATE KEY-----
```
1. Save the file and [restart](../../restart_gitlab.md#self-compiled-installations) GitLab for the changes to take effect.
## Using encrypted credentials
You can optionally store the `bind_dn` and `password` in a separate encrypted configuration file using the
[same steps as the regular LDAP integration](_index.md#use-encrypted-credentials).
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Google Secure LDAP
breadcrumbs:
- doc
- administration
- auth
- ldap
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
[Google Cloud Identity](https://cloud.google.com/identity/) provides a Secure
LDAP service that can be configured with GitLab for authentication and group sync.
Secure LDAP requires a slightly different configuration than standard LDAP servers.
The steps below cover:
- Configuring the Secure LDAP Client in the Google administrator console.
- Required GitLab configuration.
Secure LDAP is only available on specific Google Workspace editions. For more information, see the [Google Secure LDAP service documentation](https://support.google.com/a/answer/9048516).
## Configuring Google LDAP client
1. Go to <https://admin.google.com/Dashboard> and sign in as a Google Workspace domain administrator.
1. Go to **Apps > LDAP > Add Client**.
1. Provide an **LDAP client name** and an optional **Description**. Any descriptive
values are acceptable. For example, the name could be `GitLab` and the
description could be `GitLab LDAP Client`. Select **Continue**.

1. Set **Access Permission** according to your needs. You must choose either
`Entire domain (GitLab)` or `Selected organizational units` for both **Verify user
credentials** and **Read user information**. Select **Add LDAP Client**.
{{< alert type="note" >}}
If you plan to use GitLab [LDAP Group Sync](ldap_synchronization.md#group-sync)
, turn on `Read group information`.
{{< /alert >}}

1. Download the generated certificate. This is required for GitLab to
communicate with the Google Secure LDAP service. Save the downloaded certificates
for later use. After downloading, select **Continue to Client Details**.
1. Expand the **Service Status** section and turn the LDAP client `ON for everyone`.
After selecting **Save**, select the **Service Status** bar again to collapse
and return to the rest of the settings.
1. Expand the **Authentication** section and choose **Generate New Credentials**.
Copy/note these credentials for later use. After selecting **Close**, select
the **Authentication** bar again to collapse and return to the rest of the settings.
Now the Google Secure LDAP Client configuration is finished. The screenshot below
shows an example of the final settings. Continue on to configure GitLab.

## Configuring GitLab
Edit GitLab configuration, inserting the access credentials and certificate
obtained earlier.
The following are the configuration keys that need to be modified using the
values obtained during the LDAP client configuration earlier:
- `bind_dn`: The access credentials username
- `password`: The access credentials password
- `cert`: The `.crt` file text from the downloaded certificate bundle
- `key`: The `.key` file text from the downloaded certificate bundle
For Linux package installations:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-EOS # remember to close this block with 'EOS' below
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'Google Secure LDAP'
host: 'ldap.google.com'
port: 636
uid: 'uid'
bind_dn: 'DizzyHorse'
password: 'd6V5H8nhMUW9AuDP25abXeLd'
encryption: 'simple_tls'
verify_certificates: true
retry_empty_result_with_codes: [80]
base: "DC=example,DC=com"
tls_options:
cert: |
-----BEGIN CERTIFICATE-----
MIIDbDCCAlSgAwIBAgIGAWlzxiIfMA0GCSqGSIb3DQEBCwUAMHcxFDASBgNVBAoTC0dvb2dsZSBJ
bmMuMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UE
CxMGR1N1aXRlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTAeFw0xOTAzMTIyMTE5
MThaFw0yMjAzMTEyMTE5MThaMHcxFDASBgNVBAoTC0dvb2dsZSBJbmMuMRYwFAYDVQQHEw1Nb3Vu
dGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UECxMGR1N1aXRlMQswCQYDVQQG
EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALOTy4aC38dyjESk6N8fRsKk8DN23ZX/GaNFL5OUmmA1KWzrvVC881OzNdtGm3vNOIxr9clteEG/
tQwsmsJvQT5U+GkBt+tGKF/zm7zueHUYqTP7Pg5pxAnAei90qkIRFi17ulObyRHPYv1BbCt8pxNB
4fG/gAXkFbCNxwh1eiQXXRTfruasCZ4/mHfX7MVm8JmWU9uAVIOLW+DSWOFhrDQduJdGBXJOyC2r
Gqoeg9+tkBmNH/jjxpnEkFW8q7io9DdOUqqNgoidA1h9vpKTs3084sy2DOgUvKN9uXWx14uxIyYU
Y1DnDy0wczcsuRt7l+EgtCEgpsLiLJQbKW+JS1UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAf60J
yazhbHkDKIH2gFxfm7QLhhnqsmafvl4WP7JqZt0u0KdnvbDPfokdkM87yfbKJU1MTI86M36wEC+1
P6bzklKz7kXbzAD4GggksAzxsEE64OWHC+Y64Tkxq2NiZTw/76POkcg9StiIXjG0ZcebHub9+Ux/
rTncip92nDuvgEM7lbPFKRIS/YMhLCk09B/U0F6XLsf1yYjyf5miUTDikPkov23b/YGfpc8kh6hq
1kqdi6a1cYPP34eAhtRhMqcZU9qezpJF6s9EeN/3YFfKzLODFSsVToBRAdZgGHzj//SAtLyQTD4n
KCSvK1UmaMxNaZyTHg8JnMf0ZuRpv26iSg==
-----END CERTIFICATE-----
key: |
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzk8uGgt/HcoxEpOjfH0bCpPAz
dt2V/xmjRS+TlJpgNSls671QvPNTszXbRpt7zTiMa/XJbXhBv7UMLJrCb0E+VPhpAbfrRihf85u8
7nh1GKkz+z4OacQJwHovdKpCERYte7pTm8kRz2L9QWwrfKcTQeHxv4AF5BWwjccIdXokF10U367m
rAmeP5h31+zFZvCZllPbgFSDi1vg0ljhYaw0HbiXRgVyTsgtqxqqHoPfrZAZjR/448aZxJBVvKu4
qPQ3TlKqjYKInQNYfb6Sk7N9POLMtgzoFLyjfbl1sdeLsSMmFGNQ5w8tMHM3LLkbe5fhILQhIKbC
4iyUGylviUtVAgMBAAECggEAIPb0CQy0RJoX+q/lGbRVmnyJpYDf+115WNnl+mrwjdGkeZyqw4v0
BPzkWYzUFP1esJRO6buBNFybQRFdFW0z5lvVv/zzRKq71aVUBPInxaMRyHuJ8D5lIL8nDtgVOwyE
7DOGyDtURUMzMjdUwoTe7K+O6QBU4X/1pVPZYgmissYSMmt68LiP8k0p601F4+r5xOi/QEy44aVp
aOJZBUOisKB8BmUXZqmQ4Cy05vU9Xi1rLyzkn9s7fxnZ+JO6Sd1r0Thm1mE0yuPgxkDBh/b4f3/2
GsQNKKKCiij/6TfkjnBi8ZvWR44LnKpu760g/K7psVNrKwqJG6C/8RAcgISWQQKBgQDop7BaKGhK
1QMJJ/vnlyYFTucfGLn6bM//pzTys5Gop0tpcfX/Hf6a6Dd+zBhmC3tBmhr80XOX/PiyAIbc0lOI
31rafZuD/oVx5mlIySWX35EqS14LXmdVs/5vOhsInNgNiE+EPFf1L9YZgG/zA7OUBmqtTeYIPDVC
7ViJcydItQKBgQDFmK0H0IA6W4opGQo+zQKhefooqZ+RDk9IIZMPOAtnvOM7y3rSVrfsSjzYVuMS
w/RP/vs7rwhaZejnCZ8/7uIqwg4sdUBRzZYR3PRNFeheW+BPZvb+2keRCGzOs7xkbF1mu54qtYTa
HZGZj1OsD83AoMwVLcdLDgO1kw32dkS8IQKBgFRdgoifAHqqVah7VFB9se7Y1tyi5cXWsXI+Wufr
j9U9nQ4GojK52LqpnH4hWnOelDqMvF6TQTyLIk/B+yWWK26Ft/dk9wDdSdystd8L+dLh4k0Y+Whb
+lLMq2YABw+PeJUnqdYE38xsZVHoDjBsVjFGRmbDybeQxauYT7PACy3FAoGBAK2+k9bdNQMbXp7I
j8OszHVkJdz/WXlY1cmdDAxDwXOUGVKIlxTAf7TbiijILZ5gg0Cb+hj+zR9/oI0WXtr+mAv02jWp
W8cSOLS4TnBBpTLjIpdu+BwbnvYeLF6MmEjNKEufCXKQbaLEgTQ/XNlchBSuzwSIXkbWqdhM1+gx
EjtBAoGARAdMIiDMPWIIZg3nNnFebbmtBP0qiBsYohQZ+6i/8s/vautEHBEN6Q0brIU/goo+nTHc
t9VaOkzjCmAJSLPUanuBC8pdYgLu5J20NXUZLD9AE/2bBT3OpezKcdYeI2jqoc1qlWHlNtVtdqQ2
AcZSFJQjdg5BTyvdEDhaYUKGdRw=
-----END PRIVATE KEY-----
EOS
```
1. Save the file and [reconfigure](../../restart_gitlab.md#reconfigure-a-linux-package-installation) GitLab for the changes to take effect.
For self-compiled installations:
1. Edit `config/gitlab.yml`:
```yaml
ldap:
enabled: true
servers:
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'Google Secure LDAP'
base: "DC=example,DC=com"
host: 'ldap.google.com'
port: 636
uid: 'uid'
bind_dn: 'DizzyHorse'
password: 'd6V5H8nhMUW9AuDP25abXeLd'
encryption: 'simple_tls'
verify_certificates: true
retry_empty_result_with_codes: [80]
tls_options:
cert: |
-----BEGIN CERTIFICATE-----
MIIDbDCCAlSgAwIBAgIGAWlzxiIfMA0GCSqGSIb3DQEBCwUAMHcxFDASBgNVBAoTC0dvb2dsZSBJ
bmMuMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UE
CxMGR1N1aXRlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTAeFw0xOTAzMTIyMTE5
MThaFw0yMjAzMTEyMTE5MThaMHcxFDASBgNVBAoTC0dvb2dsZSBJbmMuMRYwFAYDVQQHEw1Nb3Vu
dGFpbiBWaWV3MRQwEgYDVQQDEwtMREFQIENsaWVudDEPMA0GA1UECxMGR1N1aXRlMQswCQYDVQQG
EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALOTy4aC38dyjESk6N8fRsKk8DN23ZX/GaNFL5OUmmA1KWzrvVC881OzNdtGm3vNOIxr9clteEG/
tQwsmsJvQT5U+GkBt+tGKF/zm7zueHUYqTP7Pg5pxAnAei90qkIRFi17ulObyRHPYv1BbCt8pxNB
4fG/gAXkFbCNxwh1eiQXXRTfruasCZ4/mHfX7MVm8JmWU9uAVIOLW+DSWOFhrDQduJdGBXJOyC2r
Gqoeg9+tkBmNH/jjxpnEkFW8q7io9DdOUqqNgoidA1h9vpKTs3084sy2DOgUvKN9uXWx14uxIyYU
Y1DnDy0wczcsuRt7l+EgtCEgpsLiLJQbKW+JS1UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAf60J
yazhbHkDKIH2gFxfm7QLhhnqsmafvl4WP7JqZt0u0KdnvbDPfokdkM87yfbKJU1MTI86M36wEC+1
P6bzklKz7kXbzAD4GggksAzxsEE64OWHC+Y64Tkxq2NiZTw/76POkcg9StiIXjG0ZcebHub9+Ux/
rTncip92nDuvgEM7lbPFKRIS/YMhLCk09B/U0F6XLsf1yYjyf5miUTDikPkov23b/YGfpc8kh6hq
1kqdi6a1cYPP34eAhtRhMqcZU9qezpJF6s9EeN/3YFfKzLODFSsVToBRAdZgGHzj//SAtLyQTD4n
KCSvK1UmaMxNaZyTHg8JnMf0ZuRpv26iSg==
-----END CERTIFICATE-----
key: |
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzk8uGgt/HcoxEpOjfH0bCpPAz
dt2V/xmjRS+TlJpgNSls671QvPNTszXbRpt7zTiMa/XJbXhBv7UMLJrCb0E+VPhpAbfrRihf85u8
7nh1GKkz+z4OacQJwHovdKpCERYte7pTm8kRz2L9QWwrfKcTQeHxv4AF5BWwjccIdXokF10U367m
rAmeP5h31+zFZvCZllPbgFSDi1vg0ljhYaw0HbiXRgVyTsgtqxqqHoPfrZAZjR/448aZxJBVvKu4
qPQ3TlKqjYKInQNYfb6Sk7N9POLMtgzoFLyjfbl1sdeLsSMmFGNQ5w8tMHM3LLkbe5fhILQhIKbC
4iyUGylviUtVAgMBAAECggEAIPb0CQy0RJoX+q/lGbRVmnyJpYDf+115WNnl+mrwjdGkeZyqw4v0
BPzkWYzUFP1esJRO6buBNFybQRFdFW0z5lvVv/zzRKq71aVUBPInxaMRyHuJ8D5lIL8nDtgVOwyE
7DOGyDtURUMzMjdUwoTe7K+O6QBU4X/1pVPZYgmissYSMmt68LiP8k0p601F4+r5xOi/QEy44aVp
aOJZBUOisKB8BmUXZqmQ4Cy05vU9Xi1rLyzkn9s7fxnZ+JO6Sd1r0Thm1mE0yuPgxkDBh/b4f3/2
GsQNKKKCiij/6TfkjnBi8ZvWR44LnKpu760g/K7psVNrKwqJG6C/8RAcgISWQQKBgQDop7BaKGhK
1QMJJ/vnlyYFTucfGLn6bM//pzTys5Gop0tpcfX/Hf6a6Dd+zBhmC3tBmhr80XOX/PiyAIbc0lOI
31rafZuD/oVx5mlIySWX35EqS14LXmdVs/5vOhsInNgNiE+EPFf1L9YZgG/zA7OUBmqtTeYIPDVC
7ViJcydItQKBgQDFmK0H0IA6W4opGQo+zQKhefooqZ+RDk9IIZMPOAtnvOM7y3rSVrfsSjzYVuMS
w/RP/vs7rwhaZejnCZ8/7uIqwg4sdUBRzZYR3PRNFeheW+BPZvb+2keRCGzOs7xkbF1mu54qtYTa
HZGZj1OsD83AoMwVLcdLDgO1kw32dkS8IQKBgFRdgoifAHqqVah7VFB9se7Y1tyi5cXWsXI+Wufr
j9U9nQ4GojK52LqpnH4hWnOelDqMvF6TQTyLIk/B+yWWK26Ft/dk9wDdSdystd8L+dLh4k0Y+Whb
+lLMq2YABw+PeJUnqdYE38xsZVHoDjBsVjFGRmbDybeQxauYT7PACy3FAoGBAK2+k9bdNQMbXp7I
j8OszHVkJdz/WXlY1cmdDAxDwXOUGVKIlxTAf7TbiijILZ5gg0Cb+hj+zR9/oI0WXtr+mAv02jWp
W8cSOLS4TnBBpTLjIpdu+BwbnvYeLF6MmEjNKEufCXKQbaLEgTQ/XNlchBSuzwSIXkbWqdhM1+gx
EjtBAoGARAdMIiDMPWIIZg3nNnFebbmtBP0qiBsYohQZ+6i/8s/vautEHBEN6Q0brIU/goo+nTHc
t9VaOkzjCmAJSLPUanuBC8pdYgLu5J20NXUZLD9AE/2bBT3OpezKcdYeI2jqoc1qlWHlNtVtdqQ2
AcZSFJQjdg5BTyvdEDhaYUKGdRw=
-----END PRIVATE KEY-----
```
1. Save the file and [restart](../../restart_gitlab.md#self-compiled-installations) GitLab for the changes to take effect.
## Using encrypted credentials
You can optionally store the `bind_dn` and `password` in a separate encrypted configuration file using the
[same steps as the regular LDAP integration](_index.md#use-encrypted-credentials).
|
https://docs.gitlab.com/administration/auth/ldap
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/auth/_index.md
|
2025-08-13
|
doc/administration/auth/ldap
|
[
"doc",
"administration",
"auth",
"ldap"
] |
_index.md
|
Software Supply Chain Security
|
Authentication
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Integrate LDAP with GitLab
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab integrates with [LDAP - Lightweight Directory Access Protocol](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol)
to support user authentication.
This integration works with most LDAP-compliant directory servers, including:
- Microsoft Active Directory.
- Apple Open Directory.
- OpenLDAP.
- 389 Server.
{{< alert type="note" >}}
GitLab does not support [Microsoft Active Directory Trusts](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc771568(v=ws.10)).
{{< /alert >}}
Users added through LDAP:
- Usually use a [licensed seat](../../../subscriptions/manage_users_and_seats.md#billable-users).
- Can authenticate with Git using either their GitLab username or their email and LDAP password,
even if password authentication for Git
[is disabled](../../settings/sign_in_restrictions.md#password-authentication-enabled).
The LDAP distinguished name (DN) is associated with existing GitLab users when:
- The existing user signs in to GitLab with LDAP for the first time.
- The LDAP email address is the primary email address of an existing GitLab user. If the LDAP email
attribute isn't found in the GitLab user database, a new user is created.
If an existing GitLab user wants to enable LDAP sign-in for themselves, they should:
1. Check that their GitLab email address matches their LDAP email address.
1. Sign in to GitLab by using their LDAP credentials.
## Security
GitLab verifies if a user is still active in LDAP.
Users are considered inactive in LDAP when they:
- Are removed from the directory completely.
- Reside outside the configured `base` DN or `user_filter` search.
- Are marked as disabled or deactivated in Active Directory through the user account control attribute. This means attribute
`userAccountControl:1.2.840.113556.1.4.803` has bit 2 set.
To check if a user is active or inactive in LDAP, use the following PowerShell command and the [Active Directory Module](https://learn.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps) to check the Active Directory:
```powershell
Get-ADUser -Identity <username> -Properties userAccountControl | Select-Object Name, userAccountControl
```
GitLab checks LDAP users' status:
- When signing in using any authentication provider.
- Once per hour for active web sessions or Git requests using tokens or SSH keys.
- When performing Git over HTTP requests using LDAP username and password.
- Once per day during [User Sync](ldap_synchronization.md#user-sync).
If the user is no longer active in LDAP, they are:
- Signed out.
- Placed in an `ldap_blocked` status.
- Unable to sign in using any authentication provider until they are reactivated in LDAP.
### Security risks
You should only use LDAP integration if your LDAP users cannot:
- Change their `mail`, `email` or `userPrincipalName` attributes on the LDAP server. These
users can potentially take over any account on your GitLab server.
- Share email addresses. LDAP users with the same email address can share the same GitLab
account.
## Configure LDAP
Prerequisites:
- You must have an email address to use LDAP, regardless of whether or not you
use that email address to sign in.
To configure LDAP, you edit the settings in a configuration file:
- Your configuration file must contain the following [basic configuration settings](#basic-configuration-settings):
- `label`
- `host`
- `port`
- `uid`
- `base`
- `encryption`
- You can include the following optional settings in your configuration file:
- [Optional basic configuration settings](#basic-configuration-settings).
- [SSL settings](#ssl-configuration-settings).
- [Attribute settings](#attribute-configuration-settings).
- [LDAP sync settings](#ldap-sync-configuration-settings).
- You can also configure LDAP to:
- [Use multiple servers](#use-multiple-ldap-servers).
- [Filter users](#set-up-ldap-user-filter).
- [Automatically set LDAP usernames to lowercase](#enable-ldap-username-lowercase).
- [Disable LDAP web sign in](#disable-ldap-web-sign-in).
- [Provide smart card authentication for GitLab](#provide-smart-card-authentication-for-gitlab)
- [Use encrypted credentials](#use-encrypted-credentials).
The file you edit differs depending on your GitLab setup:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'bind_dn' => 'CN=Gitlab,OU=Users,DC=domain,DC=com',
'password' => '<bind_user_password>',
'encryption' => 'simple_tls',
'verify_certificates' => true,
'timeout' => 10,
'active_directory' => false,
'user_filter' => '(employeeType=developer)',
'base' => 'dc=example,dc=com',
'lowercase_usernames' => 'false',
'retry_empty_result_with_codes' => [80],
'allow_username_or_email_login' => false,
'block_auto_created_users' => false
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
bind_dn: 'CN=Gitlab,OU=Users,DC=domain,DC=com'
password: '<bind_user_password>'
encryption: 'simple_tls'
verify_certificates: true
timeout: 10
active_directory: false
user_filter: '(employeeType=developer)'
base: 'dc=example,dc=com'
lowercase_usernames: false
retry_empty_result_with_codes: [80]
allow_username_or_email_login: false
block_auto_created_users: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
For more information, see
[how to configure LDAP for a GitLab instance that was installed by using the Helm chart](https://docs.gitlab.com/charts/charts/globals.html#ldap).
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'bind_dn' => 'CN=Gitlab,OU=Users,DC=domain,DC=com',
'password' => '<bind_user_password>',
'encryption' => 'simple_tls',
'verify_certificates' => true,
'timeout' => 10,
'active_directory' => false,
'user_filter' => '(employeeType=developer)',
'base' => 'dc=example,dc=com',
'lowercase_usernames' => 'false',
'retry_empty_result_with_codes' => [80],
'allow_username_or_email_login' => false,
'block_auto_created_users' => false
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
bind_dn: 'CN=Gitlab,OU=Users,DC=domain,DC=com'
password: '<bind_user_password>'
encryption: 'simple_tls'
verify_certificates: true
timeout: 10
active_directory: false
user_filter: '(employeeType=developer)'
base: 'dc=example,dc=com'
lowercase_usernames: false
retry_empty_result_with_codes: [80]
allow_username_or_email_login: false
block_auto_created_users: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
For more information about the various LDAP options, see the `ldap` setting in
[`gitlab.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/gitlab.yml.example).
{{< /tab >}}
{{< /tabs >}}
After configuring LDAP, to test the configuration, use the
[LDAP check Rake task](../../raketasks/ldap.md#check).
### Basic configuration settings
The following basic settings are available:
<!-- markdownlint-disable MD056 -->
| Setting | Required | Type | Description |
|---------------------------------|------------------------|-------------------------------|-------------|
| `label` | {{< icon name="check-circle" >}} Yes | String | A human-friendly name for your LDAP server. It is displayed on your sign-in page. Example: `'Paris'` or `'Acme, Ltd.'` |
| `host` | {{< icon name="check-circle" >}} Yes | String | IP address or domain name of your LDAP server. Ignored when `hosts` is defined. Example: `'ldap.mydomain.com'` |
| `port` | {{< icon name="check-circle" >}} Yes | Integer | The port to connect with on your LDAP server. Ignored when `hosts` is defined. Example: `389` or `636` (for SSL) |
| `uid` | {{< icon name="check-circle" >}} Yes | String | The LDAP attribute that maps to the username that users use to sign in. Should be the attribute, not the value that maps to the `uid`. Does not affect the GitLab username (see [attributes section](#attribute-configuration-settings)). Example: `'sAMAccountName'` or `'uid'` or `'userPrincipalName'` |
| `base` | {{< icon name="check-circle" >}} Yes | String | Base where we can search for users. Example: `'ou=people,dc=gitlab,dc=example'` or `'DC=mydomain,DC=com'` |
| `encryption` | {{< icon name="check-circle" >}} Yes | String | Encryption method (the `method` key is deprecated in favor of `encryption`). It can have one of three values: `'start_tls'`, `'simple_tls'`, or `'plain'`. `simple_tls` corresponds to 'Simple TLS' in the LDAP library. `start_tls` corresponds to StartTLS, not to be confused with regular TLS. If you specify `simple_tls`, usually it's on port 636, while `start_tls` (StartTLS) would be on port 389. `plain` also operates on port 389. |
| `hosts` | {{< icon name="dotted-circle" >}} No | Array of strings and integers | An array of host and port pairs to open connections. Each configured server should have an identical data set. This is not meant to configure multiple distinct LDAP servers, but to configure failover. Hosts are tried in the order they are configured. Example: `[['ldap1.mydomain.com', 636], ['ldap2.mydomain.com', 636]]` |
| `bind_dn` | {{< icon name="dotted-circle" >}} No | String | The full DN of the user you bind with. Example: `'america\momo'` or `'CN=Gitlab,OU=Users,DC=domain,DC=com'` |
| `password` | {{< icon name="dotted-circle" >}} No | String | The password of the bind user. |
| `verify_certificates` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `true`. Enables SSL certificate verification if encryption method is `start_tls` or `simple_tls`. If set to `false`, no validation of the LDAP server's SSL certificate is performed. |
| `timeout` | {{< icon name="dotted-circle" >}} No | Integer | Defaults to `10`. Set a timeout, in seconds, for LDAP queries. This helps avoid blocking a request if the LDAP server becomes unresponsive. A value of `0` means there is no timeout. |
| `active_directory` | {{< icon name="dotted-circle" >}} No | Boolean | This setting specifies if LDAP server is Active Directory LDAP server. For non-AD servers it skips the AD specific queries. If your LDAP server is not AD, set this to false. |
| `allow_username_or_email_login` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `false`. If enabled, GitLab ignores everything after the first `@` in the LDAP username submitted by the user on sign-in. If you are using `uid: 'userPrincipalName'` on ActiveDirectory you must disable this setting, because the userPrincipalName contains an `@`. |
| `block_auto_created_users` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `false`. To maintain tight control over the number of billable users on your GitLab installation, enable this setting to keep new users blocked until they have been cleared by an administrator . |
| `user_filter` | {{< icon name="dotted-circle" >}} No | String | Filter LDAP users. Follows the format of [RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html). GitLab does not support `omniauth-ldap`'s custom filter syntax. Examples of the `user_filter` field syntax:<br/><br/>- `'(employeeType=developer)'`<br/>- `'(&(objectclass=user)(|(samaccountname=momo)(samaccountname=toto)))'` |
| `lowercase_usernames` | {{< icon name="dotted-circle" >}} No | Boolean | If enabled, GitLab converts the name to lowercase. |
| `retry_empty_result_with_codes` | {{< icon name="dotted-circle" >}} No | Array | An array of LDAP query response code that attempt to retry the operation if the result/content is empty. For Google Secure LDAP, set this value to `[80]`. |
<!-- markdownlint-enable MD056 -->
### SSL configuration settings
You can configure SSL configuration settings under `tls_options` name/value
pairs. The following settings are all optional:
| Setting | Description | Examples |
|---------------|-------------|----------|
| `ca_file` | Specifies the path to a file containing a PEM-format CA certificate, for example, if you need an internal CA. | `'/etc/ca.pem'` |
| `ssl_version` | Specifies the SSL version for OpenSSL to use, if the OpenSSL default is not appropriate. | `'TLSv1_1'` |
| `ciphers` | Specific SSL ciphers to use in communication with LDAP servers. | `'ALL:!EXPORT:!LOW:!aNULL:!eNULL:!SSLv2'` |
| `cert` | Client certificate. | `'-----BEGIN CERTIFICATE----- <REDACTED> -----END CERTIFICATE -----'` |
| `key` | Client private key. | `'-----BEGIN PRIVATE KEY----- <REDACTED> -----END PRIVATE KEY -----'` |
The examples below illustrate how to set `ca_file` and `ssl_version` in `tls_options`:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com'
'tls_options' => {
'ca_file' => '/path/to/ca_file.pem',
'ssl_version' => 'TLSv1_2'
}
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tls_options:
ca_file: '/path/to/ca_file.pem'
ssl_version: 'TLSv1_2'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
For more information, see
[how to configure LDAP for a GitLab instance that was installed by using the Helm chart](https://docs.gitlab.com/charts/charts/globals.html#ldap).
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
'tls_options' => {
'ca_file' => '/path/to/ca_file.pem',
'ssl_version' => 'TLSv1_2'
}
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
encryption: 'simple_tls'
base: 'dc=example,dc=com'
tls_options:
ca_file: '/path/to/ca_file.pem'
ssl_version: 'TLSv1_2'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Attribute configuration settings
GitLab uses these LDAP attributes to create an account for the LDAP user. The specified
attribute can be either:
- The attribute name as a string. For example, `'mail'`.
- An array of attribute names to try in order. For example, `['mail', 'email']`.
The user's LDAP sign in is the LDAP attribute [specified as `uid`](#basic-configuration-settings).
All of the following LDAP attributes are optional. If you define these attributes,
you must do so in an `attributes` hash.
| Setting | Description | Examples |
|--------------|-------------|----------|
| `username` | The `@username` that the GitLab account will be provisioned with. If the value contains an email address, the GitLab username is the part of the email address before the `@`. Defaults to the LDAP attribute [specified as `uid`](#basic-configuration-settings). | `['uid', 'userid', 'sAMAccountName']` |
| `email` | LDAP attribute for user email. Defaults to `['mail', 'email', 'userPrincipalName']` | `['mail', 'email', 'userPrincipalName']` |
| `name` | LDAP attribute for user display name. If `name` is blank, the full name is taken from the `first_name` and `last_name`. Defaults to `'cn'`. | Attributes `'cn'`, or `'displayName'` commonly carry full names. Alternatively, you can force the use of `first_name` and `last_name` by specifying an absent attribute such as `'somethingNonExistent'`. |
| `first_name` | LDAP attribute for user first name. Used when the attribute configured for `name` does not exist. Defaults to `'givenName'`. | `'givenName'` |
| `last_name` | LDAP attribute for user last name. Used when the attribute configured for `name` does not exist. Defaults to `'sn'`. | `'sn'` |
### LDAP sync configuration settings
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
These LDAP sync configuration settings are optional, excluding `group_base` which
required when `external_groups` is configured:
| Setting | Description | Examples |
|-------------------|-------------|----------|
| `group_base` | Base used to search for groups. All valid groups have this base as part of their DN. | `'ou=groups,dc=gitlab,dc=example'` |
| `admin_group` | The CN of a group containing GitLab administrators. Not `cn=administrators` or the full DN. | `'administrators'` |
| `external_groups` | An array of CNs of groups containing users that should be considered external. Not `cn=interns` or the full DN. | `['interns', 'contractors']` |
| `sync_ssh_keys` | The LDAP attribute containing a user's public SSH key. | `'sshPublicKey'` or false if not set |
{{< alert type="note" >}}
If Sidekiq is configured on a different server to the Rails server, you must add the LDAP configuration to every Sidekiq server as well for LDAP synchronisation to work.
{{< /alert >}}
### Use multiple LDAP servers
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you have users on multiple LDAP servers, you can configure GitLab to use them. To add additional LDAP servers:
1. Duplicate the [`main` LDAP configuration](#configure-ldap).
1. Edit each duplicate configuration with the details of the additional servers.
- For each additional server, choose a different provider ID, like `main`, `secondary`, or `tertiary`. Use lowercase
alphanumeric characters. GitLab uses the provider ID to associate each user with a specific LDAP server.
- For each entry, use a unique `label` value. These values are used for the tab names on the sign-in page.
The following example shows how to configure three LDAP servers with
minimal configuration:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'GitLab AD',
'host' => 'ad.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'secondary' => {
'label' => 'GitLab Secondary AD',
'host' => 'ad-secondary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'tertiary' => {
'label' => 'GitLab Tertiary AD',
'host' => 'ad-tertiary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'GitLab AD'
host: 'ad.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
secondary:
label: 'GitLab Secondary AD'
host: 'ad-secondary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tertiary:
label: 'GitLab Tertiary AD'
host: 'ad-tertiary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'GitLab AD',
'host' => 'ad.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'secondary' => {
'label' => 'GitLab Secondary AD',
'host' => 'ad-secondary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'tertiary' => {
'label' => 'GitLab Tertiary AD',
'host' => 'ad-tertiary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'GitLab AD'
host: 'ad.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
secondary:
label: 'GitLab Secondary AD'
host: 'ad-secondary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tertiary:
label: 'GitLab Tertiary AD'
host: 'ad-tertiary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
For more information about the various LDAP options, see the `ldap` setting in
[`gitlab.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/gitlab.yml.example).
{{< /tab >}}
{{< /tabs >}}
This example results in a sign-in page with the following tabs:
- **GitLab AD**.
- **GitLab Secondary AD**.
- **GitLab Tertiary AD**.
### Set up LDAP user filter
To limit all GitLab access to a subset of the LDAP users on your LDAP server, first narrow the
configured `base`. However, to further filter users if
necessary, you can set up an LDAP user filter. The filter must comply with [RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html).
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'user_filter' => '(employeeType=developer)'
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
user_filter: '(employeeType=developer)'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'user_filter' => '(employeeType=developer)'
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
user_filter: '(employeeType=developer)'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
To limit access to the nested members of an Active Directory group, use the following syntax:
```plaintext
(memberOf:1.2.840.113556.1.4.1941:=CN=My Group,DC=Example,DC=com)
```
For more information about `LDAP_MATCHING_RULE_IN_CHAIN` filters, see
[Search Filter Syntax](https://learn.microsoft.com/en-us/windows/win32/adsi/search-filter-syntax).
Support for nested members in the user filter shouldn't be confused with
[group sync nested groups](ldap_synchronization.md#supported-ldap-group-typesattributes) support.
GitLab does not support the custom filter syntax used by OmniAuth LDAP.
#### Escape special characters in `user_filter`
The `user_filter` DN can contain special characters. For example:
- A comma:
```plaintext
OU=GitLab, Inc,DC=gitlab,DC=com
```
- Open and close brackets:
```plaintext
OU=GitLab (Inc),DC=gitlab,DC=com
```
These characters must be escaped as documented in
[RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html#section-4).
- Escape commas with `\2C`. For example:
```plaintext
OU=GitLab\2C Inc,DC=gitlab,DC=com
```
- Escape open brackets with `\28` and close brackets with `\29`. For example:
```plaintext
OU=GitLab \28Inc\29,DC=gitlab,DC=com
```
### Enable LDAP username lowercase
Some LDAP servers, depending on their configuration, can return uppercase usernames.
This can lead to several confusing issues such as creating links or namespaces with uppercase names.
GitLab can automatically lowercase usernames provided by the LDAP server by enabling
the configuration option `lowercase_usernames`. By default, this configuration option is `false`.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'lowercase_usernames' => true
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
lowercase_usernames: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'lowercase_usernames' => true
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `config/gitlab.yaml`:
```yaml
production:
ldap:
servers:
main:
lowercase_usernames: true
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Disable LDAP web sign in
It can be useful to prevent using LDAP credentials through the web UI when
an alternative such as SAML is preferred. This allows LDAP to be used for group
sync, while also allowing your SAML identity provider to handle additional
checks like custom 2FA.
When LDAP web sign in is disabled, users don't see an **LDAP** tab on the sign-in page.
This does not disable using LDAP credentials for Git access.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['prevent_ldap_sign_in'] = true
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
preventSignin: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['prevent_ldap_sign_in'] = true
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `config/gitlab.yaml`:
```yaml
production:
ldap:
prevent_ldap_sign_in: true
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Provide smart card authentication for GitLab
For more information on using smart cards with LDAP servers and GitLab, see [Smart card authentication](../smartcard.md).
### Use encrypted credentials
Instead of having the LDAP integration credentials stored in plaintext in the configuration files, you can optionally
use an encrypted file for the LDAP credentials.
Prerequisites:
- To use encrypted credentials, you must first enable the
[encrypted configuration](../../encrypted_configuration.md).
The encrypted configuration for LDAP exists in an encrypted YAML file. The
unencrypted contents of the file should be a subset of the secret settings from
your `servers` block in the LDAP configuration.
The supported configuration items for the encrypted file are:
- `bind_dn`
- `password`
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. If initially your LDAP configuration in `/etc/gitlab/gitlab.rb` looked like:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'bind_dn' => 'admin',
'password' => '123'
}
}
```
1. Edit the encrypted secret:
```shell
sudo gitlab-rake gitlab:ldap:secret:edit EDITOR=vim
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `/etc/gitlab/gitlab.rb` and remove the settings for `bind_dn` and `password`.
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
Use a Kubernetes secret to store the LDAP password. For more information,
read about [Helm LDAP secrets](https://docs.gitlab.com/charts/installation/secrets.html#ldap-password).
{{< /tab >}}
{{< tab title="Docker" >}}
1. If initially your LDAP configuration in `docker-compose.yml` looked like:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'bind_dn' => 'admin',
'password' => '123'
}
}
```
1. Get inside the container, and edit the encrypted secret:
```shell
sudo docker exec -t <container_name> bash
gitlab-rake gitlab:ldap:secret:edit EDITOR=vim
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `docker-compose.yml` and remove the settings for `bind_dn` and `password`.
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. If initially your LDAP configuration in `/home/git/gitlab/config/gitlab.yml` looked like:
```yaml
production:
ldap:
servers:
main:
bind_dn: admin
password: '123'
```
1. Edit the encrypted secret:
```shell
bundle exec rake gitlab:ldap:secret:edit EDITOR=vim RAILS_ENVIRONMENT=production
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and remove the settings for `bind_dn` and `password`.
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Updating LDAP DN and email
When an LDAP server creates a user in GitLab, the user's LDAP DN is linked to their GitLab account
as an identifier.
When a user tries to sign in with LDAP, GitLab tries to find the user using the DN saved on that user's account.
- If GitLab finds the user by the DN and the user's email address:
- Matches the GitLab account's email address, GitLab does not take any further action.
- Has changed, GitLab updates its record of the user's email to match the one in LDAP.
- If GitLab cannot find a user by their DN, it tries to find the user by their email. If GitLab:
- Finds the user by their email, GitLab updates the DN stored in the user's GitLab account. Both values now
match the information stored in LDAP.
- Cannot find the user by their email address (both the DN **and** the email address have changed), see
[User DN and email have changed](ldap-troubleshooting.md#user-dn-and-email-have-changed).
## Disable anonymous LDAP authentication
GitLab doesn't support TLS client authentication. Complete these steps on your LDAP server.
1. Disable anonymous authentication.
1. Enable one of the following authentication types:
- Simple authentication.
- Simple Authentication and Security Layer (SASL) authentication.
The TLS client authentication setting in your LDAP server cannot be mandatory and clients cannot be
authenticated with the TLS protocol.
## Users deleted from LDAP
Users deleted from the LDAP server:
- Are immediately blocked from signing in to GitLab.
- [No longer consume a license](../../moderate_users.md).
However, these users can continue to use Git with SSH until the next time the
[LDAP check cache runs](ldap_synchronization.md#adjust-ldap-user-sync-schedule).
To delete the account immediately, you can manually
[block the user](../../moderate_users.md#block-a-user).
## Update user email addresses
Email addresses on the LDAP server are considered the source of truth for users when LDAP is used to sign in.
Updating user email addresses must be done on the LDAP server that manages the user. The email address for GitLab is updated either:
- When the user next signs in.
- When the next [user sync](ldap_synchronization.md#user-sync) is run.
The updated user's previous email address becomes the secondary email address to preserve that user's commit history.
You can find more details on the expected behavior of user updates in our [LDAP troubleshooting section](ldap-troubleshooting.md#user-dn-and-email-have-changed).
## Google Secure LDAP
[Google Cloud Identity](https://cloud.google.com/identity/) provides a Secure
LDAP service that can be configured with GitLab for authentication and group sync.
See [Google Secure LDAP](google_secure_ldap.md) for detailed configuration instructions.
## Synchronize users and groups
For more information on synchronizing users and groups between LDAP and GitLab, see
[LDAP synchronization](ldap_synchronization.md).
## Move from LDAP to SAML
1. [Add SAML configuration](../../../integration/saml.md) to:
- [`gitlab.rb` for Linux package installations](../../../integration/saml.md).
- [`values.yml` for Helm chart installations](../../../integration/saml.md).
1. Optional. [Disable the LDAP auth from the sign-in page](#disable-ldap-web-sign-in).
1. Optional. To fix issues with linking users, you can first [remove those users' LDAP identities](ldap-troubleshooting.md#remove-the-identity-records-that-relate-to-the-removed-ldap-server).
1. Confirm that users are able to sign in to their accounts. If a user cannot sign in, check if that user's LDAP is still there and remove it if necessary. If this issue persists, check the logs to identify the problem.
1. In the configuration file, change:
- `omniauth_auto_link_user` to `saml` only.
- `omniauth_auto_link_ldap_user` to false.
- `ldap_enabled` to `false`.
You can also comment out the LDAP provider settings.
## Troubleshooting
See our [administrator guide to troubleshooting LDAP](ldap-troubleshooting.md).
|
---
stage: Software Supply Chain Security
group: Authentication
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
gitlab_dedicated: false
title: Integrate LDAP with GitLab
breadcrumbs:
- doc
- administration
- auth
- ldap
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab integrates with [LDAP - Lightweight Directory Access Protocol](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol)
to support user authentication.
This integration works with most LDAP-compliant directory servers, including:
- Microsoft Active Directory.
- Apple Open Directory.
- OpenLDAP.
- 389 Server.
{{< alert type="note" >}}
GitLab does not support [Microsoft Active Directory Trusts](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc771568(v=ws.10)).
{{< /alert >}}
Users added through LDAP:
- Usually use a [licensed seat](../../../subscriptions/manage_users_and_seats.md#billable-users).
- Can authenticate with Git using either their GitLab username or their email and LDAP password,
even if password authentication for Git
[is disabled](../../settings/sign_in_restrictions.md#password-authentication-enabled).
The LDAP distinguished name (DN) is associated with existing GitLab users when:
- The existing user signs in to GitLab with LDAP for the first time.
- The LDAP email address is the primary email address of an existing GitLab user. If the LDAP email
attribute isn't found in the GitLab user database, a new user is created.
If an existing GitLab user wants to enable LDAP sign-in for themselves, they should:
1. Check that their GitLab email address matches their LDAP email address.
1. Sign in to GitLab by using their LDAP credentials.
## Security
GitLab verifies if a user is still active in LDAP.
Users are considered inactive in LDAP when they:
- Are removed from the directory completely.
- Reside outside the configured `base` DN or `user_filter` search.
- Are marked as disabled or deactivated in Active Directory through the user account control attribute. This means attribute
`userAccountControl:1.2.840.113556.1.4.803` has bit 2 set.
To check if a user is active or inactive in LDAP, use the following PowerShell command and the [Active Directory Module](https://learn.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps) to check the Active Directory:
```powershell
Get-ADUser -Identity <username> -Properties userAccountControl | Select-Object Name, userAccountControl
```
GitLab checks LDAP users' status:
- When signing in using any authentication provider.
- Once per hour for active web sessions or Git requests using tokens or SSH keys.
- When performing Git over HTTP requests using LDAP username and password.
- Once per day during [User Sync](ldap_synchronization.md#user-sync).
If the user is no longer active in LDAP, they are:
- Signed out.
- Placed in an `ldap_blocked` status.
- Unable to sign in using any authentication provider until they are reactivated in LDAP.
### Security risks
You should only use LDAP integration if your LDAP users cannot:
- Change their `mail`, `email` or `userPrincipalName` attributes on the LDAP server. These
users can potentially take over any account on your GitLab server.
- Share email addresses. LDAP users with the same email address can share the same GitLab
account.
## Configure LDAP
Prerequisites:
- You must have an email address to use LDAP, regardless of whether or not you
use that email address to sign in.
To configure LDAP, you edit the settings in a configuration file:
- Your configuration file must contain the following [basic configuration settings](#basic-configuration-settings):
- `label`
- `host`
- `port`
- `uid`
- `base`
- `encryption`
- You can include the following optional settings in your configuration file:
- [Optional basic configuration settings](#basic-configuration-settings).
- [SSL settings](#ssl-configuration-settings).
- [Attribute settings](#attribute-configuration-settings).
- [LDAP sync settings](#ldap-sync-configuration-settings).
- You can also configure LDAP to:
- [Use multiple servers](#use-multiple-ldap-servers).
- [Filter users](#set-up-ldap-user-filter).
- [Automatically set LDAP usernames to lowercase](#enable-ldap-username-lowercase).
- [Disable LDAP web sign in](#disable-ldap-web-sign-in).
- [Provide smart card authentication for GitLab](#provide-smart-card-authentication-for-gitlab)
- [Use encrypted credentials](#use-encrypted-credentials).
The file you edit differs depending on your GitLab setup:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'bind_dn' => 'CN=Gitlab,OU=Users,DC=domain,DC=com',
'password' => '<bind_user_password>',
'encryption' => 'simple_tls',
'verify_certificates' => true,
'timeout' => 10,
'active_directory' => false,
'user_filter' => '(employeeType=developer)',
'base' => 'dc=example,dc=com',
'lowercase_usernames' => 'false',
'retry_empty_result_with_codes' => [80],
'allow_username_or_email_login' => false,
'block_auto_created_users' => false
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
bind_dn: 'CN=Gitlab,OU=Users,DC=domain,DC=com'
password: '<bind_user_password>'
encryption: 'simple_tls'
verify_certificates: true
timeout: 10
active_directory: false
user_filter: '(employeeType=developer)'
base: 'dc=example,dc=com'
lowercase_usernames: false
retry_empty_result_with_codes: [80]
allow_username_or_email_login: false
block_auto_created_users: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
For more information, see
[how to configure LDAP for a GitLab instance that was installed by using the Helm chart](https://docs.gitlab.com/charts/charts/globals.html#ldap).
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'bind_dn' => 'CN=Gitlab,OU=Users,DC=domain,DC=com',
'password' => '<bind_user_password>',
'encryption' => 'simple_tls',
'verify_certificates' => true,
'timeout' => 10,
'active_directory' => false,
'user_filter' => '(employeeType=developer)',
'base' => 'dc=example,dc=com',
'lowercase_usernames' => 'false',
'retry_empty_result_with_codes' => [80],
'allow_username_or_email_login' => false,
'block_auto_created_users' => false
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
bind_dn: 'CN=Gitlab,OU=Users,DC=domain,DC=com'
password: '<bind_user_password>'
encryption: 'simple_tls'
verify_certificates: true
timeout: 10
active_directory: false
user_filter: '(employeeType=developer)'
base: 'dc=example,dc=com'
lowercase_usernames: false
retry_empty_result_with_codes: [80]
allow_username_or_email_login: false
block_auto_created_users: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
For more information about the various LDAP options, see the `ldap` setting in
[`gitlab.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/gitlab.yml.example).
{{< /tab >}}
{{< /tabs >}}
After configuring LDAP, to test the configuration, use the
[LDAP check Rake task](../../raketasks/ldap.md#check).
### Basic configuration settings
The following basic settings are available:
<!-- markdownlint-disable MD056 -->
| Setting | Required | Type | Description |
|---------------------------------|------------------------|-------------------------------|-------------|
| `label` | {{< icon name="check-circle" >}} Yes | String | A human-friendly name for your LDAP server. It is displayed on your sign-in page. Example: `'Paris'` or `'Acme, Ltd.'` |
| `host` | {{< icon name="check-circle" >}} Yes | String | IP address or domain name of your LDAP server. Ignored when `hosts` is defined. Example: `'ldap.mydomain.com'` |
| `port` | {{< icon name="check-circle" >}} Yes | Integer | The port to connect with on your LDAP server. Ignored when `hosts` is defined. Example: `389` or `636` (for SSL) |
| `uid` | {{< icon name="check-circle" >}} Yes | String | The LDAP attribute that maps to the username that users use to sign in. Should be the attribute, not the value that maps to the `uid`. Does not affect the GitLab username (see [attributes section](#attribute-configuration-settings)). Example: `'sAMAccountName'` or `'uid'` or `'userPrincipalName'` |
| `base` | {{< icon name="check-circle" >}} Yes | String | Base where we can search for users. Example: `'ou=people,dc=gitlab,dc=example'` or `'DC=mydomain,DC=com'` |
| `encryption` | {{< icon name="check-circle" >}} Yes | String | Encryption method (the `method` key is deprecated in favor of `encryption`). It can have one of three values: `'start_tls'`, `'simple_tls'`, or `'plain'`. `simple_tls` corresponds to 'Simple TLS' in the LDAP library. `start_tls` corresponds to StartTLS, not to be confused with regular TLS. If you specify `simple_tls`, usually it's on port 636, while `start_tls` (StartTLS) would be on port 389. `plain` also operates on port 389. |
| `hosts` | {{< icon name="dotted-circle" >}} No | Array of strings and integers | An array of host and port pairs to open connections. Each configured server should have an identical data set. This is not meant to configure multiple distinct LDAP servers, but to configure failover. Hosts are tried in the order they are configured. Example: `[['ldap1.mydomain.com', 636], ['ldap2.mydomain.com', 636]]` |
| `bind_dn` | {{< icon name="dotted-circle" >}} No | String | The full DN of the user you bind with. Example: `'america\momo'` or `'CN=Gitlab,OU=Users,DC=domain,DC=com'` |
| `password` | {{< icon name="dotted-circle" >}} No | String | The password of the bind user. |
| `verify_certificates` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `true`. Enables SSL certificate verification if encryption method is `start_tls` or `simple_tls`. If set to `false`, no validation of the LDAP server's SSL certificate is performed. |
| `timeout` | {{< icon name="dotted-circle" >}} No | Integer | Defaults to `10`. Set a timeout, in seconds, for LDAP queries. This helps avoid blocking a request if the LDAP server becomes unresponsive. A value of `0` means there is no timeout. |
| `active_directory` | {{< icon name="dotted-circle" >}} No | Boolean | This setting specifies if LDAP server is Active Directory LDAP server. For non-AD servers it skips the AD specific queries. If your LDAP server is not AD, set this to false. |
| `allow_username_or_email_login` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `false`. If enabled, GitLab ignores everything after the first `@` in the LDAP username submitted by the user on sign-in. If you are using `uid: 'userPrincipalName'` on ActiveDirectory you must disable this setting, because the userPrincipalName contains an `@`. |
| `block_auto_created_users` | {{< icon name="dotted-circle" >}} No | Boolean | Defaults to `false`. To maintain tight control over the number of billable users on your GitLab installation, enable this setting to keep new users blocked until they have been cleared by an administrator . |
| `user_filter` | {{< icon name="dotted-circle" >}} No | String | Filter LDAP users. Follows the format of [RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html). GitLab does not support `omniauth-ldap`'s custom filter syntax. Examples of the `user_filter` field syntax:<br/><br/>- `'(employeeType=developer)'`<br/>- `'(&(objectclass=user)(|(samaccountname=momo)(samaccountname=toto)))'` |
| `lowercase_usernames` | {{< icon name="dotted-circle" >}} No | Boolean | If enabled, GitLab converts the name to lowercase. |
| `retry_empty_result_with_codes` | {{< icon name="dotted-circle" >}} No | Array | An array of LDAP query response code that attempt to retry the operation if the result/content is empty. For Google Secure LDAP, set this value to `[80]`. |
<!-- markdownlint-enable MD056 -->
### SSL configuration settings
You can configure SSL configuration settings under `tls_options` name/value
pairs. The following settings are all optional:
| Setting | Description | Examples |
|---------------|-------------|----------|
| `ca_file` | Specifies the path to a file containing a PEM-format CA certificate, for example, if you need an internal CA. | `'/etc/ca.pem'` |
| `ssl_version` | Specifies the SSL version for OpenSSL to use, if the OpenSSL default is not appropriate. | `'TLSv1_1'` |
| `ciphers` | Specific SSL ciphers to use in communication with LDAP servers. | `'ALL:!EXPORT:!LOW:!aNULL:!eNULL:!SSLv2'` |
| `cert` | Client certificate. | `'-----BEGIN CERTIFICATE----- <REDACTED> -----END CERTIFICATE -----'` |
| `key` | Client private key. | `'-----BEGIN PRIVATE KEY----- <REDACTED> -----END PRIVATE KEY -----'` |
The examples below illustrate how to set `ca_file` and `ssl_version` in `tls_options`:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com'
'tls_options' => {
'ca_file' => '/path/to/ca_file.pem',
'ssl_version' => 'TLSv1_2'
}
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tls_options:
ca_file: '/path/to/ca_file.pem'
ssl_version: 'TLSv1_2'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
For more information, see
[how to configure LDAP for a GitLab instance that was installed by using the Helm chart](https://docs.gitlab.com/charts/charts/globals.html#ldap).
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => 'ldap.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
'tls_options' => {
'ca_file' => '/path/to/ca_file.pem',
'ssl_version' => 'TLSv1_2'
}
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'LDAP'
host: 'ldap.mydomain.com'
port: 636
uid: 'sAMAccountName'
encryption: 'simple_tls'
base: 'dc=example,dc=com'
tls_options:
ca_file: '/path/to/ca_file.pem'
ssl_version: 'TLSv1_2'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Attribute configuration settings
GitLab uses these LDAP attributes to create an account for the LDAP user. The specified
attribute can be either:
- The attribute name as a string. For example, `'mail'`.
- An array of attribute names to try in order. For example, `['mail', 'email']`.
The user's LDAP sign in is the LDAP attribute [specified as `uid`](#basic-configuration-settings).
All of the following LDAP attributes are optional. If you define these attributes,
you must do so in an `attributes` hash.
| Setting | Description | Examples |
|--------------|-------------|----------|
| `username` | The `@username` that the GitLab account will be provisioned with. If the value contains an email address, the GitLab username is the part of the email address before the `@`. Defaults to the LDAP attribute [specified as `uid`](#basic-configuration-settings). | `['uid', 'userid', 'sAMAccountName']` |
| `email` | LDAP attribute for user email. Defaults to `['mail', 'email', 'userPrincipalName']` | `['mail', 'email', 'userPrincipalName']` |
| `name` | LDAP attribute for user display name. If `name` is blank, the full name is taken from the `first_name` and `last_name`. Defaults to `'cn'`. | Attributes `'cn'`, or `'displayName'` commonly carry full names. Alternatively, you can force the use of `first_name` and `last_name` by specifying an absent attribute such as `'somethingNonExistent'`. |
| `first_name` | LDAP attribute for user first name. Used when the attribute configured for `name` does not exist. Defaults to `'givenName'`. | `'givenName'` |
| `last_name` | LDAP attribute for user last name. Used when the attribute configured for `name` does not exist. Defaults to `'sn'`. | `'sn'` |
### LDAP sync configuration settings
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
These LDAP sync configuration settings are optional, excluding `group_base` which
required when `external_groups` is configured:
| Setting | Description | Examples |
|-------------------|-------------|----------|
| `group_base` | Base used to search for groups. All valid groups have this base as part of their DN. | `'ou=groups,dc=gitlab,dc=example'` |
| `admin_group` | The CN of a group containing GitLab administrators. Not `cn=administrators` or the full DN. | `'administrators'` |
| `external_groups` | An array of CNs of groups containing users that should be considered external. Not `cn=interns` or the full DN. | `['interns', 'contractors']` |
| `sync_ssh_keys` | The LDAP attribute containing a user's public SSH key. | `'sshPublicKey'` or false if not set |
{{< alert type="note" >}}
If Sidekiq is configured on a different server to the Rails server, you must add the LDAP configuration to every Sidekiq server as well for LDAP synchronisation to work.
{{< /alert >}}
### Use multiple LDAP servers
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you have users on multiple LDAP servers, you can configure GitLab to use them. To add additional LDAP servers:
1. Duplicate the [`main` LDAP configuration](#configure-ldap).
1. Edit each duplicate configuration with the details of the additional servers.
- For each additional server, choose a different provider ID, like `main`, `secondary`, or `tertiary`. Use lowercase
alphanumeric characters. GitLab uses the provider ID to associate each user with a specific LDAP server.
- For each entry, use a unique `label` value. These values are used for the tab names on the sign-in page.
The following example shows how to configure three LDAP servers with
minimal configuration:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'GitLab AD',
'host' => 'ad.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'secondary' => {
'label' => 'GitLab Secondary AD',
'host' => 'ad-secondary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'tertiary' => {
'label' => 'GitLab Tertiary AD',
'host' => 'ad-tertiary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
label: 'GitLab AD'
host: 'ad.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
secondary:
label: 'GitLab Secondary AD'
host: 'ad-secondary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tertiary:
label: 'GitLab Tertiary AD'
host: 'ad-tertiary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'GitLab AD',
'host' => 'ad.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'secondary' => {
'label' => 'GitLab Secondary AD',
'host' => 'ad-secondary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
},
'tertiary' => {
'label' => 'GitLab Tertiary AD',
'host' => 'ad-tertiary.mydomain.com',
'port' => 636,
'uid' => 'sAMAccountName',
'encryption' => 'simple_tls',
'base' => 'dc=example,dc=com',
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
enabled: true
servers:
main:
label: 'GitLab AD'
host: 'ad.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
secondary:
label: 'GitLab Secondary AD'
host: 'ad-secondary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
tertiary:
label: 'GitLab Tertiary AD'
host: 'ad-tertiary.mydomain.com'
port: 636
uid: 'sAMAccountName'
base: 'dc=example,dc=com'
encryption: 'simple_tls'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
For more information about the various LDAP options, see the `ldap` setting in
[`gitlab.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/gitlab.yml.example).
{{< /tab >}}
{{< /tabs >}}
This example results in a sign-in page with the following tabs:
- **GitLab AD**.
- **GitLab Secondary AD**.
- **GitLab Tertiary AD**.
### Set up LDAP user filter
To limit all GitLab access to a subset of the LDAP users on your LDAP server, first narrow the
configured `base`. However, to further filter users if
necessary, you can set up an LDAP user filter. The filter must comply with [RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html).
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'user_filter' => '(employeeType=developer)'
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
user_filter: '(employeeType=developer)'
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'user_filter' => '(employeeType=developer)'
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
ldap:
servers:
main:
user_filter: '(employeeType=developer)'
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
To limit access to the nested members of an Active Directory group, use the following syntax:
```plaintext
(memberOf:1.2.840.113556.1.4.1941:=CN=My Group,DC=Example,DC=com)
```
For more information about `LDAP_MATCHING_RULE_IN_CHAIN` filters, see
[Search Filter Syntax](https://learn.microsoft.com/en-us/windows/win32/adsi/search-filter-syntax).
Support for nested members in the user filter shouldn't be confused with
[group sync nested groups](ldap_synchronization.md#supported-ldap-group-typesattributes) support.
GitLab does not support the custom filter syntax used by OmniAuth LDAP.
#### Escape special characters in `user_filter`
The `user_filter` DN can contain special characters. For example:
- A comma:
```plaintext
OU=GitLab, Inc,DC=gitlab,DC=com
```
- Open and close brackets:
```plaintext
OU=GitLab (Inc),DC=gitlab,DC=com
```
These characters must be escaped as documented in
[RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html#section-4).
- Escape commas with `\2C`. For example:
```plaintext
OU=GitLab\2C Inc,DC=gitlab,DC=com
```
- Escape open brackets with `\28` and close brackets with `\29`. For example:
```plaintext
OU=GitLab \28Inc\29,DC=gitlab,DC=com
```
### Enable LDAP username lowercase
Some LDAP servers, depending on their configuration, can return uppercase usernames.
This can lead to several confusing issues such as creating links or namespaces with uppercase names.
GitLab can automatically lowercase usernames provided by the LDAP server by enabling
the configuration option `lowercase_usernames`. By default, this configuration option is `false`.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'lowercase_usernames' => true
}
}
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
servers:
main:
lowercase_usernames: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'lowercase_usernames' => true
}
}
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `config/gitlab.yaml`:
```yaml
production:
ldap:
servers:
main:
lowercase_usernames: true
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Disable LDAP web sign in
It can be useful to prevent using LDAP credentials through the web UI when
an alternative such as SAML is preferred. This allows LDAP to be used for group
sync, while also allowing your SAML identity provider to handle additional
checks like custom 2FA.
When LDAP web sign in is disabled, users don't see an **LDAP** tab on the sign-in page.
This does not disable using LDAP credentials for Git access.
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['prevent_ldap_sign_in'] = true
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
ldap:
preventSignin: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['prevent_ldap_sign_in'] = true
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `config/gitlab.yaml`:
```yaml
production:
ldap:
prevent_ldap_sign_in: true
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
### Provide smart card authentication for GitLab
For more information on using smart cards with LDAP servers and GitLab, see [Smart card authentication](../smartcard.md).
### Use encrypted credentials
Instead of having the LDAP integration credentials stored in plaintext in the configuration files, you can optionally
use an encrypted file for the LDAP credentials.
Prerequisites:
- To use encrypted credentials, you must first enable the
[encrypted configuration](../../encrypted_configuration.md).
The encrypted configuration for LDAP exists in an encrypted YAML file. The
unencrypted contents of the file should be a subset of the secret settings from
your `servers` block in the LDAP configuration.
The supported configuration items for the encrypted file are:
- `bind_dn`
- `password`
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. If initially your LDAP configuration in `/etc/gitlab/gitlab.rb` looked like:
```ruby
gitlab_rails['ldap_servers'] = {
'main' => {
'bind_dn' => 'admin',
'password' => '123'
}
}
```
1. Edit the encrypted secret:
```shell
sudo gitlab-rake gitlab:ldap:secret:edit EDITOR=vim
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `/etc/gitlab/gitlab.rb` and remove the settings for `bind_dn` and `password`.
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
Use a Kubernetes secret to store the LDAP password. For more information,
read about [Helm LDAP secrets](https://docs.gitlab.com/charts/installation/secrets.html#ldap-password).
{{< /tab >}}
{{< tab title="Docker" >}}
1. If initially your LDAP configuration in `docker-compose.yml` looked like:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['ldap_servers'] = {
'main' => {
'bind_dn' => 'admin',
'password' => '123'
}
}
```
1. Get inside the container, and edit the encrypted secret:
```shell
sudo docker exec -t <container_name> bash
gitlab-rake gitlab:ldap:secret:edit EDITOR=vim
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `docker-compose.yml` and remove the settings for `bind_dn` and `password`.
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. If initially your LDAP configuration in `/home/git/gitlab/config/gitlab.yml` looked like:
```yaml
production:
ldap:
servers:
main:
bind_dn: admin
password: '123'
```
1. Edit the encrypted secret:
```shell
bundle exec rake gitlab:ldap:secret:edit EDITOR=vim RAILS_ENVIRONMENT=production
```
1. Enter the unencrypted contents of the LDAP secret:
```yaml
main:
bind_dn: admin
password: '123'
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and remove the settings for `bind_dn` and `password`.
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Updating LDAP DN and email
When an LDAP server creates a user in GitLab, the user's LDAP DN is linked to their GitLab account
as an identifier.
When a user tries to sign in with LDAP, GitLab tries to find the user using the DN saved on that user's account.
- If GitLab finds the user by the DN and the user's email address:
- Matches the GitLab account's email address, GitLab does not take any further action.
- Has changed, GitLab updates its record of the user's email to match the one in LDAP.
- If GitLab cannot find a user by their DN, it tries to find the user by their email. If GitLab:
- Finds the user by their email, GitLab updates the DN stored in the user's GitLab account. Both values now
match the information stored in LDAP.
- Cannot find the user by their email address (both the DN **and** the email address have changed), see
[User DN and email have changed](ldap-troubleshooting.md#user-dn-and-email-have-changed).
## Disable anonymous LDAP authentication
GitLab doesn't support TLS client authentication. Complete these steps on your LDAP server.
1. Disable anonymous authentication.
1. Enable one of the following authentication types:
- Simple authentication.
- Simple Authentication and Security Layer (SASL) authentication.
The TLS client authentication setting in your LDAP server cannot be mandatory and clients cannot be
authenticated with the TLS protocol.
## Users deleted from LDAP
Users deleted from the LDAP server:
- Are immediately blocked from signing in to GitLab.
- [No longer consume a license](../../moderate_users.md).
However, these users can continue to use Git with SSH until the next time the
[LDAP check cache runs](ldap_synchronization.md#adjust-ldap-user-sync-schedule).
To delete the account immediately, you can manually
[block the user](../../moderate_users.md#block-a-user).
## Update user email addresses
Email addresses on the LDAP server are considered the source of truth for users when LDAP is used to sign in.
Updating user email addresses must be done on the LDAP server that manages the user. The email address for GitLab is updated either:
- When the user next signs in.
- When the next [user sync](ldap_synchronization.md#user-sync) is run.
The updated user's previous email address becomes the secondary email address to preserve that user's commit history.
You can find more details on the expected behavior of user updates in our [LDAP troubleshooting section](ldap-troubleshooting.md#user-dn-and-email-have-changed).
## Google Secure LDAP
[Google Cloud Identity](https://cloud.google.com/identity/) provides a Secure
LDAP service that can be configured with GitLab for authentication and group sync.
See [Google Secure LDAP](google_secure_ldap.md) for detailed configuration instructions.
## Synchronize users and groups
For more information on synchronizing users and groups between LDAP and GitLab, see
[LDAP synchronization](ldap_synchronization.md).
## Move from LDAP to SAML
1. [Add SAML configuration](../../../integration/saml.md) to:
- [`gitlab.rb` for Linux package installations](../../../integration/saml.md).
- [`values.yml` for Helm chart installations](../../../integration/saml.md).
1. Optional. [Disable the LDAP auth from the sign-in page](#disable-ldap-web-sign-in).
1. Optional. To fix issues with linking users, you can first [remove those users' LDAP identities](ldap-troubleshooting.md#remove-the-identity-records-that-relate-to-the-removed-ldap-server).
1. Confirm that users are able to sign in to their accounts. If a user cannot sign in, check if that user's LDAP is still there and remove it if necessary. If this issue persists, check the logs to identify the problem.
1. In the configuration file, change:
- `omniauth_auto_link_user` to `saml` only.
- `omniauth_auto_link_ldap_user` to false.
- `ldap_enabled` to `false`.
You can also comment out the LDAP provider settings.
## Troubleshooting
See our [administrator guide to troubleshooting LDAP](ldap-troubleshooting.md).
|
https://docs.gitlab.com/administration/lfs
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/lfs
|
[
"doc",
"administration",
"lfs"
] |
_index.md
|
Create
|
Source Code
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab Git Large File Storage (LFS) Administration
|
Configure Git LFS for GitLab Self-Managed.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Use Git Large File Storage (LFS) to store large files in a Git repository without
increasing its size or affecting performance. You can enable or disable LFS, configure local
or remote storage for LFS objects, and migrate objects between storage types.
For user documentation about Git LFS, see [Git Large File Storage](../../topics/git/lfs/_index.md).
Prerequisites:
- Users must install [Git LFS client](https://git-lfs.com/) version 1.1.0 and later, or 1.0.2.
## Enable or disable LFS
LFS is enabled by default. To disable it:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Change to true to enable lfs - enabled by default if not defined
gitlab_rails['lfs_enabled'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
lfs:
enabled: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['lfs_enabled'] = false
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
lfs:
enabled: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Change local storage path
Git LFS objects can be large in size. By default, they are stored on the server
GitLab is installed on.
{{< alert type="note" >}}
For Docker installations, you can change the path where your data is mounted.
For the Helm chart, use
[object storage](https://docs.gitlab.com/charts/advanced/external-object-storage/).
{{< /alert >}}
To change the default local storage path location:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# /var/opt/gitlab/gitlab-rails/shared/lfs-objects by default.
gitlab_rails['lfs_storage_path'] = "/mnt/storage/lfs-objects"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
# /home/git/gitlab/shared/lfs-objects by default.
production: &base
lfs:
storage_path: /mnt/storage/lfs-objects
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Storing LFS objects in remote object storage
You can store LFS objects in remote object storage. This allows you
to reduce reads and writes to the local disk, and free up disk space significantly.
You should use the
[consolidated object storage settings](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
### Migrating to object storage
You can migrate the LFS objects from local storage to object storage. The
processing is done in the background and requires no downtime.
1. [Configure the object storage](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
1. Migrate the LFS objects:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rake gitlab:lfs:migrate
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
sudo docker exec -t <container name> gitlab-rake gitlab:lfs:migrate
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rake gitlab:lfs:migrate RAILS_ENV=production
```
{{< /tab >}}
{{< /tabs >}}
1. Optional. Track the progress and verify that all job LFS objects migrated
successfully using the PostgreSQL console.
1. Open a PostgreSQL console:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-psql
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
sudo docker exec -it <container_name> /bin/bash
gitlab-psql
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H psql -d gitlabhq_production
```
{{< /tab >}}
{{< /tabs >}}
1. Verify that all LFS files migrated to object storage with the following
SQL query. The number of `objectstg` should be the same as `total`:
```shell
gitlabhq_production=# SELECT count(*) AS total, sum(case when file_store = '1' then 1 else 0 end) AS filesystem, sum(case when file_store = '2' then 1 else 0 end) AS objectstg FROM lfs_objects;
total | filesystem | objectstg
------+------------+-----------
2409 | 0 | 2409
```
1. Verify that there are no files on disk in the `lfs-objects` directory:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo find /var/opt/gitlab/gitlab-rails/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< tab title="Docker" >}}
Assuming you mounted `/var/opt/gitlab` to `/srv/gitlab`:
```shell
sudo find /srv/gitlab/gitlab-rails/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo find /home/git/gitlab/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< /tabs >}}
### Migrating back to local storage
{{< alert type="note" >}}
For the Helm chart, you should use
[object storage](https://docs.gitlab.com/charts/advanced/external-object-storage/).
{{< /alert >}}
To migrate back to local storage:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Migrate the LFS objects:
```shell
sudo gitlab-rake gitlab:lfs:migrate_to_local
```
1. Edit `/etc/gitlab/gitlab.rb` and
[disable object storage](../object_storage.md#disable-object-storage-for-specific-features)
for LFS objects:
```ruby
gitlab_rails['object_store']['objects']['lfs']['enabled'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Migrate the LFS objects:
```shell
sudo docker exec -t <container name> gitlab-rake gitlab:lfs:migrate_to_local
```
1. Edit `docker-compose.yml` and disable object storage for LFS objects:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['object_store']['objects']['lfs']['enabled'] = false
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Migrate the LFS objects:
```shell
sudo -u git -H bundle exec rake gitlab:lfs:migrate_to_local RAILS_ENV=production
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and disable object storage for LFS objects:
```yaml
production: &base
object_store:
objects:
lfs:
enabled: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Pure SSH transfer protocol
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11872) in GitLab 17.2.
- [Introduced](https://gitlab.com/gitlab-org/charts/gitlab/-/merge_requests/3845) for Helm chart (Kubernetes) in GitLab 17.3.
{{< /history >}}
{{< alert type="warning" >}}
This feature is affected by [a known issue](https://github.com/git-lfs/git-lfs/issues/5880)
(resolved in [Git LFS 3.6.0](https://github.com/git-lfs/git-lfs/blob/main/CHANGELOG.md#360-20-november-2024)).
If you clone a repository with multiple Git LFS objects using the pure SSH protocol,
the client might crash due to a `nil` pointer reference.
{{< /alert >}}
[`git-lfs` 3.0.0](https://github.com/git-lfs/git-lfs/blob/main/CHANGELOG.md#300-24-sep-2021)
released support for using SSH as the transfer protocol instead of HTTP.
SSH is handled transparently by the `git-lfs` command line tool.
When pure SSH protocol support is enabled and `git` is configured to use SSH,
all LFS operations happen over SSH. For example, when the Git remote is
`git@gitlab.com:gitlab-org/gitlab.git`. You can't configure `git` and `git-lfs`
to use different protocols. From version 3.0, `git-lfs` attempts to use the pure
SSH protocol initially and, if support is not enabled or available, it falls back
to using HTTP.
Prerequisites:
- The `git-lfs` version must be [v3.5.1](https://github.com/git-lfs/git-lfs/releases/tag/v3.5.1) or higher.
To switch Git LFS to use pure SSH protocol:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_shell['lfs_pure_ssh_protocol'] = true
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
gitlab:
gitlab-shell:
config:
lfs:
pureSSHProtocol: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_shell['lfs_pure_ssh_protocol'] = true
```
1. Save the file and restart GitLab and its services:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab-shell/config.yml`:
```yaml
lfs:
pure_ssh_protocol: true
```
1. Save the file and restart GitLab Shell:
```shell
# For systems running systemd
sudo systemctl restart gitlab-shell.target
# For systems running SysV init
sudo service gitlab-shell restart
```
{{< /tab >}}
{{< /tabs >}}
## Storage statistics
You can see the total storage used for LFS objects for groups and projects in:
- The **Admin** area
- The [groups](../../api/groups.md) and [projects](../../api/projects.md) APIs
{{< alert type="note" >}}
The storage statistics count each LFS object for every project linking to it.
{{< /alert >}}
## Related topics
- Blog post: [Getting started with Git LFS](https://about.gitlab.com/blog/2017/01/30/getting-started-with-git-lfs-tutorial/)
- User documentation: [Git Large File Storage (LFS)](../../topics/git/lfs/_index.md)
## Troubleshooting
### Missing LFS objects
An error about a missing LFS object may occur in either of these situations:
- When migrating LFS objects from disk to object storage, with error messages like:
```plaintext
ERROR -- : Failed to transfer LFS object
006622269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
with error: No such file or directory @ rb_sysopen -
/var/opt/gitlab/gitlab-rails/shared/lfs-objects/00/66/22269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
```
(Line breaks have been added for legibility.)
- When running the
[integrity check for LFS objects](../raketasks/check.md#uploaded-files-integrity)
with the `VERBOSE=1` parameter.
The database can have records for LFS objects which are not on disk. The database entry may
[prevent a new copy of the object from being pushed](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49241).
To delete these references:
1. [Start a rails console](../operations/rails_console.md).
1. Query the object that's reported as missing in the rails console, to return a file path:
```ruby
lfs_object = LfsObject.find_by(oid: '006622269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7')
lfs_object.file.path
```
1. Check on disk or object storage if it exists:
```shell
ls -al /var/opt/gitlab/gitlab-rails/shared/lfs-objects/00/66/22269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
```
1. If the file is not present, remove the database records with the Rails console:
```ruby
# First delete the parent records and then destroy the record itself
lfs_object.lfs_objects_projects.destroy_all
lfs_object.destroy
```
#### Remove multiple missing LFS objects
To remove references to multiple missing LFS objects at once:
1. Open the [GitLab Rails Console](../operations/rails_console.md#starting-a-rails-console-session).
1. Run the following script:
```ruby
lfs_files_deleted = 0
LfsObject.find_each do |lfs_file|
next if lfs_file.file.file.exists?
lfs_files_deleted += 1
p "LFS file with ID #{lfs_file.id} and path #{lfs_file.file.path} is missing."
# lfs_file.lfs_objects_projects.destroy_all # Uncomment to delete parent records
# lfs_file.destroy # Uncomment to destroy the LFS object reference
end
p "Count of identified/destroyed invalid references: #{lfs_files_deleted}"
```
This script identifies all missing LFS objects in the database. Before deleting any records:
- It first prints information about missing files for verification.
- The commented lines prevent accidental deletion. If you uncomment them, the script deletes the
identified records.
- The script automatically prints a final count of deleted records for comparison.
### LFS commands fail on TLS v1.3 server
If you configure GitLab to [disable TLS v1.2](https://docs.gitlab.com/omnibus/settings/nginx.html)
and only enable TLS v1.3 connections, LFS operations require a
[Git LFS client](https://git-lfs.com/) version 2.11.0 or later. If you use
a Git LFS client earlier than version 2.11.0, GitLab displays an error:
```plaintext
batch response: Post https://username:***@gitlab.example.com/tool/releases.git/info/lfs/objects/batch: remote error: tls: protocol version not supported
error: failed to fetch some objects from 'https://username:[MASKED]@gitlab.example.com/tool/releases.git/info/lfs'
```
When using GitLab CI over a TLS v1.3 configured GitLab server, you must
[upgrade to GitLab Runner](https://docs.gitlab.com/runner/install/) 13.2.0
or later to receive an updated Git LFS client version with
the included [GitLab Runner Helper image](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#helper-image).
To check an installed Git LFS client's version, run this command:
```shell
git lfs version
```
### `Connection refused` errors
If you push or mirror LFS objects and receive errors like the following:
- `dial tcp <IP>:443: connect: connection refused`
- `Connection refused - connect(2) for \"<target-or-proxy-IP>\" port 443`
a firewall or proxy rule may be terminating the connection.
If connection checks with standard Unix tools or manual Git pushes are successful,
the rule may be related to the size of the request.
### Error viewing a PDF file
When LFS has been configured with object storage and `proxy_download` set to
`false`, [you may see an error when previewing a PDF file from the Web browser](https://gitlab.com/gitlab-org/gitlab/-/issues/248100):
```plaintext
An error occurred while loading the file. Please try again later.
```
This occurs due to Cross-Origin Resource Sharing (CORS) restrictions:
the browser attempts to load the PDF from object storage, but the object
storage provider rejects the request because the GitLab domain differs
from the object storage domain.
To fix this issue, configure your object storage provider's CORS
settings to allow the GitLab domain. See the following documentation
for more details:
1. [AWS S3](https://repost.aws/knowledge-center/s3-configure-cors)
1. [Google Cloud Storage](https://cloud.google.com/storage/docs/using-cors)
1. [Azure Storage](https://learn.microsoft.com/en-us/rest/api/storageservices/cross-origin-resource-sharing--cors--support-for-the-azure-storage-services).
### Fork operation stuck on `Forking in progress` message
If you are forking a project with multiple LFS files, the operation might get stuck with a `Forking in progress` message.
If you encounter this, follow these steps to diagnose and resolve the issue:
1. Check your [exceptions_json.log](../logs/_index.md#exceptions_jsonlog) file for the following error message:
```plaintext
"error_message": "Unable to fork project 12345 for repository
@hashed/11/22/encoded-path -> @hashed/33/44/encoded-new-path:
Source project has too many LFS objects"
```
This error indicates that you've reached the default limit of 100,000 LFS files,
as described in issue [#476693](https://gitlab.com/gitlab-org/gitlab/-/issues/476693).
1. Increase the value of the `GITLAB_LFS_MAX_OID_TO_FETCH` variable:
1. Open the configuration file `/etc/gitlab/gitlab.rb`.
1. Add or update the variable:
```ruby
gitlab_rails['env'] = {
"GITLAB_LFS_MAX_OID_TO_FETCH" => "NEW_VALUE"
}
```
Replace `NEW_VALUE` with a number based on your requirements.
1. Apply the changes. Run:
```shell
sudo gitlab-ctl reconfigure
```
For additional information, see [Reconfigure a Linux package installation](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Repeat the fork operation.
{{< alert type="note" >}}
For the GitLab Helm chart, use [`extraEnv`](https://docs.gitlab.com/charts/charts/globals.html#extraenv) to configure the environment variable `GITLAB_LFS_MAX_OID_TO_FETCH`.
{{< /alert >}}
|
---
stage: Create
group: Source Code
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Configure Git LFS for GitLab Self-Managed.
title: GitLab Git Large File Storage (LFS) Administration
breadcrumbs:
- doc
- administration
- lfs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Use Git Large File Storage (LFS) to store large files in a Git repository without
increasing its size or affecting performance. You can enable or disable LFS, configure local
or remote storage for LFS objects, and migrate objects between storage types.
For user documentation about Git LFS, see [Git Large File Storage](../../topics/git/lfs/_index.md).
Prerequisites:
- Users must install [Git LFS client](https://git-lfs.com/) version 1.1.0 and later, or 1.0.2.
## Enable or disable LFS
LFS is enabled by default. To disable it:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# Change to true to enable lfs - enabled by default if not defined
gitlab_rails['lfs_enabled'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
global:
appConfig:
lfs:
enabled: false
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['lfs_enabled'] = false
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
production: &base
lfs:
enabled: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Change local storage path
Git LFS objects can be large in size. By default, they are stored on the server
GitLab is installed on.
{{< alert type="note" >}}
For Docker installations, you can change the path where your data is mounted.
For the Helm chart, use
[object storage](https://docs.gitlab.com/charts/advanced/external-object-storage/).
{{< /alert >}}
To change the default local storage path location:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
# /var/opt/gitlab/gitlab-rails/shared/lfs-objects by default.
gitlab_rails['lfs_storage_path'] = "/mnt/storage/lfs-objects"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab/config/gitlab.yml`:
```yaml
# /home/git/gitlab/shared/lfs-objects by default.
production: &base
lfs:
storage_path: /mnt/storage/lfs-objects
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Storing LFS objects in remote object storage
You can store LFS objects in remote object storage. This allows you
to reduce reads and writes to the local disk, and free up disk space significantly.
You should use the
[consolidated object storage settings](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
### Migrating to object storage
You can migrate the LFS objects from local storage to object storage. The
processing is done in the background and requires no downtime.
1. [Configure the object storage](../object_storage.md#configure-a-single-storage-connection-for-all-object-types-consolidated-form).
1. Migrate the LFS objects:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rake gitlab:lfs:migrate
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
sudo docker exec -t <container name> gitlab-rake gitlab:lfs:migrate
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rake gitlab:lfs:migrate RAILS_ENV=production
```
{{< /tab >}}
{{< /tabs >}}
1. Optional. Track the progress and verify that all job LFS objects migrated
successfully using the PostgreSQL console.
1. Open a PostgreSQL console:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-psql
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
sudo docker exec -it <container_name> /bin/bash
gitlab-psql
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H psql -d gitlabhq_production
```
{{< /tab >}}
{{< /tabs >}}
1. Verify that all LFS files migrated to object storage with the following
SQL query. The number of `objectstg` should be the same as `total`:
```shell
gitlabhq_production=# SELECT count(*) AS total, sum(case when file_store = '1' then 1 else 0 end) AS filesystem, sum(case when file_store = '2' then 1 else 0 end) AS objectstg FROM lfs_objects;
total | filesystem | objectstg
------+------------+-----------
2409 | 0 | 2409
```
1. Verify that there are no files on disk in the `lfs-objects` directory:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo find /var/opt/gitlab/gitlab-rails/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< tab title="Docker" >}}
Assuming you mounted `/var/opt/gitlab` to `/srv/gitlab`:
```shell
sudo find /srv/gitlab/gitlab-rails/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo find /home/git/gitlab/shared/lfs-objects -type f | grep -v tmp | wc -l
```
{{< /tab >}}
{{< /tabs >}}
### Migrating back to local storage
{{< alert type="note" >}}
For the Helm chart, you should use
[object storage](https://docs.gitlab.com/charts/advanced/external-object-storage/).
{{< /alert >}}
To migrate back to local storage:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Migrate the LFS objects:
```shell
sudo gitlab-rake gitlab:lfs:migrate_to_local
```
1. Edit `/etc/gitlab/gitlab.rb` and
[disable object storage](../object_storage.md#disable-object-storage-for-specific-features)
for LFS objects:
```ruby
gitlab_rails['object_store']['objects']['lfs']['enabled'] = false
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Migrate the LFS objects:
```shell
sudo docker exec -t <container name> gitlab-rake gitlab:lfs:migrate_to_local
```
1. Edit `docker-compose.yml` and disable object storage for LFS objects:
```yaml
version: "3.6"
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['object_store']['objects']['lfs']['enabled'] = false
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Migrate the LFS objects:
```shell
sudo -u git -H bundle exec rake gitlab:lfs:migrate_to_local RAILS_ENV=production
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and disable object storage for LFS objects:
```yaml
production: &base
object_store:
objects:
lfs:
enabled: false
```
1. Save the file and restart GitLab:
```shell
# For systems running systemd
sudo systemctl restart gitlab.target
# For systems running SysV init
sudo service gitlab restart
```
{{< /tab >}}
{{< /tabs >}}
## Pure SSH transfer protocol
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11872) in GitLab 17.2.
- [Introduced](https://gitlab.com/gitlab-org/charts/gitlab/-/merge_requests/3845) for Helm chart (Kubernetes) in GitLab 17.3.
{{< /history >}}
{{< alert type="warning" >}}
This feature is affected by [a known issue](https://github.com/git-lfs/git-lfs/issues/5880)
(resolved in [Git LFS 3.6.0](https://github.com/git-lfs/git-lfs/blob/main/CHANGELOG.md#360-20-november-2024)).
If you clone a repository with multiple Git LFS objects using the pure SSH protocol,
the client might crash due to a `nil` pointer reference.
{{< /alert >}}
[`git-lfs` 3.0.0](https://github.com/git-lfs/git-lfs/blob/main/CHANGELOG.md#300-24-sep-2021)
released support for using SSH as the transfer protocol instead of HTTP.
SSH is handled transparently by the `git-lfs` command line tool.
When pure SSH protocol support is enabled and `git` is configured to use SSH,
all LFS operations happen over SSH. For example, when the Git remote is
`git@gitlab.com:gitlab-org/gitlab.git`. You can't configure `git` and `git-lfs`
to use different protocols. From version 3.0, `git-lfs` attempts to use the pure
SSH protocol initially and, if support is not enabled or available, it falls back
to using HTTP.
Prerequisites:
- The `git-lfs` version must be [v3.5.1](https://github.com/git-lfs/git-lfs/releases/tag/v3.5.1) or higher.
To switch Git LFS to use pure SSH protocol:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_shell['lfs_pure_ssh_protocol'] = true
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
gitlab:
gitlab-shell:
config:
lfs:
pureSSHProtocol: true
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
services:
gitlab:
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_shell['lfs_pure_ssh_protocol'] = true
```
1. Save the file and restart GitLab and its services:
```shell
docker compose up -d
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
1. Edit `/home/git/gitlab-shell/config.yml`:
```yaml
lfs:
pure_ssh_protocol: true
```
1. Save the file and restart GitLab Shell:
```shell
# For systems running systemd
sudo systemctl restart gitlab-shell.target
# For systems running SysV init
sudo service gitlab-shell restart
```
{{< /tab >}}
{{< /tabs >}}
## Storage statistics
You can see the total storage used for LFS objects for groups and projects in:
- The **Admin** area
- The [groups](../../api/groups.md) and [projects](../../api/projects.md) APIs
{{< alert type="note" >}}
The storage statistics count each LFS object for every project linking to it.
{{< /alert >}}
## Related topics
- Blog post: [Getting started with Git LFS](https://about.gitlab.com/blog/2017/01/30/getting-started-with-git-lfs-tutorial/)
- User documentation: [Git Large File Storage (LFS)](../../topics/git/lfs/_index.md)
## Troubleshooting
### Missing LFS objects
An error about a missing LFS object may occur in either of these situations:
- When migrating LFS objects from disk to object storage, with error messages like:
```plaintext
ERROR -- : Failed to transfer LFS object
006622269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
with error: No such file or directory @ rb_sysopen -
/var/opt/gitlab/gitlab-rails/shared/lfs-objects/00/66/22269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
```
(Line breaks have been added for legibility.)
- When running the
[integrity check for LFS objects](../raketasks/check.md#uploaded-files-integrity)
with the `VERBOSE=1` parameter.
The database can have records for LFS objects which are not on disk. The database entry may
[prevent a new copy of the object from being pushed](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49241).
To delete these references:
1. [Start a rails console](../operations/rails_console.md).
1. Query the object that's reported as missing in the rails console, to return a file path:
```ruby
lfs_object = LfsObject.find_by(oid: '006622269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7')
lfs_object.file.path
```
1. Check on disk or object storage if it exists:
```shell
ls -al /var/opt/gitlab/gitlab-rails/shared/lfs-objects/00/66/22269c61b41bf14a22bbe0e43be3acf86a4a446afb4250c3794ea47541a7
```
1. If the file is not present, remove the database records with the Rails console:
```ruby
# First delete the parent records and then destroy the record itself
lfs_object.lfs_objects_projects.destroy_all
lfs_object.destroy
```
#### Remove multiple missing LFS objects
To remove references to multiple missing LFS objects at once:
1. Open the [GitLab Rails Console](../operations/rails_console.md#starting-a-rails-console-session).
1. Run the following script:
```ruby
lfs_files_deleted = 0
LfsObject.find_each do |lfs_file|
next if lfs_file.file.file.exists?
lfs_files_deleted += 1
p "LFS file with ID #{lfs_file.id} and path #{lfs_file.file.path} is missing."
# lfs_file.lfs_objects_projects.destroy_all # Uncomment to delete parent records
# lfs_file.destroy # Uncomment to destroy the LFS object reference
end
p "Count of identified/destroyed invalid references: #{lfs_files_deleted}"
```
This script identifies all missing LFS objects in the database. Before deleting any records:
- It first prints information about missing files for verification.
- The commented lines prevent accidental deletion. If you uncomment them, the script deletes the
identified records.
- The script automatically prints a final count of deleted records for comparison.
### LFS commands fail on TLS v1.3 server
If you configure GitLab to [disable TLS v1.2](https://docs.gitlab.com/omnibus/settings/nginx.html)
and only enable TLS v1.3 connections, LFS operations require a
[Git LFS client](https://git-lfs.com/) version 2.11.0 or later. If you use
a Git LFS client earlier than version 2.11.0, GitLab displays an error:
```plaintext
batch response: Post https://username:***@gitlab.example.com/tool/releases.git/info/lfs/objects/batch: remote error: tls: protocol version not supported
error: failed to fetch some objects from 'https://username:[MASKED]@gitlab.example.com/tool/releases.git/info/lfs'
```
When using GitLab CI over a TLS v1.3 configured GitLab server, you must
[upgrade to GitLab Runner](https://docs.gitlab.com/runner/install/) 13.2.0
or later to receive an updated Git LFS client version with
the included [GitLab Runner Helper image](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#helper-image).
To check an installed Git LFS client's version, run this command:
```shell
git lfs version
```
### `Connection refused` errors
If you push or mirror LFS objects and receive errors like the following:
- `dial tcp <IP>:443: connect: connection refused`
- `Connection refused - connect(2) for \"<target-or-proxy-IP>\" port 443`
a firewall or proxy rule may be terminating the connection.
If connection checks with standard Unix tools or manual Git pushes are successful,
the rule may be related to the size of the request.
### Error viewing a PDF file
When LFS has been configured with object storage and `proxy_download` set to
`false`, [you may see an error when previewing a PDF file from the Web browser](https://gitlab.com/gitlab-org/gitlab/-/issues/248100):
```plaintext
An error occurred while loading the file. Please try again later.
```
This occurs due to Cross-Origin Resource Sharing (CORS) restrictions:
the browser attempts to load the PDF from object storage, but the object
storage provider rejects the request because the GitLab domain differs
from the object storage domain.
To fix this issue, configure your object storage provider's CORS
settings to allow the GitLab domain. See the following documentation
for more details:
1. [AWS S3](https://repost.aws/knowledge-center/s3-configure-cors)
1. [Google Cloud Storage](https://cloud.google.com/storage/docs/using-cors)
1. [Azure Storage](https://learn.microsoft.com/en-us/rest/api/storageservices/cross-origin-resource-sharing--cors--support-for-the-azure-storage-services).
### Fork operation stuck on `Forking in progress` message
If you are forking a project with multiple LFS files, the operation might get stuck with a `Forking in progress` message.
If you encounter this, follow these steps to diagnose and resolve the issue:
1. Check your [exceptions_json.log](../logs/_index.md#exceptions_jsonlog) file for the following error message:
```plaintext
"error_message": "Unable to fork project 12345 for repository
@hashed/11/22/encoded-path -> @hashed/33/44/encoded-new-path:
Source project has too many LFS objects"
```
This error indicates that you've reached the default limit of 100,000 LFS files,
as described in issue [#476693](https://gitlab.com/gitlab-org/gitlab/-/issues/476693).
1. Increase the value of the `GITLAB_LFS_MAX_OID_TO_FETCH` variable:
1. Open the configuration file `/etc/gitlab/gitlab.rb`.
1. Add or update the variable:
```ruby
gitlab_rails['env'] = {
"GITLAB_LFS_MAX_OID_TO_FETCH" => "NEW_VALUE"
}
```
Replace `NEW_VALUE` with a number based on your requirements.
1. Apply the changes. Run:
```shell
sudo gitlab-ctl reconfigure
```
For additional information, see [Reconfigure a Linux package installation](../restart_gitlab.md#reconfigure-a-linux-package-installation).
1. Repeat the fork operation.
{{< alert type="note" >}}
For the GitLab Helm chart, use [`extraEnv`](https://docs.gitlab.com/charts/charts/globals.html#extraenv) to configure the environment variable `GITLAB_LFS_MAX_OID_TO_FETCH`.
{{< /alert >}}
|
https://docs.gitlab.com/administration/replication_and_failover
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/replication_and_failover.md
|
2025-08-13
|
doc/administration/redis
|
[
"doc",
"administration",
"redis"
] |
replication_and_failover.md
|
Data access
|
Durability
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Redis replication and failover with the Linux package
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This documentation is for the Linux package. To use your own
non-bundled Redis, see [Redis replication and failover providing your own instance](replication_and_failover_external.md).
In Redis lingo, `primary` is called `master`. In this document, `primary` is used
instead of `master`, except the settings where `master` is required.
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
Before diving into the details of setting up Redis and Redis Sentinel for a
replicated topology, make sure you read this document once as a whole to better
understand how the components are tied together.
You need at least `3` independent machines: physical, or VMs running into
distinct physical machines. It is essential that all primary and replica Redis
instances run in different machines. If you fail to provision the machines in
that specific way, any issue with the shared environment can bring your entire
setup down.
It is OK to run a Sentinel alongside of a primary or replica Redis instance.
There should be no more than one Sentinel on the same machine though.
You also need to take into consideration the underlying network topology,
making sure you have redundant connectivity between Redis / Sentinel and
GitLab instances, otherwise the networks become a single point of
failure.
Running Redis in a scaled environment requires a few things:
- Multiple Redis instances
- Run Redis in a **Primary** x **Replica** topology
- Multiple Sentinel instances
- Application support and visibility to all Sentinel and Redis instances
Redis Sentinel can handle the most important tasks in an HA environment and that's
to help keep servers online with minimal to no downtime. Redis Sentinel:
- Monitors **Primary** and **Replicas** instances to see if they are available
- Promotes a **Replica** to **Primary** when the **Primary** fails
- Demotes a **Primary** to **Replica** when the failed **Primary** comes back online
(to prevent data-partitioning)
- Can be queried by the application to always connect to the current **Primary**
server
When a **Primary** fails to respond, it's the application's responsibility
(in our case GitLab) to handle timeout and reconnect (querying a **Sentinel**
for a new **Primary**).
To get a better understanding on how to correctly set up Sentinel, read
the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation first, as
failing to configure it correctly can lead to data loss or can bring your
whole cluster down, invalidating the failover effort.
## Recommended setup
For a minimal setup, you need to install the Linux package in `3`
**independent** machines, both with **Redis** and **Sentinel**:
- Redis Primary + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
If you are not sure or don't understand why and where the amount of nodes come
from, read [Redis setup overview](#redis-setup-overview) and
[Sentinel setup overview](#sentinel-setup-overview).
For a recommended setup that can resist more failures, you need to install
the Linux package in `5` **independent** machines, both with
**Redis** and **Sentinel**:
- Redis Primary + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
### Redis setup overview
You must have at least `3` Redis servers: `1` primary, `2` Replicas, and they
need to each be on independent machines.
You can have additional Redis nodes, that helps to survive a situation
where more nodes goes down. Whenever there is only `2` nodes online, a failover
is not initiated.
As an example, if you have `6` Redis nodes, a maximum of `3` can be
simultaneously down.
There are different requirements for Sentinel nodes.
If you host them in the same Redis machines, you may need to take
that restrictions into consideration when calculating the amount of
nodes to be provisioned. See [Sentinel setup overview](#sentinel-setup-overview)
documentation for more information.
All Redis nodes should be configured the same way and with similar server specs, as
in a failover situation, any **Replica** can be promoted as the new **Primary** by
the Sentinel servers.
The replication requires authentication, so you need to define a password to
protect all Redis nodes and the Sentinels. All of them share the same
password, and all instances must be able to talk to
each other over the network.
### Sentinel setup overview
Sentinels watch both other Sentinels and Redis nodes. Whenever a Sentinel
detects that a Redis node isn't responding, it announces the node's status to
the other Sentinels. The Sentinels have to reach a _quorum_ (the minimum amount
of Sentinels agreeing a node is down) to be able to start a failover.
Whenever the **quorum** is met, the **majority** of all known Sentinel nodes
need to be available and reachable, so that they can elect the Sentinel **leader**
who takes all the decisions to restore the service availability by:
- Promoting a new **Primary**
- Reconfiguring the other **Replicas** and make them point to the new **Primary**
- Announce the new **Primary** to every other Sentinel peer
- Reconfigure the old **Primary** and demote to **Replica** when it comes back online
You must have at least `3` Redis Sentinel servers, and they need to
be each in an independent machine (that are believed to fail independently),
ideally in different geographical areas.
You can configure them in the same machines where you've configured the other
Redis servers, but understand that if a whole node goes down, you loose both
a Sentinel and a Redis instance.
The number of sentinels should ideally always be an **odd** number, for the
consensus algorithm to be effective in the case of a failure.
In a `3` nodes topology, you can only afford `1` Sentinel node going down.
Whenever the **majority** of the Sentinels goes down, the network partition
protection prevents destructive actions and a failover **is not started**.
Here are some examples:
- With `5` or `6` sentinels, a maximum of `2` can go down for a failover begin.
- With `7` sentinels, a maximum of `3` nodes can go down.
The **Leader** election can sometimes fail the voting round when **consensus**
is not achieved. In that case,
a new attempt is made after the amount of time defined in
`sentinel['failover_timeout']` (in milliseconds).
{{< alert type="note" >}}
We can see where `sentinel['failover_timeout']` is defined later.
{{< /alert >}}
The `failover_timeout` variable has a lot of different use cases. According to
the official documentation:
- The time needed to re-start a failover after a previous failover was
already tried against the same primary by a given Sentinel, is two
times the failover timeout.
- The time needed for a replica replicating to a wrong primary according
to a Sentinel current configuration, to be forced to replicate
with the right primary, is exactly the failover timeout (counting since
the moment a Sentinel detected the misconfiguration).
- The time needed to cancel a failover that is already in progress but
did not produced any configuration change (REPLICAOF NO ONE yet not
acknowledged by the promoted replica).
- The maximum time a failover in progress waits for all the replicas to be
reconfigured as replicas of the new primary. However even after this time
the replicas are reconfigured by the Sentinels anyway, but not with
the exact parallel-syncs progression as specified.
## Configuring Redis
This is the section where we install and set up the new Redis instances.
It is assumed that you have installed GitLab and all its components from scratch.
If you already have Redis installed and running, read how to
[switch from a single-machine installation](#switching-from-an-existing-single-machine-installation).
{{< alert type="note" >}}
Redis nodes (both primary and replica) need the same password defined in
`redis['password']`. At any time during a failover the Sentinels can
reconfigure a node and change its status from primary to replica and vice versa.
{{< /alert >}}
### Requirements
The requirements for a Redis setup are the following:
1. Provision the minimum required number of instances as specified in the
[recommended setup](#recommended-setup) section.
1. We **Do not** recommend installing Redis or Redis Sentinel in the same machines your
GitLab application is running on as this weakens your HA configuration. You can however opt in to install Redis
and Sentinel in the same machine.
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks ([Internet](https://gitlab.com/gitlab-org/gitlab-foss/uploads/c4cc8cd353604bd80315f9384035ff9e/The_Internet_IT_Crowd.png)), using
firewall.
### Switching from an existing single-machine installation
If you already have a single-machine GitLab install running, you need to
replicate from this machine first, before de-activating the Redis instance
inside it.
Your single-machine install is the initial **Primary**, and the `3` others
should be configured as **Replica** pointing to this machine.
After replication catches up, you need to stop services in the
single-machine install, to rotate the **Primary** to one of the new nodes.
Make the required changes in configuration and restart the new nodes again.
To disable Redis in the single install, edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['enable'] = false
```
If you fail to replicate first, you may loose data (unprocessed background jobs).
### Step 1. Configuring the primary Redis instance
1. SSH into the **Primary** Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want using **steps 1 and 2** from the GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
and type (Community, Enterprise editions) of your current install.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_master_role'
roles ['redis_master_role']
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really need to bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.0.0.1'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# Set up password authentication for Redis (use the same password in all nodes).
redis['password'] = 'redis-password-goes-here'
```
1. Only the primary GitLab application server should handle migrations. To
prevent database migrations from running on upgrade, add the following
configuration to your `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< alert type="note" >}}
You can specify multiple roles like sentinel and Redis as:
`roles ['redis_sentinel_role', 'redis_master_role']`.
Read more about [roles](https://docs.gitlab.com/omnibus/roles/).
{{< /alert >}}
### Step 2. Configuring the replica Redis instances
1. SSH into the **replica** Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want using **steps 1 and 2** from the GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
and type (Community, Enterprise editions) of your current install.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_replica_role'
roles ['redis_replica_role']
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really need to bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.0.0.2'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'redis-password-goes-here'
# The IP of the primary Redis node.
redis['master_ip'] = '10.0.0.1'
# Port of primary Redis server, uncomment to change to non default. Defaults
# to `6379`.
#redis['master_port'] = 6379
```
1. To prevent reconfigure from running automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. Only the primary GitLab application server should handle migrations. To
prevent database migrations from running on upgrade, add the following
configuration to your `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes.
{{< alert type="note" >}}
You can specify multiple roles like sentinel and Redis as:
`roles ['redis_sentinel_role', 'redis_master_role']`.
Read more about [roles](https://docs.gitlab.com/omnibus/roles/).
{{< /alert >}}
These values don't have to be changed again in `/etc/gitlab/gitlab.rb` after
a failover, as the nodes are managed by the Sentinels, and even after a
`gitlab-ctl reconfigure`, they get their configuration restored by
the same Sentinels.
### Step 3. Configuring the Redis Sentinel instances
{{< alert type="note" >}}
[Support for Sentinel password authentication](https://gitlab.com/gitlab-org/gitlab/-/issues/235938) was introduced in GitLab 16.1.
{{< /alert >}}
Now that the Redis servers are all set up, let's configure the Sentinel
servers.
If you are not sure if your Redis servers are working and replicating
correctly, read the [Troubleshooting Replication](troubleshooting.md#troubleshooting-redis-replication)
and fix it before proceeding with Sentinel setup.
You must have at least `3` Redis Sentinel servers, and they need to
be each in an independent machine. You can configure them in the same
machines where you've configured the other Redis servers.
With GitLab Enterprise Edition, you can use the Linux package to set up
multiple machines with the Sentinel daemon.
1. SSH into the server that hosts Redis Sentinel.
1. **You can omit this step if the Sentinels is hosted in the same node as
the other Redis instances**.
[Download and install](https://about.gitlab.com/install/) the
Linux Enterprise Edition package using **steps 1 and 2** from the
GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
the GitLab application is running.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents (if you are installing the
Sentinels in the same node as the other Redis instances, some values might
be duplicate below):
```ruby
roles ['redis_sentinel_role']
# Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
# The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'redis-password-goes-here'
# The IP of the primary Redis node.
redis['master_ip'] = '10.0.0.1'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# Port of primary Redis server, uncomment to change to non default. Defaults
# to `6379`.
#redis['master_port'] = 6379
## Configure Sentinel
sentinel['bind'] = '10.0.0.1'
## Optional password for Sentinel authentication. Defaults to no password required.
# sentinel['password'] = 'sentinel-password-goes here'
# Port that Sentinel listens on, uncomment to change to non default. Defaults
# to `26379`.
# sentinel['port'] = 26379
## Quorum must reflect the amount of voting sentinels it take to start a failover.
## Value must NOT be greater then the amount of sentinels.
##
## The quorum can be used to tune Sentinel in two ways:
## 1. If a the quorum is set to a value smaller than the majority of Sentinels
## we deploy, we are basically making Sentinel more sensible to primary failures,
## triggering a failover as soon as even just a minority of Sentinels is no longer
## able to talk with the primary.
## 1. If a quorum is set to a value greater than the majority of Sentinels, we are
## making Sentinel able to failover only when there are a very large number (larger
## than majority) of well connected Sentinels which agree about the primary being down.s
sentinel['quorum'] = 2
## Consider unresponsive server down after x amount of ms.
# sentinel['down_after_milliseconds'] = 10000
## Specifies the failover timeout in milliseconds. It is used in many ways:
##
## - The time needed to re-start a failover after a previous failover was
## already tried against the same primary by a given Sentinel, is two
## times the failover timeout.
##
## - The time needed for a replica replicating to a wrong primary according
## to a Sentinel current configuration, to be forced to replicate
## with the right primary, is exactly the failover timeout (counting since
## the moment a Sentinel detected the misconfiguration).
##
## - The time needed to cancel a failover that is already in progress but
## did not produced any configuration change (REPLICAOF NO ONE yet not
## acknowledged by the promoted replica).
##
## - The maximum time a failover in progress waits for all the replica to be
## reconfigured as replicas of the new primary. However even after this time
## the replicas are reconfigured by the Sentinels anyway, but not with
## the exact parallel-syncs progression as specified.
# sentinel['failover_timeout'] = 60000
```
1. To prevent database migrations from running on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only the primary GitLab application server should handle migrations.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Sentinel nodes.
### Step 4. Configuring the GitLab application
The final part is to inform the main GitLab application server of the Redis
Sentinels servers and authentication credentials.
You can enable or disable Sentinel support at any time in new or existing
installations. From the GitLab application perspective, all it requires is
the correct credentials for the Sentinel nodes.
While it doesn't require a list of all Sentinel nodes, in case of a failure,
it needs to access at least one of the listed.
{{< alert type="note" >}}
The following steps should be performed in the GitLab application server
which ideally should not have Redis or Sentinels on it for a HA setup.
{{< /alert >}}
1. SSH into the server where the GitLab application is installed.
1. Edit `/etc/gitlab/gitlab.rb` and add/change the following lines:
```ruby
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'redis-password-goes-here'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.0.0.1', 'port' => 26379},
{'host' => '10.0.0.2', 'port' => 26379},
{'host' => '10.0.0.3', 'port' => 26379}
]
# gitlab_rails['redis_sentinels_password'] = 'sentinel-password-goes-here' # uncomment and set it to the same value as in sentinel['password']
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Step 5. Enable Monitoring
If you enable Monitoring, it must be enabled on **all** Redis servers.
1. Make sure to collect [`CONSUL_SERVER_NODES`](../postgresql/replication_and_failover.md#consul-information), which are the IP addresses or DNS records of the Consul server nodes, for the next step. Note they are presented as `Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z`
1. Create/edit `/etc/gitlab/gitlab.rb` and add the following configuration:
```ruby
# Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Replace placeholders
# Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z
# with the addresses of the Consul server nodes
consul['configuration'] = {
retry_join: %w(Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z),
}
# Set the network addresses that the exporters listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
```
1. Run `sudo gitlab-ctl reconfigure` to compile the configuration.
## Example of a minimal configuration with 1 primary, 2 replicas and 3 Sentinels
In this example we consider that all servers have an internal network
interface with IPs in the `10.0.0.x` range, and that they can connect
to each other using these IPs.
In a real world usage, you would also set up firewall rules to prevent
unauthorized access from other machines and block traffic from the
outside (Internet).
We use the same `3` nodes with **Redis** + **Sentinel** topology
discussed in [Redis setup overview](#redis-setup-overview) and
[Sentinel setup overview](#sentinel-setup-overview) documentation.
Here is a list and description of each **machine** and the assigned **IP**:
- `10.0.0.1`: Redis primary + Sentinel 1
- `10.0.0.2`: Redis Replica 1 + Sentinel 2
- `10.0.0.3`: Redis Replica 2 + Sentinel 3
- `10.0.0.4`: GitLab application
After the initial configuration, if a failover is initiated
by the Sentinel nodes, the Redis nodes are reconfigured and the **Primary**
changes permanently (including in `redis.conf`) from one node to the other,
until a new failover is initiated again.
The same thing happens with `sentinel.conf` that is overridden after the
initial execution, after any new sentinel node starts watching the **Primary**,
or a failover promotes a different **Primary** node.
### Example configuration for Redis primary and Sentinel 1
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_master_role']
redis['bind'] = '10.0.0.1'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
redis['master_password'] = 'redis-password-goes-here' # the same value defined in redis['password'] in the primary instance
redis['master_ip'] = '10.0.0.1' # ip of the initial primary redis instance
#redis['master_port'] = 6379 # port of the initial primary redis instance, uncomment to change to non default
sentinel['bind'] = '10.0.0.1'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for Redis replica 1 and Sentinel 2
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_replica_role']
redis['bind'] = '10.0.0.2'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_password'] = 'redis-password-goes-here'
redis['master_ip'] = '10.0.0.1' # IP of primary Redis server
#redis['master_port'] = 6379 # Port of primary Redis server, uncomment to change to non default
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
sentinel['bind'] = '10.0.0.2'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for Redis replica 2 and Sentinel 3
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_replica_role']
redis['bind'] = '10.0.0.3'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_password'] = 'redis-password-goes-here'
redis['master_ip'] = '10.0.0.1' # IP of primary Redis server
#redis['master_port'] = 6379 # Port of primary Redis server, uncomment to change to non default
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
sentinel['bind'] = '10.0.0.3'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for the GitLab application
In `/etc/gitlab/gitlab.rb`:
```ruby
redis['master_name'] = 'gitlab-redis'
redis['master_password'] = 'redis-password-goes-here'
gitlab_rails['redis_sentinels'] = [
{'host' => '10.0.0.1', 'port' => 26379},
{'host' => '10.0.0.2', 'port' => 26379},
{'host' => '10.0.0.3', 'port' => 26379}
]
# gitlab_rails['redis_sentinels_password'] = 'sentinel-password-goes-here' # uncomment and set it to the same value as in sentinel['password']
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Advanced configuration
This section covers configuration options that go beyond the recommended and minimal configurations.
### Running multiple Redis clusters
The Linux package supports running separate Redis and Sentinel instances for different
persistence classes.
| Class | Purpose |
|--------------------|---------|
| `cache` | Store cached data. |
| `queues` | Store Sidekiq background jobs. |
| `shared_state` | Store session-related and other persistent data. |
| `actioncable` | Pub/Sub queue backend for ActionCable. |
| `trace_chunks` | Store [CI trace chunks](../cicd/job_logs.md#incremental-logging) data. |
| `rate_limiting` | Store [rate limiting](../settings/user_and_ip_rate_limits.md) state. |
| `sessions` | Store sessions. |
| `repository_cache` | Store cache data specific to repositories. |
To make this work with Sentinel:
1. [Configure the different Redis/Sentinels](#configuring-redis) instances based on your needs.
1. For each Rails application instance, edit its `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['redis_cache_instance'] = REDIS_CACHE_URL
gitlab_rails['redis_queues_instance'] = REDIS_QUEUES_URL
gitlab_rails['redis_shared_state_instance'] = REDIS_SHARED_STATE_URL
gitlab_rails['redis_actioncable_instance'] = REDIS_ACTIONCABLE_URL
gitlab_rails['redis_trace_chunks_instance'] = REDIS_TRACE_CHUNKS_URL
gitlab_rails['redis_rate_limiting_instance'] = REDIS_RATE_LIMITING_URL
gitlab_rails['redis_sessions_instance'] = REDIS_SESSIONS_URL
gitlab_rails['redis_repository_cache_instance'] = REDIS_REPOSITORY_CACHE_URL
# Configure the Sentinels
gitlab_rails['redis_cache_sentinels'] = [
{ host: REDIS_CACHE_SENTINEL_HOST, port: 26379 },
{ host: REDIS_CACHE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_queues_sentinels'] = [
{ host: REDIS_QUEUES_SENTINEL_HOST, port: 26379 },
{ host: REDIS_QUEUES_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_shared_state_sentinels'] = [
{ host: SHARED_STATE_SENTINEL_HOST, port: 26379 },
{ host: SHARED_STATE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_actioncable_sentinels'] = [
{ host: ACTIONCABLE_SENTINEL_HOST, port: 26379 },
{ host: ACTIONCABLE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_trace_chunks_sentinels'] = [
{ host: TRACE_CHUNKS_SENTINEL_HOST, port: 26379 },
{ host: TRACE_CHUNKS_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_rate_limiting_sentinels'] = [
{ host: RATE_LIMITING_SENTINEL_HOST, port: 26379 },
{ host: RATE_LIMITING_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_sessions_sentinels'] = [
{ host: SESSIONS_SENTINEL_HOST, port: 26379 },
{ host: SESSIONS_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_repository_cache_sentinels'] = [
{ host: REPOSITORY_CACHE_SENTINEL_HOST, port: 26379 },
{ host: REPOSITORY_CACHE_SENTINEL_HOST2, port: 26379 }
]
# gitlab_rails['redis_cache_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_queues_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_shared_state_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_actioncable_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_trace_chunks_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_rate_limiting_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_sessions_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_repository_cache_sentinels_password'] = 'sentinel-password-goes-here'
```
- Redis URLs should be in the format: `redis://:PASSWORD@SENTINEL_PRIMARY_NAME`, where:
- `PASSWORD` is the plaintext password for the Redis instance.
- `SENTINEL_PRIMARY_NAME` is the Sentinel primary name set with `redis['master_name']`,
for example `gitlab-redis-cache`.
1. Save the file and reconfigure GitLab for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
{{< alert type="note" >}}
For each persistence class, GitLab defaults to using the
configuration specified in `gitlab_rails['redis_sentinels']` unless
overridden by the previously described settings.
{{< /alert >}}
### Control running services
In the previous example, we've used `redis_sentinel_role` and
`redis_master_role` which simplifies the amount of configuration changes.
If you want more control, here is what each one sets for you automatically
when enabled:
```ruby
## Redis Sentinel Role
redis_sentinel_role['enable'] = true
# When Sentinel Role is enabled, the following services are also enabled
sentinel['enable'] = true
# The following services are disabled
redis['enable'] = false
bootstrap['enable'] = false
nginx['enable'] = false
postgresql['enable'] = false
gitlab_rails['enable'] = false
mailroom['enable'] = false
-------
## Redis primary/replica Role
redis_master_role['enable'] = true # enable only one of them
redis_replica_role['enable'] = true # enable only one of them
# When Redis primary or Replica role are enabled, the following services are
# enabled/disabled. If Redis and Sentinel roles are combined, both
# services are enabled.
# The following services are disabled
sentinel['enable'] = false
bootstrap['enable'] = false
nginx['enable'] = false
postgresql['enable'] = false
gitlab_rails['enable'] = false
mailroom['enable'] = false
# For Redis Replica role, also change this setting from default 'true' to 'false':
redis['master'] = false
```
You can find the relevant attributes defined in [`gitlab_rails.rb`](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-cookbooks/gitlab/libraries/gitlab_rails.rb).
### Control startup behavior
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6646) in GitLab 15.10.
{{< /history >}}
To prevent the bundled Redis service from starting at boot or restarting after changing its configuration:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['start_down'] = true
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
If you need to test a new replica node, you may set `start_down` to
`true` and manually start the node. After the new replica node is confirmed
working in the Redis cluster, set `start_down` to `false` and reconfigure GitLab
to ensure the node starts and restarts as expected during operation.
### Control replica configuration
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6646) in GitLab 15.10.
{{< /history >}}
To prevent the `replicaof` line from rendering in the Redis configuration file:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['set_replicaof'] = false
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
This setting can be used to prevent replication of a Redis node independently of other Redis settings.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
## Further reading
Read more:
1. [Reference architectures](../reference_architectures/_index.md)
1. [Configure the database](../postgresql/replication_and_failover.md)
1. [Configure NFS](../nfs.md)
1. [Configure the load balancers](../load_balancer.md)
|
---
stage: Data access
group: Durability
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Redis replication and failover with the Linux package
breadcrumbs:
- doc
- administration
- redis
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This documentation is for the Linux package. To use your own
non-bundled Redis, see [Redis replication and failover providing your own instance](replication_and_failover_external.md).
In Redis lingo, `primary` is called `master`. In this document, `primary` is used
instead of `master`, except the settings where `master` is required.
Using [Redis](https://redis.io/) in scalable environment is possible using a **Primary** x **Replica**
topology with a [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) service to watch and automatically
start the failover procedure.
Redis requires authentication if used with Sentinel. See
[Redis Security](https://redis.io/docs/latest/operate/rc/security/) documentation for more
information. We recommend using a combination of a Redis password and tight
firewall rules to secure your Redis service.
You are highly encouraged to read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation
before configuring Redis with GitLab to fully understand the topology and
architecture.
Before diving into the details of setting up Redis and Redis Sentinel for a
replicated topology, make sure you read this document once as a whole to better
understand how the components are tied together.
You need at least `3` independent machines: physical, or VMs running into
distinct physical machines. It is essential that all primary and replica Redis
instances run in different machines. If you fail to provision the machines in
that specific way, any issue with the shared environment can bring your entire
setup down.
It is OK to run a Sentinel alongside of a primary or replica Redis instance.
There should be no more than one Sentinel on the same machine though.
You also need to take into consideration the underlying network topology,
making sure you have redundant connectivity between Redis / Sentinel and
GitLab instances, otherwise the networks become a single point of
failure.
Running Redis in a scaled environment requires a few things:
- Multiple Redis instances
- Run Redis in a **Primary** x **Replica** topology
- Multiple Sentinel instances
- Application support and visibility to all Sentinel and Redis instances
Redis Sentinel can handle the most important tasks in an HA environment and that's
to help keep servers online with minimal to no downtime. Redis Sentinel:
- Monitors **Primary** and **Replicas** instances to see if they are available
- Promotes a **Replica** to **Primary** when the **Primary** fails
- Demotes a **Primary** to **Replica** when the failed **Primary** comes back online
(to prevent data-partitioning)
- Can be queried by the application to always connect to the current **Primary**
server
When a **Primary** fails to respond, it's the application's responsibility
(in our case GitLab) to handle timeout and reconnect (querying a **Sentinel**
for a new **Primary**).
To get a better understanding on how to correctly set up Sentinel, read
the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation first, as
failing to configure it correctly can lead to data loss or can bring your
whole cluster down, invalidating the failover effort.
## Recommended setup
For a minimal setup, you need to install the Linux package in `3`
**independent** machines, both with **Redis** and **Sentinel**:
- Redis Primary + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
If you are not sure or don't understand why and where the amount of nodes come
from, read [Redis setup overview](#redis-setup-overview) and
[Sentinel setup overview](#sentinel-setup-overview).
For a recommended setup that can resist more failures, you need to install
the Linux package in `5` **independent** machines, both with
**Redis** and **Sentinel**:
- Redis Primary + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
- Redis Replica + Sentinel
### Redis setup overview
You must have at least `3` Redis servers: `1` primary, `2` Replicas, and they
need to each be on independent machines.
You can have additional Redis nodes, that helps to survive a situation
where more nodes goes down. Whenever there is only `2` nodes online, a failover
is not initiated.
As an example, if you have `6` Redis nodes, a maximum of `3` can be
simultaneously down.
There are different requirements for Sentinel nodes.
If you host them in the same Redis machines, you may need to take
that restrictions into consideration when calculating the amount of
nodes to be provisioned. See [Sentinel setup overview](#sentinel-setup-overview)
documentation for more information.
All Redis nodes should be configured the same way and with similar server specs, as
in a failover situation, any **Replica** can be promoted as the new **Primary** by
the Sentinel servers.
The replication requires authentication, so you need to define a password to
protect all Redis nodes and the Sentinels. All of them share the same
password, and all instances must be able to talk to
each other over the network.
### Sentinel setup overview
Sentinels watch both other Sentinels and Redis nodes. Whenever a Sentinel
detects that a Redis node isn't responding, it announces the node's status to
the other Sentinels. The Sentinels have to reach a _quorum_ (the minimum amount
of Sentinels agreeing a node is down) to be able to start a failover.
Whenever the **quorum** is met, the **majority** of all known Sentinel nodes
need to be available and reachable, so that they can elect the Sentinel **leader**
who takes all the decisions to restore the service availability by:
- Promoting a new **Primary**
- Reconfiguring the other **Replicas** and make them point to the new **Primary**
- Announce the new **Primary** to every other Sentinel peer
- Reconfigure the old **Primary** and demote to **Replica** when it comes back online
You must have at least `3` Redis Sentinel servers, and they need to
be each in an independent machine (that are believed to fail independently),
ideally in different geographical areas.
You can configure them in the same machines where you've configured the other
Redis servers, but understand that if a whole node goes down, you loose both
a Sentinel and a Redis instance.
The number of sentinels should ideally always be an **odd** number, for the
consensus algorithm to be effective in the case of a failure.
In a `3` nodes topology, you can only afford `1` Sentinel node going down.
Whenever the **majority** of the Sentinels goes down, the network partition
protection prevents destructive actions and a failover **is not started**.
Here are some examples:
- With `5` or `6` sentinels, a maximum of `2` can go down for a failover begin.
- With `7` sentinels, a maximum of `3` nodes can go down.
The **Leader** election can sometimes fail the voting round when **consensus**
is not achieved. In that case,
a new attempt is made after the amount of time defined in
`sentinel['failover_timeout']` (in milliseconds).
{{< alert type="note" >}}
We can see where `sentinel['failover_timeout']` is defined later.
{{< /alert >}}
The `failover_timeout` variable has a lot of different use cases. According to
the official documentation:
- The time needed to re-start a failover after a previous failover was
already tried against the same primary by a given Sentinel, is two
times the failover timeout.
- The time needed for a replica replicating to a wrong primary according
to a Sentinel current configuration, to be forced to replicate
with the right primary, is exactly the failover timeout (counting since
the moment a Sentinel detected the misconfiguration).
- The time needed to cancel a failover that is already in progress but
did not produced any configuration change (REPLICAOF NO ONE yet not
acknowledged by the promoted replica).
- The maximum time a failover in progress waits for all the replicas to be
reconfigured as replicas of the new primary. However even after this time
the replicas are reconfigured by the Sentinels anyway, but not with
the exact parallel-syncs progression as specified.
## Configuring Redis
This is the section where we install and set up the new Redis instances.
It is assumed that you have installed GitLab and all its components from scratch.
If you already have Redis installed and running, read how to
[switch from a single-machine installation](#switching-from-an-existing-single-machine-installation).
{{< alert type="note" >}}
Redis nodes (both primary and replica) need the same password defined in
`redis['password']`. At any time during a failover the Sentinels can
reconfigure a node and change its status from primary to replica and vice versa.
{{< /alert >}}
### Requirements
The requirements for a Redis setup are the following:
1. Provision the minimum required number of instances as specified in the
[recommended setup](#recommended-setup) section.
1. We **Do not** recommend installing Redis or Redis Sentinel in the same machines your
GitLab application is running on as this weakens your HA configuration. You can however opt in to install Redis
and Sentinel in the same machine.
1. All Redis nodes must be able to talk to each other and accept incoming
connections over Redis (`6379`) and Sentinel (`26379`) ports (unless you
change the default ones).
1. The server that hosts the GitLab application must be able to access the
Redis nodes.
1. Protect the nodes from access from external networks ([Internet](https://gitlab.com/gitlab-org/gitlab-foss/uploads/c4cc8cd353604bd80315f9384035ff9e/The_Internet_IT_Crowd.png)), using
firewall.
### Switching from an existing single-machine installation
If you already have a single-machine GitLab install running, you need to
replicate from this machine first, before de-activating the Redis instance
inside it.
Your single-machine install is the initial **Primary**, and the `3` others
should be configured as **Replica** pointing to this machine.
After replication catches up, you need to stop services in the
single-machine install, to rotate the **Primary** to one of the new nodes.
Make the required changes in configuration and restart the new nodes again.
To disable Redis in the single install, edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['enable'] = false
```
If you fail to replicate first, you may loose data (unprocessed background jobs).
### Step 1. Configuring the primary Redis instance
1. SSH into the **Primary** Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want using **steps 1 and 2** from the GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
and type (Community, Enterprise editions) of your current install.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_master_role'
roles ['redis_master_role']
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really need to bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.0.0.1'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# Set up password authentication for Redis (use the same password in all nodes).
redis['password'] = 'redis-password-goes-here'
```
1. Only the primary GitLab application server should handle migrations. To
prevent database migrations from running on upgrade, add the following
configuration to your `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
{{< alert type="note" >}}
You can specify multiple roles like sentinel and Redis as:
`roles ['redis_sentinel_role', 'redis_master_role']`.
Read more about [roles](https://docs.gitlab.com/omnibus/roles/).
{{< /alert >}}
### Step 2. Configuring the replica Redis instances
1. SSH into the **replica** Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want using **steps 1 and 2** from the GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
and type (Community, Enterprise editions) of your current install.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
# Specify server role as 'redis_replica_role'
roles ['redis_replica_role']
# IP address pointing to a local IP that the other machines can reach to.
# You can also set bind to '0.0.0.0' which listen in all interfaces.
# If you really need to bind to an external accessible IP, make
# sure you add extra firewall rules to prevent unauthorized access.
redis['bind'] = '10.0.0.2'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# The same password for Redis authentication you set up for the primary node.
redis['password'] = 'redis-password-goes-here'
# The IP of the primary Redis node.
redis['master_ip'] = '10.0.0.1'
# Port of primary Redis server, uncomment to change to non default. Defaults
# to `6379`.
#redis['master_port'] = 6379
```
1. To prevent reconfigure from running automatically on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
1. Only the primary GitLab application server should handle migrations. To
prevent database migrations from running on upgrade, add the following
configuration to your `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other replica nodes.
{{< alert type="note" >}}
You can specify multiple roles like sentinel and Redis as:
`roles ['redis_sentinel_role', 'redis_master_role']`.
Read more about [roles](https://docs.gitlab.com/omnibus/roles/).
{{< /alert >}}
These values don't have to be changed again in `/etc/gitlab/gitlab.rb` after
a failover, as the nodes are managed by the Sentinels, and even after a
`gitlab-ctl reconfigure`, they get their configuration restored by
the same Sentinels.
### Step 3. Configuring the Redis Sentinel instances
{{< alert type="note" >}}
[Support for Sentinel password authentication](https://gitlab.com/gitlab-org/gitlab/-/issues/235938) was introduced in GitLab 16.1.
{{< /alert >}}
Now that the Redis servers are all set up, let's configure the Sentinel
servers.
If you are not sure if your Redis servers are working and replicating
correctly, read the [Troubleshooting Replication](troubleshooting.md#troubleshooting-redis-replication)
and fix it before proceeding with Sentinel setup.
You must have at least `3` Redis Sentinel servers, and they need to
be each in an independent machine. You can configure them in the same
machines where you've configured the other Redis servers.
With GitLab Enterprise Edition, you can use the Linux package to set up
multiple machines with the Sentinel daemon.
1. SSH into the server that hosts Redis Sentinel.
1. **You can omit this step if the Sentinels is hosted in the same node as
the other Redis instances**.
[Download and install](https://about.gitlab.com/install/) the
Linux Enterprise Edition package using **steps 1 and 2** from the
GitLab downloads page.
- Make sure you select the correct Linux package, with the same version
the GitLab application is running.
- Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents (if you are installing the
Sentinels in the same node as the other Redis instances, some values might
be duplicate below):
```ruby
roles ['redis_sentinel_role']
# Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
# The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'redis-password-goes-here'
# The IP of the primary Redis node.
redis['master_ip'] = '10.0.0.1'
# Define a port so Redis can listen for TCP requests which allows other
# machines to connect to it.
redis['port'] = 6379
# Port of primary Redis server, uncomment to change to non default. Defaults
# to `6379`.
#redis['master_port'] = 6379
## Configure Sentinel
sentinel['bind'] = '10.0.0.1'
## Optional password for Sentinel authentication. Defaults to no password required.
# sentinel['password'] = 'sentinel-password-goes here'
# Port that Sentinel listens on, uncomment to change to non default. Defaults
# to `26379`.
# sentinel['port'] = 26379
## Quorum must reflect the amount of voting sentinels it take to start a failover.
## Value must NOT be greater then the amount of sentinels.
##
## The quorum can be used to tune Sentinel in two ways:
## 1. If a the quorum is set to a value smaller than the majority of Sentinels
## we deploy, we are basically making Sentinel more sensible to primary failures,
## triggering a failover as soon as even just a minority of Sentinels is no longer
## able to talk with the primary.
## 1. If a quorum is set to a value greater than the majority of Sentinels, we are
## making Sentinel able to failover only when there are a very large number (larger
## than majority) of well connected Sentinels which agree about the primary being down.s
sentinel['quorum'] = 2
## Consider unresponsive server down after x amount of ms.
# sentinel['down_after_milliseconds'] = 10000
## Specifies the failover timeout in milliseconds. It is used in many ways:
##
## - The time needed to re-start a failover after a previous failover was
## already tried against the same primary by a given Sentinel, is two
## times the failover timeout.
##
## - The time needed for a replica replicating to a wrong primary according
## to a Sentinel current configuration, to be forced to replicate
## with the right primary, is exactly the failover timeout (counting since
## the moment a Sentinel detected the misconfiguration).
##
## - The time needed to cancel a failover that is already in progress but
## did not produced any configuration change (REPLICAOF NO ONE yet not
## acknowledged by the promoted replica).
##
## - The maximum time a failover in progress waits for all the replica to be
## reconfigured as replicas of the new primary. However even after this time
## the replicas are reconfigured by the Sentinels anyway, but not with
## the exact parallel-syncs progression as specified.
# sentinel['failover_timeout'] = 60000
```
1. To prevent database migrations from running on upgrade, run:
```shell
sudo touch /etc/gitlab/skip-auto-reconfigure
```
Only the primary GitLab application server should handle migrations.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Go through the steps again for all the other Sentinel nodes.
### Step 4. Configuring the GitLab application
The final part is to inform the main GitLab application server of the Redis
Sentinels servers and authentication credentials.
You can enable or disable Sentinel support at any time in new or existing
installations. From the GitLab application perspective, all it requires is
the correct credentials for the Sentinel nodes.
While it doesn't require a list of all Sentinel nodes, in case of a failure,
it needs to access at least one of the listed.
{{< alert type="note" >}}
The following steps should be performed in the GitLab application server
which ideally should not have Redis or Sentinels on it for a HA setup.
{{< /alert >}}
1. SSH into the server where the GitLab application is installed.
1. Edit `/etc/gitlab/gitlab.rb` and add/change the following lines:
```ruby
## Must be the same in every sentinel node
redis['master_name'] = 'gitlab-redis'
## The same password for Redis authentication you set up for the primary node.
redis['master_password'] = 'redis-password-goes-here'
## A list of sentinels with `host` and `port`
gitlab_rails['redis_sentinels'] = [
{'host' => '10.0.0.1', 'port' => 26379},
{'host' => '10.0.0.2', 'port' => 26379},
{'host' => '10.0.0.3', 'port' => 26379}
]
# gitlab_rails['redis_sentinels_password'] = 'sentinel-password-goes-here' # uncomment and set it to the same value as in sentinel['password']
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Step 5. Enable Monitoring
If you enable Monitoring, it must be enabled on **all** Redis servers.
1. Make sure to collect [`CONSUL_SERVER_NODES`](../postgresql/replication_and_failover.md#consul-information), which are the IP addresses or DNS records of the Consul server nodes, for the next step. Note they are presented as `Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z`
1. Create/edit `/etc/gitlab/gitlab.rb` and add the following configuration:
```ruby
# Enable service discovery for Prometheus
consul['enable'] = true
consul['monitoring_service_discovery'] = true
# Replace placeholders
# Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z
# with the addresses of the Consul server nodes
consul['configuration'] = {
retry_join: %w(Y.Y.Y.Y consul1.gitlab.example.com Z.Z.Z.Z),
}
# Set the network addresses that the exporters listen on
node_exporter['listen_address'] = '0.0.0.0:9100'
redis_exporter['listen_address'] = '0.0.0.0:9121'
```
1. Run `sudo gitlab-ctl reconfigure` to compile the configuration.
## Example of a minimal configuration with 1 primary, 2 replicas and 3 Sentinels
In this example we consider that all servers have an internal network
interface with IPs in the `10.0.0.x` range, and that they can connect
to each other using these IPs.
In a real world usage, you would also set up firewall rules to prevent
unauthorized access from other machines and block traffic from the
outside (Internet).
We use the same `3` nodes with **Redis** + **Sentinel** topology
discussed in [Redis setup overview](#redis-setup-overview) and
[Sentinel setup overview](#sentinel-setup-overview) documentation.
Here is a list and description of each **machine** and the assigned **IP**:
- `10.0.0.1`: Redis primary + Sentinel 1
- `10.0.0.2`: Redis Replica 1 + Sentinel 2
- `10.0.0.3`: Redis Replica 2 + Sentinel 3
- `10.0.0.4`: GitLab application
After the initial configuration, if a failover is initiated
by the Sentinel nodes, the Redis nodes are reconfigured and the **Primary**
changes permanently (including in `redis.conf`) from one node to the other,
until a new failover is initiated again.
The same thing happens with `sentinel.conf` that is overridden after the
initial execution, after any new sentinel node starts watching the **Primary**,
or a failover promotes a different **Primary** node.
### Example configuration for Redis primary and Sentinel 1
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_master_role']
redis['bind'] = '10.0.0.1'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
redis['master_password'] = 'redis-password-goes-here' # the same value defined in redis['password'] in the primary instance
redis['master_ip'] = '10.0.0.1' # ip of the initial primary redis instance
#redis['master_port'] = 6379 # port of the initial primary redis instance, uncomment to change to non default
sentinel['bind'] = '10.0.0.1'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for Redis replica 1 and Sentinel 2
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_replica_role']
redis['bind'] = '10.0.0.2'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_password'] = 'redis-password-goes-here'
redis['master_ip'] = '10.0.0.1' # IP of primary Redis server
#redis['master_port'] = 6379 # Port of primary Redis server, uncomment to change to non default
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
sentinel['bind'] = '10.0.0.2'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for Redis replica 2 and Sentinel 3
In `/etc/gitlab/gitlab.rb`:
```ruby
roles ['redis_sentinel_role', 'redis_replica_role']
redis['bind'] = '10.0.0.3'
redis['port'] = 6379
redis['password'] = 'redis-password-goes-here'
redis['master_password'] = 'redis-password-goes-here'
redis['master_ip'] = '10.0.0.1' # IP of primary Redis server
#redis['master_port'] = 6379 # Port of primary Redis server, uncomment to change to non default
redis['master_name'] = 'gitlab-redis' # must be the same in every sentinel node
sentinel['bind'] = '10.0.0.3'
# sentinel['password'] = 'sentinel-password-goes-here' # must be the same in every sentinel node, uncomment to set a password
# sentinel['port'] = 26379 # uncomment to change default port
sentinel['quorum'] = 2
# sentinel['down_after_milliseconds'] = 10000
# sentinel['failover_timeout'] = 60000
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
### Example configuration for the GitLab application
In `/etc/gitlab/gitlab.rb`:
```ruby
redis['master_name'] = 'gitlab-redis'
redis['master_password'] = 'redis-password-goes-here'
gitlab_rails['redis_sentinels'] = [
{'host' => '10.0.0.1', 'port' => 26379},
{'host' => '10.0.0.2', 'port' => 26379},
{'host' => '10.0.0.3', 'port' => 26379}
]
# gitlab_rails['redis_sentinels_password'] = 'sentinel-password-goes-here' # uncomment and set it to the same value as in sentinel['password']
```
[Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Advanced configuration
This section covers configuration options that go beyond the recommended and minimal configurations.
### Running multiple Redis clusters
The Linux package supports running separate Redis and Sentinel instances for different
persistence classes.
| Class | Purpose |
|--------------------|---------|
| `cache` | Store cached data. |
| `queues` | Store Sidekiq background jobs. |
| `shared_state` | Store session-related and other persistent data. |
| `actioncable` | Pub/Sub queue backend for ActionCable. |
| `trace_chunks` | Store [CI trace chunks](../cicd/job_logs.md#incremental-logging) data. |
| `rate_limiting` | Store [rate limiting](../settings/user_and_ip_rate_limits.md) state. |
| `sessions` | Store sessions. |
| `repository_cache` | Store cache data specific to repositories. |
To make this work with Sentinel:
1. [Configure the different Redis/Sentinels](#configuring-redis) instances based on your needs.
1. For each Rails application instance, edit its `/etc/gitlab/gitlab.rb` file:
```ruby
gitlab_rails['redis_cache_instance'] = REDIS_CACHE_URL
gitlab_rails['redis_queues_instance'] = REDIS_QUEUES_URL
gitlab_rails['redis_shared_state_instance'] = REDIS_SHARED_STATE_URL
gitlab_rails['redis_actioncable_instance'] = REDIS_ACTIONCABLE_URL
gitlab_rails['redis_trace_chunks_instance'] = REDIS_TRACE_CHUNKS_URL
gitlab_rails['redis_rate_limiting_instance'] = REDIS_RATE_LIMITING_URL
gitlab_rails['redis_sessions_instance'] = REDIS_SESSIONS_URL
gitlab_rails['redis_repository_cache_instance'] = REDIS_REPOSITORY_CACHE_URL
# Configure the Sentinels
gitlab_rails['redis_cache_sentinels'] = [
{ host: REDIS_CACHE_SENTINEL_HOST, port: 26379 },
{ host: REDIS_CACHE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_queues_sentinels'] = [
{ host: REDIS_QUEUES_SENTINEL_HOST, port: 26379 },
{ host: REDIS_QUEUES_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_shared_state_sentinels'] = [
{ host: SHARED_STATE_SENTINEL_HOST, port: 26379 },
{ host: SHARED_STATE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_actioncable_sentinels'] = [
{ host: ACTIONCABLE_SENTINEL_HOST, port: 26379 },
{ host: ACTIONCABLE_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_trace_chunks_sentinels'] = [
{ host: TRACE_CHUNKS_SENTINEL_HOST, port: 26379 },
{ host: TRACE_CHUNKS_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_rate_limiting_sentinels'] = [
{ host: RATE_LIMITING_SENTINEL_HOST, port: 26379 },
{ host: RATE_LIMITING_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_sessions_sentinels'] = [
{ host: SESSIONS_SENTINEL_HOST, port: 26379 },
{ host: SESSIONS_SENTINEL_HOST2, port: 26379 }
]
gitlab_rails['redis_repository_cache_sentinels'] = [
{ host: REPOSITORY_CACHE_SENTINEL_HOST, port: 26379 },
{ host: REPOSITORY_CACHE_SENTINEL_HOST2, port: 26379 }
]
# gitlab_rails['redis_cache_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_queues_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_shared_state_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_actioncable_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_trace_chunks_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_rate_limiting_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_sessions_sentinels_password'] = 'sentinel-password-goes-here'
# gitlab_rails['redis_repository_cache_sentinels_password'] = 'sentinel-password-goes-here'
```
- Redis URLs should be in the format: `redis://:PASSWORD@SENTINEL_PRIMARY_NAME`, where:
- `PASSWORD` is the plaintext password for the Redis instance.
- `SENTINEL_PRIMARY_NAME` is the Sentinel primary name set with `redis['master_name']`,
for example `gitlab-redis-cache`.
1. Save the file and reconfigure GitLab for the change to take effect:
```shell
sudo gitlab-ctl reconfigure
```
{{< alert type="note" >}}
For each persistence class, GitLab defaults to using the
configuration specified in `gitlab_rails['redis_sentinels']` unless
overridden by the previously described settings.
{{< /alert >}}
### Control running services
In the previous example, we've used `redis_sentinel_role` and
`redis_master_role` which simplifies the amount of configuration changes.
If you want more control, here is what each one sets for you automatically
when enabled:
```ruby
## Redis Sentinel Role
redis_sentinel_role['enable'] = true
# When Sentinel Role is enabled, the following services are also enabled
sentinel['enable'] = true
# The following services are disabled
redis['enable'] = false
bootstrap['enable'] = false
nginx['enable'] = false
postgresql['enable'] = false
gitlab_rails['enable'] = false
mailroom['enable'] = false
-------
## Redis primary/replica Role
redis_master_role['enable'] = true # enable only one of them
redis_replica_role['enable'] = true # enable only one of them
# When Redis primary or Replica role are enabled, the following services are
# enabled/disabled. If Redis and Sentinel roles are combined, both
# services are enabled.
# The following services are disabled
sentinel['enable'] = false
bootstrap['enable'] = false
nginx['enable'] = false
postgresql['enable'] = false
gitlab_rails['enable'] = false
mailroom['enable'] = false
# For Redis Replica role, also change this setting from default 'true' to 'false':
redis['master'] = false
```
You can find the relevant attributes defined in [`gitlab_rails.rb`](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-cookbooks/gitlab/libraries/gitlab_rails.rb).
### Control startup behavior
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6646) in GitLab 15.10.
{{< /history >}}
To prevent the bundled Redis service from starting at boot or restarting after changing its configuration:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['start_down'] = true
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
If you need to test a new replica node, you may set `start_down` to
`true` and manually start the node. After the new replica node is confirmed
working in the Redis cluster, set `start_down` to `false` and reconfigure GitLab
to ensure the node starts and restarts as expected during operation.
### Control replica configuration
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6646) in GitLab 15.10.
{{< /history >}}
To prevent the `replicaof` line from rendering in the Redis configuration file:
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
redis['set_replicaof'] = false
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
This setting can be used to prevent replication of a Redis node independently of other Redis settings.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
## Further reading
Read more:
1. [Reference architectures](../reference_architectures/_index.md)
1. [Configure the database](../postgresql/replication_and_failover.md)
1. [Configure NFS](../nfs.md)
1. [Configure the load balancers](../load_balancer.md)
|
https://docs.gitlab.com/administration/redis
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/_index.md
|
2025-08-13
|
doc/administration/redis
|
[
"doc",
"administration",
"redis"
] |
_index.md
|
Data access
|
Durability
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configuring Redis for scaling
|
Configure Redis for scaling.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Based on your infrastructure setup and how you have installed GitLab, there are
multiple ways to configure Redis.
You can choose to install and manage Redis and Sentinel yourself, use a hosted
cloud solution, or you can use the ones that come bundled with the Linux
packages so you can only focus on configuration. Pick the one that suits your needs.
## Redis replication and failover using the Linux package
This setup is for when you have installed GitLab using the
[Linux **Enterprise Edition** (EE) package](https://about.gitlab.com/install/?version=ee).
Both Redis and Sentinel are bundled in the package, so you can use it to set up the whole Redis infrastructure (primary,
replica and sentinel).
For more information, see [Redis replication and failover with the Linux package](replication_and_failover.md).
## Redis replication and failover using the non-bundled Redis
This setup is for when you have either a [Linux package](https://about.gitlab.com/install/) installation or a
[self-compiled installation](../../install/self_compiled/_index.md), but you want to use your own external Redis and Sentinel
servers.
For more information, see [Redis replication and failover providing your own instance](replication_and_failover_external.md).
## Standalone Redis using the Linux package
This setup is for when you have installed the
[Linux **Community Edition** (CE) package](https://about.gitlab.com/install/?version=ce)
to use the bundled Redis, so you can use the package with only the Redis service enabled.
For more information, see [Standalone Redis using the Linux package](standalone.md).
|
---
stage: Data access
group: Durability
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Configuring Redis for scaling
description: Configure Redis for scaling.
breadcrumbs:
- doc
- administration
- redis
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Based on your infrastructure setup and how you have installed GitLab, there are
multiple ways to configure Redis.
You can choose to install and manage Redis and Sentinel yourself, use a hosted
cloud solution, or you can use the ones that come bundled with the Linux
packages so you can only focus on configuration. Pick the one that suits your needs.
## Redis replication and failover using the Linux package
This setup is for when you have installed GitLab using the
[Linux **Enterprise Edition** (EE) package](https://about.gitlab.com/install/?version=ee).
Both Redis and Sentinel are bundled in the package, so you can use it to set up the whole Redis infrastructure (primary,
replica and sentinel).
For more information, see [Redis replication and failover with the Linux package](replication_and_failover.md).
## Redis replication and failover using the non-bundled Redis
This setup is for when you have either a [Linux package](https://about.gitlab.com/install/) installation or a
[self-compiled installation](../../install/self_compiled/_index.md), but you want to use your own external Redis and Sentinel
servers.
For more information, see [Redis replication and failover providing your own instance](replication_and_failover_external.md).
## Standalone Redis using the Linux package
This setup is for when you have installed the
[Linux **Community Edition** (CE) package](https://about.gitlab.com/install/?version=ce)
to use the bundled Redis, so you can use the package with only the Redis service enabled.
For more information, see [Standalone Redis using the Linux package](standalone.md).
|
https://docs.gitlab.com/administration/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/troubleshooting.md
|
2025-08-13
|
doc/administration/redis
|
[
"doc",
"administration",
"redis"
] |
troubleshooting.md
|
Data access
|
Durability
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting Redis
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
There are a lot of moving parts that must be taken care carefully
in order for the HA setup to work as expected.
Before proceeding with the troubleshooting below, check your firewall rules:
- Redis machines
- Accept TCP connection in `6379`
- Connect to the other Redis machines via TCP in `6379`
- Sentinel machines
- Accept TCP connection in `26379`
- Connect to other Sentinel machines via TCP in `26379`
- Connect to the Redis machines via TCP in `6379`
## Basic Redis activity check
Start Redis troubleshooting with a basic Redis activity check:
1. Open a terminal on your GitLab server.
1. Run `gitlab-redis-cli --stat` and observe the output while it runs.
1. Go to your GitLab UI and browse to a handful of pages. Any page works, such as
group or project overviews, issues, or files in repositories.
1. Check the `stat` output again and verify that the values for `keys`, `clients`,
`requests`, and `connections` increases as you browse. If the numbers go up,
basic Redis functionality is working and GitLab can connect to it.
## Troubleshooting Redis replication
You can check if everything is correct by connecting to each server using
`redis-cli` application, and sending the `info replication` command as below.
```shell
/opt/gitlab/embedded/bin/redis-cli -h <redis-host-or-ip> -a '<redis-password>' info replication
```
When connected to a `Primary` Redis, you see the number of connected
`replicas`, and a list of each with connection details:
```plaintext
# Replication
role:master
connected_replicas:1
replica0:ip=10.133.5.21,port=6379,state=online,offset=208037514,lag=1
master_repl_offset:208037658
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:206989083
repl_backlog_histlen:1048576
```
When it's a `replica`, you see details of the primary connection and if
its `up` or `down`:
```plaintext
# Replication
role:replica
master_host:10.133.1.58
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
replica_repl_offset:208096498
replica_priority:100
replica_read_only:1
connected_replicas:0
master_repl_offset:0
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
```
## High CPU usage on Redis instance
By default, GitLab uses over 600 Sidekiq queues, each stored as a Redis list. Each Sidekiq thread issues a `BRPOP` command with all the queues listed in a long string.
Redis CPU utilization grows as the number of queues and the rate of `BRPOP` calls increases. If your GitLab instance has many Sidekiq processes, this can cause Redis
CPU utilization to approach 100%. High CPU utilization degrades GitLab performance significantly.
To reduce CPU usage on Redis caused by Sidekiq you can both:
- Use [routing rules](../sidekiq/processing_specific_job_classes.md#routing-rules) to reduce the number of Sidekiq queues.
- If you are using GitLab 16.6 and earlier, increase the [`SIDEKIQ_SEMI_RELIABLE_FETCH_TIMEOUT` environment variable](../environment_variables.md) to improve CPU usage on Redis.
On GitLab 16.7 and later, the [default value is 5](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/139583), which should be sufficient.
The `SIDEKIQ_SEMI_RELIABLE_FETCH_TIMEOUT` option reduces the overhead that tearing down and connecting causes, but increase the shutdown delay of Sidekiq.
## Troubleshooting Sentinel
If you get an error like: `Redis::CannotConnectError: No sentinels available.`,
there may be something wrong with your configuration files or it can be related
to [this issue](https://github.com/redis/redis-rb/issues/531).
You must make sure you are defining the same value in `redis['master_name']`
and `redis['master_password']` as you defined for your sentinel node.
The way the Redis connector `redis-rb` works with sentinel is a bit
non-intuitive. We try to hide the complexity in the Linux package, but it still requires
a few extra configurations.
To make sure your configuration is correct:
1. SSH into your GitLab application server
1. Enter the Rails console:
```shell
# For Omnibus installations
sudo gitlab-rails console
# For source installations
sudo -u git rails console -e production
```
1. Run in the console:
```ruby
redis = Gitlab::Redis::SharedState.redis
redis.info
```
Keep this screen open, and proceed to trigger a failover as described below.
1. To trigger a failover on the primary Redis, SSH into the Redis server and run:
```shell
# port must match your primary redis port, and the sleep time must be a few seconds bigger than defined one
redis-cli -h localhost -p 6379 DEBUG sleep 20
```
{{< alert type="warning" >}}
This action affects services, and takes the instance down for up to 20 seconds. If successful,
it should recover after that.
{{< /alert >}}
1. Then back in the Rails console from the first step, run:
```ruby
redis.info
```
You should see a different port after a few seconds delay
(the failover/reconnect time).
## Troubleshooting a non-bundled Redis with a self-compiled installation
If you get an error in GitLab like `Redis::CannotConnectError: No sentinels available.`,
there may be something wrong with your configuration files or it can be related
to [this upstream issue](https://github.com/redis/redis-rb/issues/531).
You must make sure that `resque.yml` and `sentinel.conf` are configured correctly,
otherwise `redis-rb` does not work properly.
The `master-group-name` (`gitlab-redis`) defined in (`sentinel.conf`)
**must** be used as the hostname in GitLab (`resque.yml`):
```conf
# sentinel.conf:
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel config-epoch gitlab-redis 0
sentinel leader-epoch gitlab-redis 0
```
```yaml
# resque.yaml
production:
url: redis://:myredispassword@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
When in doubt, read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation.
|
---
stage: Data access
group: Durability
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting Redis
breadcrumbs:
- doc
- administration
- redis
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
There are a lot of moving parts that must be taken care carefully
in order for the HA setup to work as expected.
Before proceeding with the troubleshooting below, check your firewall rules:
- Redis machines
- Accept TCP connection in `6379`
- Connect to the other Redis machines via TCP in `6379`
- Sentinel machines
- Accept TCP connection in `26379`
- Connect to other Sentinel machines via TCP in `26379`
- Connect to the Redis machines via TCP in `6379`
## Basic Redis activity check
Start Redis troubleshooting with a basic Redis activity check:
1. Open a terminal on your GitLab server.
1. Run `gitlab-redis-cli --stat` and observe the output while it runs.
1. Go to your GitLab UI and browse to a handful of pages. Any page works, such as
group or project overviews, issues, or files in repositories.
1. Check the `stat` output again and verify that the values for `keys`, `clients`,
`requests`, and `connections` increases as you browse. If the numbers go up,
basic Redis functionality is working and GitLab can connect to it.
## Troubleshooting Redis replication
You can check if everything is correct by connecting to each server using
`redis-cli` application, and sending the `info replication` command as below.
```shell
/opt/gitlab/embedded/bin/redis-cli -h <redis-host-or-ip> -a '<redis-password>' info replication
```
When connected to a `Primary` Redis, you see the number of connected
`replicas`, and a list of each with connection details:
```plaintext
# Replication
role:master
connected_replicas:1
replica0:ip=10.133.5.21,port=6379,state=online,offset=208037514,lag=1
master_repl_offset:208037658
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:206989083
repl_backlog_histlen:1048576
```
When it's a `replica`, you see details of the primary connection and if
its `up` or `down`:
```plaintext
# Replication
role:replica
master_host:10.133.1.58
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
replica_repl_offset:208096498
replica_priority:100
replica_read_only:1
connected_replicas:0
master_repl_offset:0
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
```
## High CPU usage on Redis instance
By default, GitLab uses over 600 Sidekiq queues, each stored as a Redis list. Each Sidekiq thread issues a `BRPOP` command with all the queues listed in a long string.
Redis CPU utilization grows as the number of queues and the rate of `BRPOP` calls increases. If your GitLab instance has many Sidekiq processes, this can cause Redis
CPU utilization to approach 100%. High CPU utilization degrades GitLab performance significantly.
To reduce CPU usage on Redis caused by Sidekiq you can both:
- Use [routing rules](../sidekiq/processing_specific_job_classes.md#routing-rules) to reduce the number of Sidekiq queues.
- If you are using GitLab 16.6 and earlier, increase the [`SIDEKIQ_SEMI_RELIABLE_FETCH_TIMEOUT` environment variable](../environment_variables.md) to improve CPU usage on Redis.
On GitLab 16.7 and later, the [default value is 5](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/139583), which should be sufficient.
The `SIDEKIQ_SEMI_RELIABLE_FETCH_TIMEOUT` option reduces the overhead that tearing down and connecting causes, but increase the shutdown delay of Sidekiq.
## Troubleshooting Sentinel
If you get an error like: `Redis::CannotConnectError: No sentinels available.`,
there may be something wrong with your configuration files or it can be related
to [this issue](https://github.com/redis/redis-rb/issues/531).
You must make sure you are defining the same value in `redis['master_name']`
and `redis['master_password']` as you defined for your sentinel node.
The way the Redis connector `redis-rb` works with sentinel is a bit
non-intuitive. We try to hide the complexity in the Linux package, but it still requires
a few extra configurations.
To make sure your configuration is correct:
1. SSH into your GitLab application server
1. Enter the Rails console:
```shell
# For Omnibus installations
sudo gitlab-rails console
# For source installations
sudo -u git rails console -e production
```
1. Run in the console:
```ruby
redis = Gitlab::Redis::SharedState.redis
redis.info
```
Keep this screen open, and proceed to trigger a failover as described below.
1. To trigger a failover on the primary Redis, SSH into the Redis server and run:
```shell
# port must match your primary redis port, and the sleep time must be a few seconds bigger than defined one
redis-cli -h localhost -p 6379 DEBUG sleep 20
```
{{< alert type="warning" >}}
This action affects services, and takes the instance down for up to 20 seconds. If successful,
it should recover after that.
{{< /alert >}}
1. Then back in the Rails console from the first step, run:
```ruby
redis.info
```
You should see a different port after a few seconds delay
(the failover/reconnect time).
## Troubleshooting a non-bundled Redis with a self-compiled installation
If you get an error in GitLab like `Redis::CannotConnectError: No sentinels available.`,
there may be something wrong with your configuration files or it can be related
to [this upstream issue](https://github.com/redis/redis-rb/issues/531).
You must make sure that `resque.yml` and `sentinel.conf` are configured correctly,
otherwise `redis-rb` does not work properly.
The `master-group-name` (`gitlab-redis`) defined in (`sentinel.conf`)
**must** be used as the hostname in GitLab (`resque.yml`):
```conf
# sentinel.conf:
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel config-epoch gitlab-redis 0
sentinel leader-epoch gitlab-redis 0
```
```yaml
# resque.yaml
production:
url: redis://:myredispassword@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
When in doubt, read the [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/) documentation.
|
https://docs.gitlab.com/administration/replication_and_failover_external
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/replication_and_failover_external.md
|
2025-08-13
|
doc/administration/redis
|
[
"doc",
"administration",
"redis"
] |
replication_and_failover_external.md
|
Data access
|
Durability
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Redis replication and failover providing your own instance
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you're hosting GitLab on a cloud provider, you can optionally use a managed
service for Redis. For example, AWS offers ElastiCache that runs Redis.
Alternatively, you may opt to manage your own Redis instance separate from the
Linux package.
## Requirements
The following are the requirements for providing your own Redis instance:
- Find the minimum Redis version that is required in the
[requirements page](../../install/requirements.md).
- Standalone Redis or Redis high availability with Sentinel are supported. Redis
Cluster is not supported.
- Managed Redis from cloud providers such as AWS ElastiCache works fine. If these
services support high availability, be sure it is **not** the Redis Cluster type.
Note the Redis node's IP address or hostname, port, and password (if required).
## Redis as a managed service in a cloud provider
1. Set up Redis according to the [requirements](#requirements).
1. Configure the GitLab application servers with the appropriate connection details
for your external Redis service in your `/etc/gitlab/gitlab.rb` file:
When using a single Redis instance:
```ruby
redis['enable'] = false
gitlab_rails['redis_host'] = '<redis_instance_url>'
gitlab_rails['redis_port'] = '<redis_instance_port>'
# Required if Redis authentication is configured on the Redis node
gitlab_rails['redis_password'] = '<redis_password>'
# Set to true if instance is using Redis SSL
gitlab_rails['redis_ssl'] = true
```
When using separate Redis Cache and Persistent instances:
```ruby
redis['enable'] = false
# Default Redis connection
gitlab_rails['redis_host'] = '<redis_persistent_instance_url>'
gitlab_rails['redis_port'] = '<redis_persistent_instance_port>'
gitlab_rails['redis_password'] = '<redis_persistent_password>'
# Set to true if instance is using Redis SSL
gitlab_rails['redis_ssl'] = true
# Redis Cache connection
# Replace `redis://` with `rediss://` if using SSL
gitlab_rails['redis_cache_instance'] = 'redis://:<redis_cache_password>@<redis_cache_instance_url>:<redis_cache_instance_port>'
```
1. Reconfigure for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
### Setting the eviction policy
When running a single Redis instance the eviction policy should be set to `noeviction`.
If you are running separate Redis Cache and Persistent instances, Cache should be configured as a [Least Recently Used cache](https://redis.io/docs/latest/operate/rs/databases/memory-performance/eviction-policy/) (LRU) with `allkeys-lru` while Persistent should be set to `noeviction`.
Configuring this depends on the cloud provider or service, but generally the following settings and values configure a cache:
- `maxmemory-policy` = `allkeys-lru`
- `maxmemory-samples` = `5`
## Redis replication and failover with your own Redis servers
This is the documentation for configuring a scalable Redis setup when
you have installed Redis all by yourself and not using the bundled one that
comes with the Linux packages, although using the Linux packages is
highly recommend as we optimize them specifically for GitLab, and we take
care of upgrading Redis to the latest supported version.
Note also that you may elect to override all references to
`/home/git/gitlab/config/resque.yml` in accordance with the advanced Redis
settings outlined in
[Configuration Files Documentation](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/README.md).
We cannot stress enough the importance of reading the
[replication and failover](replication_and_failover.md) documentation of the
Linux package Redis HA because it provides some invaluable information to the configuration
of Redis. Read it before going forward with this guide.
Before proceeding on setting up the new Redis instances, here are some
requirements:
- All Redis servers in this guide must be configured to use a TCP connection
instead of a socket. To configure Redis to use TCP connections you need to
define both `bind` and `port` in the Redis configuration file. You can bind to all
interfaces (`0.0.0.0`) or specify the IP of the desired interface
(for example, one from an internal network).
- Since Redis 3.2, you must define a password to receive external connections
(`requirepass`).
- If you are using Redis with Sentinel, you also need to define the same
password for the replica password definition (`masterauth`) in the same instance.
In addition, read the prerequisites as described in
[Redis replication and failover with the Linux package](replication_and_failover.md#requirements).
### Step 1. Configuring the primary Redis instance
Assuming that the Redis primary instance IP is `10.0.0.1`:
1. [Install Redis](../../install/self_compiled/_index.md#8-redis).
1. Edit `/etc/redis/redis.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.1
## Define a `port` to force redis to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 6379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
```
1. Restart the Redis service for the changes to take effect.
### Step 2. Configuring the replica Redis instances
Assuming that the Redis replica instance IP is `10.0.0.2`:
1. [Install Redis](../../install/self_compiled/_index.md#8-redis).
1. Edit `/etc/redis/redis.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.2
## Define a `port` to force redis to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 6379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
## Define `replicaof` pointing to the Redis primary instance with IP and port.
replicaof 10.0.0.1 6379
```
1. Restart the Redis service for the changes to take effect.
1. Go through the steps again for all the other replica nodes.
### Step 3. Configuring the Redis Sentinel instances
Sentinel is a special type of Redis server. It inherits most of the basic
configuration options you can define in `redis.conf`, with specific ones
starting with `sentinel` prefix.
Assuming that the Redis Sentinel is installed on the same instance as Redis
primary with IP `10.0.0.1` (some settings might overlap with the primary):
1. [Install Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/).
1. Edit `/etc/redis/sentinel.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.1
## Define a `port` to force Sentinel to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 26379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
## Define with `sentinel auth-pass` the same shared password you have
## defined for both Redis primary and replicas instances.
sentinel auth-pass gitlab-redis redis-password-goes-here
## Define with `sentinel monitor` the IP and port of the Redis
## primary node, and the quorum required to start a failover.
sentinel monitor gitlab-redis 10.0.0.1 6379 2
## Define with `sentinel down-after-milliseconds` the time in `ms`
## that an unresponsive server is considered down.
sentinel down-after-milliseconds gitlab-redis 10000
## Define a value for `sentinel failover_timeout` in `ms`. This has multiple
## meanings:
##
## * The time needed to re-start a failover after a previous failover was
## already tried against the same primary by a given Sentinel, is two
## times the failover timeout.
##
## * The time needed for a replica replicating to a wrong primary according
## to a Sentinel current configuration, to be forced to replicate
## with the right primary, is exactly the failover timeout (counting since
## the moment a Sentinel detected the misconfiguration).
##
## * The time needed to cancel a failover that is already in progress but
## did not produced any configuration change (REPLICAOF NO ONE yet not
## acknowledged by the promoted replica).
##
## * The maximum time a failover in progress waits for all the replicas to be
## reconfigured as replicas of the new primary. However even after this time
## the replicas are reconfigured by the Sentinels anyway, but not with
## the exact parallel-syncs progression as specified.
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
1. Go through the steps again for all the other Sentinel nodes.
### Step 4. Configuring the GitLab application
You can enable or disable Sentinel support at any time in new or existing
installations. From the GitLab application perspective, all it requires is
the correct credentials for the Sentinel nodes.
While it doesn't require a list of all Sentinel nodes, in case of a failure,
it needs to access at least one of listed ones.
The following steps should be performed in the GitLab application server
which ideally should not have Redis or Sentinels in the same machine:
1. Edit `/home/git/gitlab/config/resque.yml` following the example in
[`resque.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/resque.yml.example), and uncomment the Sentinel lines, pointing to
the correct server credentials:
```yaml
# resque.yaml
production:
url: redis://:redi-password-goes-here@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Example of minimal configuration with 1 primary, 2 replicas and 3 sentinels
In this example we consider that all servers have an internal network
interface with IPs in the `10.0.0.x` range, and that they can connect
to each other using these IPs.
In a real world usage, you would also set up firewall rules to prevent
unauthorized access from other machines, and block traffic from the
outside ([Internet](https://gitlab.com/gitlab-org/gitlab-foss/uploads/c4cc8cd353604bd80315f9384035ff9e/The_Internet_IT_Crowd.png)).
For this example, **Sentinel 1** is configured in the same machine as the
**Redis Primary**, **Sentinel 2** in the same machine as **Replica 1**, and
**Sentinel 3** in the same machine as **Replica 2**.
Here is a list and description of each **machine** and the assigned **IP**:
- `10.0.0.1`: Redis Primary + Sentinel 1
- `10.0.0.2`: Redis Replica 1 + Sentinel 2
- `10.0.0.3`: Redis Replica 2 + Sentinel 3
- `10.0.0.4`: GitLab application
After the initial configuration, if a failover is initiated
by the Sentinel nodes, the Redis nodes are reconfigured and the **Primary**
changes permanently (including in `redis.conf`) from one node to the other,
until a new failover is initiated again.
The same thing happens with `sentinel.conf` that is overridden after the
initial execution, after any new sentinel node starts watching the **Primary**,
or a failover promotes a different **Primary** node.
### Example configuration for Redis primary and Sentinel 1
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.1
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.1
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration for Redis replica 1 and Sentinel 2
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.2
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
replicaof 10.0.0.1 6379
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.2
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration for Redis replica 2 and Sentinel 3
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.3
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
replicaof 10.0.0.1 6379
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.3
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration of the GitLab application
1. Edit `/home/git/gitlab/config/resque.yml`:
```yaml
production:
url: redis://:redis-password-goes-here@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
|
---
stage: Data access
group: Durability
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Redis replication and failover providing your own instance
breadcrumbs:
- doc
- administration
- redis
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
If you're hosting GitLab on a cloud provider, you can optionally use a managed
service for Redis. For example, AWS offers ElastiCache that runs Redis.
Alternatively, you may opt to manage your own Redis instance separate from the
Linux package.
## Requirements
The following are the requirements for providing your own Redis instance:
- Find the minimum Redis version that is required in the
[requirements page](../../install/requirements.md).
- Standalone Redis or Redis high availability with Sentinel are supported. Redis
Cluster is not supported.
- Managed Redis from cloud providers such as AWS ElastiCache works fine. If these
services support high availability, be sure it is **not** the Redis Cluster type.
Note the Redis node's IP address or hostname, port, and password (if required).
## Redis as a managed service in a cloud provider
1. Set up Redis according to the [requirements](#requirements).
1. Configure the GitLab application servers with the appropriate connection details
for your external Redis service in your `/etc/gitlab/gitlab.rb` file:
When using a single Redis instance:
```ruby
redis['enable'] = false
gitlab_rails['redis_host'] = '<redis_instance_url>'
gitlab_rails['redis_port'] = '<redis_instance_port>'
# Required if Redis authentication is configured on the Redis node
gitlab_rails['redis_password'] = '<redis_password>'
# Set to true if instance is using Redis SSL
gitlab_rails['redis_ssl'] = true
```
When using separate Redis Cache and Persistent instances:
```ruby
redis['enable'] = false
# Default Redis connection
gitlab_rails['redis_host'] = '<redis_persistent_instance_url>'
gitlab_rails['redis_port'] = '<redis_persistent_instance_port>'
gitlab_rails['redis_password'] = '<redis_persistent_password>'
# Set to true if instance is using Redis SSL
gitlab_rails['redis_ssl'] = true
# Redis Cache connection
# Replace `redis://` with `rediss://` if using SSL
gitlab_rails['redis_cache_instance'] = 'redis://:<redis_cache_password>@<redis_cache_instance_url>:<redis_cache_instance_port>'
```
1. Reconfigure for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
### Setting the eviction policy
When running a single Redis instance the eviction policy should be set to `noeviction`.
If you are running separate Redis Cache and Persistent instances, Cache should be configured as a [Least Recently Used cache](https://redis.io/docs/latest/operate/rs/databases/memory-performance/eviction-policy/) (LRU) with `allkeys-lru` while Persistent should be set to `noeviction`.
Configuring this depends on the cloud provider or service, but generally the following settings and values configure a cache:
- `maxmemory-policy` = `allkeys-lru`
- `maxmemory-samples` = `5`
## Redis replication and failover with your own Redis servers
This is the documentation for configuring a scalable Redis setup when
you have installed Redis all by yourself and not using the bundled one that
comes with the Linux packages, although using the Linux packages is
highly recommend as we optimize them specifically for GitLab, and we take
care of upgrading Redis to the latest supported version.
Note also that you may elect to override all references to
`/home/git/gitlab/config/resque.yml` in accordance with the advanced Redis
settings outlined in
[Configuration Files Documentation](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/README.md).
We cannot stress enough the importance of reading the
[replication and failover](replication_and_failover.md) documentation of the
Linux package Redis HA because it provides some invaluable information to the configuration
of Redis. Read it before going forward with this guide.
Before proceeding on setting up the new Redis instances, here are some
requirements:
- All Redis servers in this guide must be configured to use a TCP connection
instead of a socket. To configure Redis to use TCP connections you need to
define both `bind` and `port` in the Redis configuration file. You can bind to all
interfaces (`0.0.0.0`) or specify the IP of the desired interface
(for example, one from an internal network).
- Since Redis 3.2, you must define a password to receive external connections
(`requirepass`).
- If you are using Redis with Sentinel, you also need to define the same
password for the replica password definition (`masterauth`) in the same instance.
In addition, read the prerequisites as described in
[Redis replication and failover with the Linux package](replication_and_failover.md#requirements).
### Step 1. Configuring the primary Redis instance
Assuming that the Redis primary instance IP is `10.0.0.1`:
1. [Install Redis](../../install/self_compiled/_index.md#8-redis).
1. Edit `/etc/redis/redis.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.1
## Define a `port` to force redis to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 6379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
```
1. Restart the Redis service for the changes to take effect.
### Step 2. Configuring the replica Redis instances
Assuming that the Redis replica instance IP is `10.0.0.2`:
1. [Install Redis](../../install/self_compiled/_index.md#8-redis).
1. Edit `/etc/redis/redis.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.2
## Define a `port` to force redis to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 6379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
## Define `replicaof` pointing to the Redis primary instance with IP and port.
replicaof 10.0.0.1 6379
```
1. Restart the Redis service for the changes to take effect.
1. Go through the steps again for all the other replica nodes.
### Step 3. Configuring the Redis Sentinel instances
Sentinel is a special type of Redis server. It inherits most of the basic
configuration options you can define in `redis.conf`, with specific ones
starting with `sentinel` prefix.
Assuming that the Redis Sentinel is installed on the same instance as Redis
primary with IP `10.0.0.1` (some settings might overlap with the primary):
1. [Install Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/).
1. Edit `/etc/redis/sentinel.conf`:
```conf
## Define a `bind` address pointing to a local IP that your other machines
## can reach you. If you really need to bind to an external accessible IP, make
## sure you add extra firewall rules to prevent unauthorized access:
bind 10.0.0.1
## Define a `port` to force Sentinel to listen on TCP so other machines can
## connect to it (default port is `6379`).
port 26379
## Set up password authentication (use the same password in all nodes).
## The password should be defined equal for both `requirepass` and `masterauth`
## when setting up Redis to use with Sentinel.
requirepass redis-password-goes-here
masterauth redis-password-goes-here
## Define with `sentinel auth-pass` the same shared password you have
## defined for both Redis primary and replicas instances.
sentinel auth-pass gitlab-redis redis-password-goes-here
## Define with `sentinel monitor` the IP and port of the Redis
## primary node, and the quorum required to start a failover.
sentinel monitor gitlab-redis 10.0.0.1 6379 2
## Define with `sentinel down-after-milliseconds` the time in `ms`
## that an unresponsive server is considered down.
sentinel down-after-milliseconds gitlab-redis 10000
## Define a value for `sentinel failover_timeout` in `ms`. This has multiple
## meanings:
##
## * The time needed to re-start a failover after a previous failover was
## already tried against the same primary by a given Sentinel, is two
## times the failover timeout.
##
## * The time needed for a replica replicating to a wrong primary according
## to a Sentinel current configuration, to be forced to replicate
## with the right primary, is exactly the failover timeout (counting since
## the moment a Sentinel detected the misconfiguration).
##
## * The time needed to cancel a failover that is already in progress but
## did not produced any configuration change (REPLICAOF NO ONE yet not
## acknowledged by the promoted replica).
##
## * The maximum time a failover in progress waits for all the replicas to be
## reconfigured as replicas of the new primary. However even after this time
## the replicas are reconfigured by the Sentinels anyway, but not with
## the exact parallel-syncs progression as specified.
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
1. Go through the steps again for all the other Sentinel nodes.
### Step 4. Configuring the GitLab application
You can enable or disable Sentinel support at any time in new or existing
installations. From the GitLab application perspective, all it requires is
the correct credentials for the Sentinel nodes.
While it doesn't require a list of all Sentinel nodes, in case of a failure,
it needs to access at least one of listed ones.
The following steps should be performed in the GitLab application server
which ideally should not have Redis or Sentinels in the same machine:
1. Edit `/home/git/gitlab/config/resque.yml` following the example in
[`resque.yml.example`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/config/resque.yml.example), and uncomment the Sentinel lines, pointing to
the correct server credentials:
```yaml
# resque.yaml
production:
url: redis://:redi-password-goes-here@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Example of minimal configuration with 1 primary, 2 replicas and 3 sentinels
In this example we consider that all servers have an internal network
interface with IPs in the `10.0.0.x` range, and that they can connect
to each other using these IPs.
In a real world usage, you would also set up firewall rules to prevent
unauthorized access from other machines, and block traffic from the
outside ([Internet](https://gitlab.com/gitlab-org/gitlab-foss/uploads/c4cc8cd353604bd80315f9384035ff9e/The_Internet_IT_Crowd.png)).
For this example, **Sentinel 1** is configured in the same machine as the
**Redis Primary**, **Sentinel 2** in the same machine as **Replica 1**, and
**Sentinel 3** in the same machine as **Replica 2**.
Here is a list and description of each **machine** and the assigned **IP**:
- `10.0.0.1`: Redis Primary + Sentinel 1
- `10.0.0.2`: Redis Replica 1 + Sentinel 2
- `10.0.0.3`: Redis Replica 2 + Sentinel 3
- `10.0.0.4`: GitLab application
After the initial configuration, if a failover is initiated
by the Sentinel nodes, the Redis nodes are reconfigured and the **Primary**
changes permanently (including in `redis.conf`) from one node to the other,
until a new failover is initiated again.
The same thing happens with `sentinel.conf` that is overridden after the
initial execution, after any new sentinel node starts watching the **Primary**,
or a failover promotes a different **Primary** node.
### Example configuration for Redis primary and Sentinel 1
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.1
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.1
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration for Redis replica 1 and Sentinel 2
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.2
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
replicaof 10.0.0.1 6379
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.2
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration for Redis replica 2 and Sentinel 3
1. In `/etc/redis/redis.conf`:
```conf
bind 10.0.0.3
port 6379
requirepass redis-password-goes-here
masterauth redis-password-goes-here
replicaof 10.0.0.1 6379
```
1. In `/etc/redis/sentinel.conf`:
```conf
bind 10.0.0.3
port 26379
sentinel auth-pass gitlab-redis redis-password-goes-here
sentinel monitor gitlab-redis 10.0.0.1 6379 2
sentinel down-after-milliseconds gitlab-redis 10000
sentinel failover_timeout 30000
```
1. Restart the Redis service for the changes to take effect.
### Example configuration of the GitLab application
1. Edit `/home/git/gitlab/config/resque.yml`:
```yaml
production:
url: redis://:redis-password-goes-here@gitlab-redis/
sentinels:
-
host: 10.0.0.1
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.2
port: 26379 # point to sentinel, not to redis port
-
host: 10.0.0.3
port: 26379 # point to sentinel, not to redis port
```
1. [Restart GitLab](../restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
|
https://docs.gitlab.com/administration/standalone
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/administration/standalone.md
|
2025-08-13
|
doc/administration/redis
|
[
"doc",
"administration",
"redis"
] |
standalone.md
|
Data access
|
Durability
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Standalone Redis using the Linux package
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux package can be used to configure a standalone Redis server.
In this configuration, Redis is not scaled, and represents a single
point of failure. However, in a scaled environment the objective is to allow
the environment to handle more users or to increase throughput. Redis itself
is generally stable and can handle many requests, so it is an acceptable
trade off to have only a single instance. See the [reference architectures](../reference_architectures/_index.md)
page for an overview of GitLab scaling options.
## Set up the standalone Redis instance
The steps below are the minimum necessary to configure a Redis server with
the Linux package:
1. SSH into the Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want by using **steps 1 and 2** from the GitLab downloads page.
Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
## Enable Redis and disable all other services
## https://docs.gitlab.com/omnibus/roles/
roles ['redis_master_role']
## Redis configuration
redis['bind'] = '0.0.0.0'
redis['port'] = 6379
redis['password'] = '<redis_password>'
## Disable automatic database migrations
## Only the primary GitLab application server should handle migrations
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the Redis node's IP address or hostname, port, and
Redis password. These are necessary when [configuring the GitLab application servers](#set-up-the-gitlab-rails-application-instance).
[Advanced configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
## Set up the GitLab Rails application instance
On the instance where GitLab is installed:
1. Edit the `/etc/gitlab/gitlab.rb` file and add the following contents:
```ruby
## Disable Redis
redis['enable'] = false
gitlab_rails['redis_host'] = 'redis.example.com'
gitlab_rails['redis_port'] = 6379
## Required if Redis authentication is configured on the Redis node
gitlab_rails['redis_password'] = '<redis_password>'
```
1. Save your changes to `/etc/gitlab/gitlab.rb`.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
|
---
stage: Data access
group: Durability
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Standalone Redis using the Linux package
breadcrumbs:
- doc
- administration
- redis
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux package can be used to configure a standalone Redis server.
In this configuration, Redis is not scaled, and represents a single
point of failure. However, in a scaled environment the objective is to allow
the environment to handle more users or to increase throughput. Redis itself
is generally stable and can handle many requests, so it is an acceptable
trade off to have only a single instance. See the [reference architectures](../reference_architectures/_index.md)
page for an overview of GitLab scaling options.
## Set up the standalone Redis instance
The steps below are the minimum necessary to configure a Redis server with
the Linux package:
1. SSH into the Redis server.
1. [Download and install](https://about.gitlab.com/install/) the Linux
package you want by using **steps 1 and 2** from the GitLab downloads page.
Do not complete any other steps on the download page.
1. Edit `/etc/gitlab/gitlab.rb` and add the contents:
```ruby
## Enable Redis and disable all other services
## https://docs.gitlab.com/omnibus/roles/
roles ['redis_master_role']
## Redis configuration
redis['bind'] = '0.0.0.0'
redis['port'] = 6379
redis['password'] = '<redis_password>'
## Disable automatic database migrations
## Only the primary GitLab application server should handle migrations
gitlab_rails['auto_migrate'] = false
```
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
1. Note the Redis node's IP address or hostname, port, and
Redis password. These are necessary when [configuring the GitLab application servers](#set-up-the-gitlab-rails-application-instance).
[Advanced configuration options](https://docs.gitlab.com/omnibus/settings/redis.html)
are supported and can be added if needed.
## Set up the GitLab Rails application instance
On the instance where GitLab is installed:
1. Edit the `/etc/gitlab/gitlab.rb` file and add the following contents:
```ruby
## Disable Redis
redis['enable'] = false
gitlab_rails['redis_host'] = 'redis.example.com'
gitlab_rails['redis_port'] = 6379
## Required if Redis authentication is configured on the Redis node
gitlab_rails['redis_password'] = '<redis_password>'
```
1. Save your changes to `/etc/gitlab/gitlab.rb`.
1. [Reconfigure GitLab](../restart_gitlab.md#reconfigure-a-linux-package-installation) for the changes to take effect.
## Troubleshooting
See the [Redis troubleshooting guide](troubleshooting.md).
|
https://docs.gitlab.com/error_tracking
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/error_tracking.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
error_tracking.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Error Tracking
|
Error tracking, logging, debugging, and data retention.
|
Error Tracking helps developers to discover and view errors generated by their
application. Because error information is surfaced where the code is developed,
error tracking increases efficiency and awareness. Users can choose between
[GitLab Integrated error tracking](integrated_error_tracking.md) and
[Sentry-based](sentry_error_tracking.md) backends.
## Prerequisites
For error tracking to work, you need:
- **Your application configured with the Sentry SDK**: When the error happens, Sentry SDK captures information
about it and sends it over the network to the backend. The backend stores information about all
errors.
- **Error tracking backend**: The backend can be either GitLab itself or Sentry.
- To use the GitLab backend, see [GitLab integrated error tracking](integrated_error_tracking.md).
Integrated error tracking is available only on GitLab.com.
- To use Sentry as the backend, see [Sentry error tracking](sentry_error_tracking.md).
Sentry-based error tracking is available for GitLab.com, GitLab Dedicated, and GitLab Self-Managed.
## How error tracking works
The following table gives an overview of the capabilities for each GitLab offering:
| Feature | Availability | Data collection | Data storage | Data query |
| ----------- | ----------- | ----------- | ----------- | ----------- |
| [GitLab integrated Error Tracking](integrated_error_tracking.md) | GitLab.com | With [Sentry SDK](https://github.com/getsentry/sentry?tab=readme-ov-file#official-sentry-sdks) | On GitLab.com | With GitLab.com |
| [Sentry-based Error Tracking](sentry_error_tracking.md) | GitLab.com, GitLab Dedicated, GitLab Self-Managed | With [Sentry SDK](https://github.com/getsentry/sentry?tab=readme-ov-file#official-sentry-sdks) | On Sentry instance (Cloud Sentry.io or [self-hosted Sentry](https://develop.sentry.dev/self-hosted/)) | With GitLab.com or Sentry instance |
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Error Tracking
description: Error tracking, logging, debugging, and data retention.
breadcrumbs:
- doc
- operations
---
Error Tracking helps developers to discover and view errors generated by their
application. Because error information is surfaced where the code is developed,
error tracking increases efficiency and awareness. Users can choose between
[GitLab Integrated error tracking](integrated_error_tracking.md) and
[Sentry-based](sentry_error_tracking.md) backends.
## Prerequisites
For error tracking to work, you need:
- **Your application configured with the Sentry SDK**: When the error happens, Sentry SDK captures information
about it and sends it over the network to the backend. The backend stores information about all
errors.
- **Error tracking backend**: The backend can be either GitLab itself or Sentry.
- To use the GitLab backend, see [GitLab integrated error tracking](integrated_error_tracking.md).
Integrated error tracking is available only on GitLab.com.
- To use Sentry as the backend, see [Sentry error tracking](sentry_error_tracking.md).
Sentry-based error tracking is available for GitLab.com, GitLab Dedicated, and GitLab Self-Managed.
## How error tracking works
The following table gives an overview of the capabilities for each GitLab offering:
| Feature | Availability | Data collection | Data storage | Data query |
| ----------- | ----------- | ----------- | ----------- | ----------- |
| [GitLab integrated Error Tracking](integrated_error_tracking.md) | GitLab.com | With [Sentry SDK](https://github.com/getsentry/sentry?tab=readme-ov-file#official-sentry-sdks) | On GitLab.com | With GitLab.com |
| [Sentry-based Error Tracking](sentry_error_tracking.md) | GitLab.com, GitLab Dedicated, GitLab Self-Managed | With [Sentry SDK](https://github.com/getsentry/sentry?tab=readme-ov-file#official-sentry-sdks) | On Sentry instance (Cloud Sentry.io or [self-hosted Sentry](https://develop.sentry.dev/self-hosted/)) | With GitLab.com or Sentry instance |
|
https://docs.gitlab.com/operations
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/_index.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
_index.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Monitor your application
|
Track errors and manage incident response.
|
Visualize and analyze errors and incidents related to your application and its infrastructure.
{{< cards >}}
- [Getting started](../user/get_started/get_started_monitoring.md)
- [Error tracking](error_tracking.md)
- [Incident management](incident_management/_index.md)
- [Observability](observability.md)
{{< /cards >}}
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Track errors and manage incident response.
title: Monitor your application
breadcrumbs:
- doc
- operations
---
Visualize and analyze errors and incidents related to your application and its infrastructure.
{{< cards >}}
- [Getting started](../user/get_started/get_started_monitoring.md)
- [Error tracking](error_tracking.md)
- [Incident management](incident_management/_index.md)
- [Observability](observability.md)
{{< /cards >}}
|
https://docs.gitlab.com/integrated_error_tracking
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/integrated_error_tracking.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
integrated_error_tracking.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Integrated error tracking
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
This guide provides basic information on how to set up integrated error tracking for
your project, using examples from different languages.
Error tracking provided by GitLab Observability is based on
[Sentry SDK](https://docs.sentry.io/).
For more information and examples of how you can use Sentry SDK in your application,
see the [Sentry SDK documentation](https://docs.sentry.io/platforms/).
## Enable error tracking for a project
Regardless of the programming language you use, you first need to enable error tracking
for your GitLab project. This guide uses the `GitLab.com` instance.
Prerequisites:
- You must have a project for which you want to enable error tracking.
See how to [create a project](../user/project/_index.md).
To enable error tracking with GitLab as the backend:
1. On the left sidebar, select **Search or go to** and find your project.
1. Go to **Settings > Monitor**.
1. Expand **Error Tracking**.
1. For **Enable error tracking**, select **Active**.
1. For **Error tracking backend**, select **GitLab**.
1. Select **Save changes**.
1. Copy the **Data Source Name (DSN)** string. You need it to configure your SDK implementation.
## Configure user tracking
To track the number of users affected by an error:
- In the instrumentation code, ensure each user is uniquely identified.
You can use a user ID, name, email address, or IP address to identify a user.
For example, if you use
[Python](https://docs.sentry.io/platforms/python/enriching-events/identify-user/),
you can identify a user by email:
```python
sentry_sdk.set_user({ email: "john.doe@example.com" });
```
For more information about user identification, see the [Sentry documentation](https://docs.sentry.io/).
## View tracked errors
After your application emits errors to the Error Tracking API through the Sentry SDK,
those errors are available in the GitLab UI. To view them:
1. On the left sidebar, select **Search or go to** and find your project.
1. Go to **Monitor > Error Tracking** to see the list of open errors:

1. Select an error to see the **Error details** view:

This page shows more details of the exception, including:
- Total number of occurrences.
- Total users affected.
- First seen: the date and commit ({{< icon name="commit" >}}).
- Last seen date, shown as a relative date. To view the timestamp, hover over the date.
- A bar graph of error frequency per hour. To view the total number of errors in a specific hour, hover over a bar.
- A stack trace.
### Create an issue from an error
If you want to track work related to an error, you can create an issue directly from the error:
- From the **Error details** view, select **Create issue**.
An issue is created. The issue description contains the error stack trace.
### Analyze an error's details
To view the full timestamp of an error:
- On the **Error details** page, hover over to the **Last seen** date.
In the following example, the error happened at 11:41 CEST:

The **Last 24 hours** graph measures how many times this error occurred per hour.
By pointing at the `11 am` bar, the dialog shows the error was seen 239 times:

The **Last seen** field does not update until the full hour is complete, due to
the library used for the call
[`import * as timeago from 'timeago.js'`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/lib/utils/datetime/timeago_utility.js#L1).
## Emit errors
### Supported language SDKs & Sentry types
GitLab Error Tracking supports these event types:
| Language | Tested SDK client and version | Endpoint | Supported item types |
| -------- | ------------------------------- | ---------- | --------------------------------- |
| Go | `sentry-go/0.20.0` | `store` | `exception`, `message` |
| Java | `sentry.java:6.18.1` | `envelope` | `exception`, `message` |
| NodeJS | `sentry.javascript.node:7.38.0` | `envelope` | `exception`, `message` |
| PHP | `sentry.php/3.18.0` | `store` | `exception`, `message` |
| Python | `sentry.python/1.21.0` | `envelope` | `exception`, `message`, `session` |
| Ruby | `sentry.ruby:5.9.0` | `envelope` | `exception`, `message` |
| Rust | `sentry.rust/0.31.0` | `envelope` | `exception`, `message`, `session` |
For a detailed version of this table, see
[issue 1737](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/1737).
See also working [examples for supported language SDKs](https://gitlab.com/gitlab-org/opstrace/opstrace/-/tree/main/test/sentry-sdk/testdata/supported-sdk-clients), showing how to capture exceptions, events, or messages with that SDK.
For more information, see the [Sentry SDK documentation](https://docs.sentry.io/) for a specific language.
## Rotate generated DSN
{{< alert type="warning" >}}
According to Sentry [it is safe to keep a DSN public](https://docs.sentry.io/concepts/key-terms/dsn-explainer/#dsn-utilization), but this opens up the possibility of junk events being sent to Sentry by malicious users. Therefore if possible you should keep the DSN secret. This doesn't apply to client-side applications where the DSN will be loaded and therefore stored on the user's device.
{{< /alert >}}
Prerequisites:
- You need the numeric [project ID](../user/project/working_with_projects.md#find-the-project-id)
for your project.
To rotate the Sentry DSN:
1. [Create an access token](../user/profile/personal_access_tokens.md#create-a-personal-access-token)
with the `api` scope. Copy off this value, as you need it in future steps.
1. Use the [error tracking API](../api/error_tracking.md) to create a new Sentry DSN,
replacing `<your_access_token>` and `<your_project_number>` with your values:
```shell
curl --request POST \
--header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys"
```
1. Get the available client keys (Sentry DSNs). Ensure your newly-created Sentry DSN
is in place. Run the following command with the key ID of the old client key, replacing `<your_access_token>`
and `<your_project_number>` with your values:
```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys"
```
1. Delete the old client key:
```shell
curl --request DELETE \
--header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys/<key_id>"
```
## Debug SDK issues
The majority of languages supported by Sentry expose a `debug` option as part
of initialization. The `debug` option can help you when you debug issues with
sending errors. Other options exist to output JSON before sending the data to the API.
## Data retention
GitLab has a 90-day retention limit for all errors.
To leave feedback about Error Tracking bugs or features, comment in the
[feedback issue](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/2362) or open a
[new issue](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/new).
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Integrated error tracking
breadcrumbs:
- doc
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
This guide provides basic information on how to set up integrated error tracking for
your project, using examples from different languages.
Error tracking provided by GitLab Observability is based on
[Sentry SDK](https://docs.sentry.io/).
For more information and examples of how you can use Sentry SDK in your application,
see the [Sentry SDK documentation](https://docs.sentry.io/platforms/).
## Enable error tracking for a project
Regardless of the programming language you use, you first need to enable error tracking
for your GitLab project. This guide uses the `GitLab.com` instance.
Prerequisites:
- You must have a project for which you want to enable error tracking.
See how to [create a project](../user/project/_index.md).
To enable error tracking with GitLab as the backend:
1. On the left sidebar, select **Search or go to** and find your project.
1. Go to **Settings > Monitor**.
1. Expand **Error Tracking**.
1. For **Enable error tracking**, select **Active**.
1. For **Error tracking backend**, select **GitLab**.
1. Select **Save changes**.
1. Copy the **Data Source Name (DSN)** string. You need it to configure your SDK implementation.
## Configure user tracking
To track the number of users affected by an error:
- In the instrumentation code, ensure each user is uniquely identified.
You can use a user ID, name, email address, or IP address to identify a user.
For example, if you use
[Python](https://docs.sentry.io/platforms/python/enriching-events/identify-user/),
you can identify a user by email:
```python
sentry_sdk.set_user({ email: "john.doe@example.com" });
```
For more information about user identification, see the [Sentry documentation](https://docs.sentry.io/).
## View tracked errors
After your application emits errors to the Error Tracking API through the Sentry SDK,
those errors are available in the GitLab UI. To view them:
1. On the left sidebar, select **Search or go to** and find your project.
1. Go to **Monitor > Error Tracking** to see the list of open errors:

1. Select an error to see the **Error details** view:

This page shows more details of the exception, including:
- Total number of occurrences.
- Total users affected.
- First seen: the date and commit ({{< icon name="commit" >}}).
- Last seen date, shown as a relative date. To view the timestamp, hover over the date.
- A bar graph of error frequency per hour. To view the total number of errors in a specific hour, hover over a bar.
- A stack trace.
### Create an issue from an error
If you want to track work related to an error, you can create an issue directly from the error:
- From the **Error details** view, select **Create issue**.
An issue is created. The issue description contains the error stack trace.
### Analyze an error's details
To view the full timestamp of an error:
- On the **Error details** page, hover over to the **Last seen** date.
In the following example, the error happened at 11:41 CEST:

The **Last 24 hours** graph measures how many times this error occurred per hour.
By pointing at the `11 am` bar, the dialog shows the error was seen 239 times:

The **Last seen** field does not update until the full hour is complete, due to
the library used for the call
[`import * as timeago from 'timeago.js'`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/lib/utils/datetime/timeago_utility.js#L1).
## Emit errors
### Supported language SDKs & Sentry types
GitLab Error Tracking supports these event types:
| Language | Tested SDK client and version | Endpoint | Supported item types |
| -------- | ------------------------------- | ---------- | --------------------------------- |
| Go | `sentry-go/0.20.0` | `store` | `exception`, `message` |
| Java | `sentry.java:6.18.1` | `envelope` | `exception`, `message` |
| NodeJS | `sentry.javascript.node:7.38.0` | `envelope` | `exception`, `message` |
| PHP | `sentry.php/3.18.0` | `store` | `exception`, `message` |
| Python | `sentry.python/1.21.0` | `envelope` | `exception`, `message`, `session` |
| Ruby | `sentry.ruby:5.9.0` | `envelope` | `exception`, `message` |
| Rust | `sentry.rust/0.31.0` | `envelope` | `exception`, `message`, `session` |
For a detailed version of this table, see
[issue 1737](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/1737).
See also working [examples for supported language SDKs](https://gitlab.com/gitlab-org/opstrace/opstrace/-/tree/main/test/sentry-sdk/testdata/supported-sdk-clients), showing how to capture exceptions, events, or messages with that SDK.
For more information, see the [Sentry SDK documentation](https://docs.sentry.io/) for a specific language.
## Rotate generated DSN
{{< alert type="warning" >}}
According to Sentry [it is safe to keep a DSN public](https://docs.sentry.io/concepts/key-terms/dsn-explainer/#dsn-utilization), but this opens up the possibility of junk events being sent to Sentry by malicious users. Therefore if possible you should keep the DSN secret. This doesn't apply to client-side applications where the DSN will be loaded and therefore stored on the user's device.
{{< /alert >}}
Prerequisites:
- You need the numeric [project ID](../user/project/working_with_projects.md#find-the-project-id)
for your project.
To rotate the Sentry DSN:
1. [Create an access token](../user/profile/personal_access_tokens.md#create-a-personal-access-token)
with the `api` scope. Copy off this value, as you need it in future steps.
1. Use the [error tracking API](../api/error_tracking.md) to create a new Sentry DSN,
replacing `<your_access_token>` and `<your_project_number>` with your values:
```shell
curl --request POST \
--header "PRIVATE-TOKEN: <your_access_token>" \
--header "Content-Type: application/json" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys"
```
1. Get the available client keys (Sentry DSNs). Ensure your newly-created Sentry DSN
is in place. Run the following command with the key ID of the old client key, replacing `<your_access_token>`
and `<your_project_number>` with your values:
```shell
curl --header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys"
```
1. Delete the old client key:
```shell
curl --request DELETE \
--header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.example.com/api/v4/projects/<your_project_number>/error_tracking/client_keys/<key_id>"
```
## Debug SDK issues
The majority of languages supported by Sentry expose a `debug` option as part
of initialization. The `debug` option can help you when you debug issues with
sending errors. Other options exist to output JSON before sending the data to the API.
## Data retention
GitLab has a 90-day retention limit for all errors.
To leave feedback about Error Tracking bugs or features, comment in the
[feedback issue](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/2362) or open a
[new issue](https://gitlab.com/gitlab-org/opstrace/opstrace/-/issues/new).
|
https://docs.gitlab.com/feature_flags
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/feature_flags.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
feature_flags.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Feature flags
|
Progressive delivery, controlled deployment, and risk reduction.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
With feature flags, you can deploy your application's new features to production in smaller batches.
You can toggle a feature on and off to subsets of users, helping you achieve Continuous Delivery.
Feature flags help reduce risk, allowing you to do controlled testing, and separate feature
delivery from customer launch.
A [complete list of feature flags](../administration/feature_flags/list.md) in GitLab is also available.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an example of feature flags in action, see [Eliminating risk with feature flags](https://www.youtube.com/watch?v=U9WqoK9froI).
<!-- Video published on 2024-02-01 -->
For a click-through demo, see [Feature Flags](https://tech-marketing.gitlab.io/static-demos/feature-flags/feature-flags-html.html).
<!-- Demo published on 2023-07-13 -->
## Using feature flags
GitLab offers an [Unleash](https://github.com/Unleash/unleash)-compatible API for feature flags.
By enabling or disabling a flag in GitLab, your application
can determine which features to enable or disable.
You can create feature flags in GitLab and use the API from your application
to get the list of feature flags and their statuses. The application must be configured to communicate
with GitLab, so it's up to developers to use a compatible client library and
[integrate the feature flags in your app](#integrate-feature-flags-with-your-application).
## Create a feature flag
To create and enable a feature flag:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **New feature flag**.
1. Enter a name that starts with a letter and contains only lowercase letters, digits, underscores (`_`),
or dashes (`-`), and does not end with a dash (`-`) or underscore (`_`).
1. Optional. Enter a description (255 characters maximum).
1. Add feature flag [**Strategies**](#feature-flag-strategies) to define how the flag should be applied. For each strategy, include the **Type** (defaults to [**All users**](#all-users))
and **Environments** (defaults to all environments).
1. Select **Create feature flag**.
To change these settings, select **Edit** ({{< icon name="pencil" >}})
next to any feature flag in the list.
## Maximum number of feature flags
The maximum number of feature flags per project on GitLab Self-Managed
is 200. For GitLab.com, the maximum number is determined by [tier](https://about.gitlab.com/pricing/):
| Tier | Feature flags per project (GitLab.com) | Feature flags per project (GitLab Self-Managed) |
|----------|----------------------------------|------------------------------------------|
| Free | 50 | 200 |
| Premium | 150 | 200 |
| Ultimate | 200 | 200 |
## Feature flag strategies
You can apply a feature flag strategy across multiple environments, without defining
the strategy multiple times.
GitLab feature flags are based on [Unleash](https://docs.getunleash.io/). In Unleash, there are
[strategies](https://docs.getunleash.io/reference/activation-strategies) for granular feature
flag controls. GitLab feature flags can have multiple strategies, and the supported strategies are:
- [All users](#all-users)
- [Percent of Users](#percent-of-users)
- [User IDs](#user-ids)
- [User List](#user-list)
Strategies can be added to feature flags when [creating a feature flag](#create-a-feature-flag),
or by editing an existing feature flag after creation by navigating to **Deploy > Feature flags**
and selecting **Edit** ({{< icon name="pencil" >}}).
### All users
Enables the feature for all users. It uses the Standard (`default`) Unleash activation [strategy](https://docs.getunleash.io/reference/activation-strategies#standard).
### Percent Rollout
Enables the feature for a percentage of page views, with configurable consistency
of behavior. This consistency is also known as stickiness. It uses the
Gradual Rollout (`flexibleRollout`) Unleash activation [strategy](https://docs.getunleash.io/reference/activation-strategies#gradual-rollout).
You can configure the consistency to be based on:
- **User IDs**: Each user ID has a consistent behavior, ignoring session IDs.
- **Session IDs**: Each session ID has a consistent behavior, ignoring user IDs.
- **Random**: Consistent behavior is not guaranteed. The feature is enabled for the
selected percentage of page views randomly. User IDs and session IDs are ignored.
- **Available ID**: Consistent behavior is attempted based on the status of the user:
- If the user is logged in, make behavior consistent based on user ID.
- If the user is anonymous, make the behavior consistent based on the session ID.
- If there is no user ID or session ID, then the feature is enabled for the selected
percentage of page view randomly.
For example, set a value of 15% based on **Available ID** to enable the feature for 15% of page views. For
authenticated users this is based on their user ID. For anonymous users with a session ID it would be based on their
session ID instead as they do not have a user ID. Then if no session ID is provided, it falls back to random.
The rollout percentage can be from 0% to 100%.
Selecting a consistency based on User IDs functions the same as the [percent of Users](#percent-of-users) rollout.
{{< alert type="warning" >}}
Selecting **Random** provides inconsistent application behavior for individual users.
{{< /alert >}}
### Percent of Users
Enables the feature for a percentage of authenticated users. It uses the Unleash activation strategy
[`gradualRolloutUserId`](https://docs.getunleash.io/reference/activation-strategies#gradual-rollout).
For example, set a value of 15% to enable the feature for 15% of authenticated users.
The rollout percentage can be from 0% to 100%.
Stickiness (consistent application behavior for the same user) is guaranteed for authenticated users,
but not anonymous users.
[Percent rollout](#percent-rollout) with a consistency based on **User IDs** has the same
behavior. We recommend using percent rollout because it's more flexible than percent of users
{{< alert type="warning" >}}
If the percent of users strategy is selected, then the Unleash client **must** be given a user
ID for the feature to be enabled. See the [Ruby example](#ruby-application-example) below.
{{< /alert >}}
### User IDs
Enables the feature for a list of target users. It is implemented
using the Unleash UserIDs (`userWithId`) activation [strategy](https://docs.getunleash.io/reference/activation-strategies#userids).
Enter user IDs as a comma-separated list of values (for example,
`user@example.com, user2@example.com`, or `username1,username2,username3`, and so on).
User IDs are identifiers for your application users. They do not need to be GitLab users.
{{< alert type="warning" >}}
The Unleash client **must** be given a user ID for the feature to be enabled for
target users. See the [Ruby example](#ruby-application-example) below.
{{< /alert >}}
### User List
Enables the feature for lists of users created [in the feature flags UI](#create-a-user-list), or with the [feature flag user list API](../api/feature_flag_user_lists.md).
Similar to [User IDs](#user-ids), it uses the Unleash UsersIDs (`userWithId`) activation [strategy](https://docs.getunleash.io/reference/activation-strategies#userids).
You can't disable a specific feature for a user, but you can achieve similar results by enabling it for a user list.
For example:
- `Full-user-list` = `User1A, User1B, User2A, User2B, User3A, User3B, ...`
- `Full-user-list-excluding-B-users` = `User1A, User2A, User3A, ...`
#### Create a user list
To create a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **View user lists**
1. Select **New user list**.
1. Enter a name for the list.
1. Select **Create**.
You can view a list's User IDs by selecting **Edit** ({{< icon name="pencil" >}}) next to it.
When viewing a list, you can rename it by selecting **Edit** ({{< icon name="pencil" >}}).
#### Add users to a user list
To add users to a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Edit** ({{< icon name="pencil" >}}) next to the list you want to add users to.
1. Select **Add Users**.
1. Enter the user IDs as a comma-separated list of values. For example,
`user@example.com, user2@example.com`, or `username1,username2,username3`, and so on.
1. Select **Add**.
#### Remove users from a user list
To remove users from a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Edit** ({{< icon name="pencil" >}}) next to the list you want to change.
1. Select **Remove** ({{< icon name="remove" >}}) next to the ID you want to remove.
## Search for Code References
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To remove the feature flag from the code during cleanup, find any project references to it.
To search for code references of a feature flag:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Edit the feature flag you want to remove.
1. Select **More actions** ({{< icon name="ellipsis_v" >}}).
1. Select **Search code references**.
## Disable a feature flag for a specific environment
To disable a feature flag for a specific environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. For the feature flag you want to disable, select **Edit** ({{< icon name="pencil" >}}).
1. To disable the flag:
- For each strategy it applies to, under **Environments**, delete the environment.
1. Select **Save changes**.
## Disable a feature flag for all environments
To disable a feature flag for all environments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. For the feature flag you want to disable, slide the Status toggle to **Disabled**.
The feature flag is displayed on the **Disabled** tab.
## Integrate feature flags with your application
To use feature flags with your application, get access credentials from GitLab.
Then prepare your application with a client library.
### Get access credentials
To get the access credentials that your application needs to communicate with GitLab:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Configure** to view the following:
- **API URL**: URL where the client (application) connects to get a list of feature flags.
- **Instance ID**: Unique token that authorizes the retrieval of the feature flags.
- **Application name**: The name of the environment the application runs in
(not the name of the application itself).
For example, if the application runs for a production server, the **Application name**
could be `production` or similar. This value is used for the environment spec evaluation.
The meaning of these fields might change over time. For example, we're not sure if
**Instance ID** is a single token or multiple tokens, assigned to the **Environment**. Also,
**Application name** could describe the application version instead of the running environment.
### Choose a client library
GitLab implements a single backend that is compatible with Unleash clients.
With the Unleash client, developers can define, in the application code, the default values for flags.
Each feature flag evaluation can express the desired outcome if the flag isn't present in the
provided configuration file.
Unleash currently [offers many SDKs for various languages and frameworks](https://github.com/Unleash/unleash#unleash-sdks).
### Feature flags API information
For API content, see:
- [Feature flags API](../api/feature_flags.md)
- [Feature flag user lists API](../api/feature_flag_user_lists.md)
### Go application example
Here's an example of how to integrate feature flags in a Go application:
```go
package main
import (
"io"
"log"
"net/http"
"github.com/Unleash/unleash-client-go/v3"
)
type metricsInterface struct {
}
func init() {
unleash.Initialize(
unleash.WithUrl("https://gitlab.com/api/v4/feature_flags/unleash/42"),
unleash.WithInstanceId("29QmjsW6KngPR5JNPMWx"),
unleash.WithAppName("production"), // Set to the running environment of your application
unleash.WithListener(&metricsInterface{}),
)
}
func helloServer(w http.ResponseWriter, req *http.Request) {
if unleash.IsEnabled("my_feature_name") {
io.WriteString(w, "Feature enabled\n")
} else {
io.WriteString(w, "hello, world!\n")
}
}
func main() {
http.HandleFunc("/", helloServer)
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
### Ruby application example
Here's an example of how to integrate feature flags in a Ruby application.
The Unleash client is given a user ID for use with a **Percent rollout (logged in users)** rollout strategy or a list of **Target Users**.
```ruby
#!/usr/bin/env ruby
require 'unleash'
require 'unleash/context'
unleash = Unleash::Client.new({
url: 'http://gitlab.com/api/v4/feature_flags/unleash/42',
app_name: 'production', # Set to the running environment of your application
instance_id: '29QmjsW6KngPR5JNPMWx'
})
unleash_context = Unleash::Context.new
# Replace "123" with the ID of an authenticated user.
# The context's user ID must be a string:
# https://unleash.github.io/docs/unleash_context
unleash_context.user_id = "123"
if unleash.is_enabled?("my_feature_name", unleash_context)
puts "Feature enabled"
else
puts "hello, world!"
end
```
### Unleash Proxy example
As of [Unleash Proxy](https://docs.getunleash.io/reference/unleash-proxy) version
0.2, the proxy is compatible with feature flags.
You should use Unleash Proxy for production on GitLab.com. See the [performance note](#maximum-supported-clients-in-application-nodes) for details.
To run a Docker container to
connect to your project's feature flags, run the following command:
```shell
docker run \
-e UNLEASH_PROXY_SECRETS=<secret> \
-e UNLEASH_URL=<project feature flags URL> \
-e UNLEASH_INSTANCE_ID=<project feature flags instance ID> \
-e UNLEASH_APP_NAME=<project environment> \
-e UNLEASH_API_TOKEN=<tokenNotUsed> \
-p 3000:3000 \
unleashorg/unleash-proxy
```
| Variable | Value |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `UNLEASH_PROXY_SECRETS` | Shared secret used to configure an [Unleash Proxy client](https://docs.getunleash.io/reference/unleash-proxy#how-to-connect-to-the-proxy). |
| `UNLEASH_URL` | Your project's API URL. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_INSTANCE_ID` | Your project's Instance ID. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_APP_NAME` | The name of the environment the application runs in. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_API_TOKEN` | Required to start the Unleash Proxy, but not used to connect to GitLab. Can be set to any value. |
There is a limitation when using the Unleash Proxy where each proxy instance can request flags only for the environment named in `UNLEASH_APP_NAME`. The Proxy sends
this to GitLab on behalf of the client, which means the client can't override it.
## Feature flag related issues
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can link related issues to a feature flag. In the feature flag **Linked issues** section,
select the `+` button and input the issue reference number or the full URL of the issue.
The issues then appear in the related feature flag and the other way round.
This feature is similar to the [linked issues](../user/project/issues/related_issues.md) feature.
## Performance factors
GitLab feature flags can be used in any application. Large applications might require advance configuration.
This section explains the performance factors to help your organization to identify
what's needed to be done before using the feature.
For more information, see [using feature flags](#using-feature-flags).
### Maximum supported clients in application nodes
GitLab accepts as many client requests as possible until it hits the [rate limit](../security/rate_limits.md).
The feature flag API is considered **Unauthenticated traffic (from a given IP address)**. For GitLab.com, see the [GitLab.com specific limits](../user/gitlab_com/_index.md).
The polling rate is configurable in SDKs. Provided that all clients are requesting from the same IP:
- Request once per minute ... 500 clients can be supported.
- Request once per 15 sec ... 125 clients can be supported.
For applications looking for more scalable solution, you should use [Unleash Proxy](#unleash-proxy-example).
On GitLab.com, you should use Unleash Proxy to reduce the chance of being rate limited across endpoints.
This proxy server sits between the server and clients. It makes requests to the server on behalf of the client groups,
so the number of outbound requests can be greatly reduced. If you still get `429` responses, increase the `UNLEASH_FETCH_INTERVAL` value in the Unleash Proxy.
There is also an [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/295472) to give more
capacity to the current rate limit.
### Recovering from network errors
In general, [Unleash clients](https://github.com/Unleash/unleash#unleash-sdks) have
a fall-back mechanism when the server returns an error code.
For example, `unleash-ruby-client` reads flag data from the local backup so that
application can keep running in the current state.
Read the documentation in a SDK project for more information.
### GitLab Self-Managed
Functionality-wise, there are no differences. Both GitLab.com and GitLab Self-Managed behave the same.
In terms of scalability, it's up to the spec of the GitLab instance.
For example, GitLab.com uses HA architecture so it can handle many concurrent requests. However, GitLab Self-Managed instances on underpowered machines won't deliver comparable performance.
See [Reference architectures](../administration/reference_architectures/_index.md)
for more information.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Progressive delivery, controlled deployment, and risk reduction.
title: Feature flags
breadcrumbs:
- doc
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
With feature flags, you can deploy your application's new features to production in smaller batches.
You can toggle a feature on and off to subsets of users, helping you achieve Continuous Delivery.
Feature flags help reduce risk, allowing you to do controlled testing, and separate feature
delivery from customer launch.
A [complete list of feature flags](../administration/feature_flags/list.md) in GitLab is also available.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an example of feature flags in action, see [Eliminating risk with feature flags](https://www.youtube.com/watch?v=U9WqoK9froI).
<!-- Video published on 2024-02-01 -->
For a click-through demo, see [Feature Flags](https://tech-marketing.gitlab.io/static-demos/feature-flags/feature-flags-html.html).
<!-- Demo published on 2023-07-13 -->
## Using feature flags
GitLab offers an [Unleash](https://github.com/Unleash/unleash)-compatible API for feature flags.
By enabling or disabling a flag in GitLab, your application
can determine which features to enable or disable.
You can create feature flags in GitLab and use the API from your application
to get the list of feature flags and their statuses. The application must be configured to communicate
with GitLab, so it's up to developers to use a compatible client library and
[integrate the feature flags in your app](#integrate-feature-flags-with-your-application).
## Create a feature flag
To create and enable a feature flag:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **New feature flag**.
1. Enter a name that starts with a letter and contains only lowercase letters, digits, underscores (`_`),
or dashes (`-`), and does not end with a dash (`-`) or underscore (`_`).
1. Optional. Enter a description (255 characters maximum).
1. Add feature flag [**Strategies**](#feature-flag-strategies) to define how the flag should be applied. For each strategy, include the **Type** (defaults to [**All users**](#all-users))
and **Environments** (defaults to all environments).
1. Select **Create feature flag**.
To change these settings, select **Edit** ({{< icon name="pencil" >}})
next to any feature flag in the list.
## Maximum number of feature flags
The maximum number of feature flags per project on GitLab Self-Managed
is 200. For GitLab.com, the maximum number is determined by [tier](https://about.gitlab.com/pricing/):
| Tier | Feature flags per project (GitLab.com) | Feature flags per project (GitLab Self-Managed) |
|----------|----------------------------------|------------------------------------------|
| Free | 50 | 200 |
| Premium | 150 | 200 |
| Ultimate | 200 | 200 |
## Feature flag strategies
You can apply a feature flag strategy across multiple environments, without defining
the strategy multiple times.
GitLab feature flags are based on [Unleash](https://docs.getunleash.io/). In Unleash, there are
[strategies](https://docs.getunleash.io/reference/activation-strategies) for granular feature
flag controls. GitLab feature flags can have multiple strategies, and the supported strategies are:
- [All users](#all-users)
- [Percent of Users](#percent-of-users)
- [User IDs](#user-ids)
- [User List](#user-list)
Strategies can be added to feature flags when [creating a feature flag](#create-a-feature-flag),
or by editing an existing feature flag after creation by navigating to **Deploy > Feature flags**
and selecting **Edit** ({{< icon name="pencil" >}}).
### All users
Enables the feature for all users. It uses the Standard (`default`) Unleash activation [strategy](https://docs.getunleash.io/reference/activation-strategies#standard).
### Percent Rollout
Enables the feature for a percentage of page views, with configurable consistency
of behavior. This consistency is also known as stickiness. It uses the
Gradual Rollout (`flexibleRollout`) Unleash activation [strategy](https://docs.getunleash.io/reference/activation-strategies#gradual-rollout).
You can configure the consistency to be based on:
- **User IDs**: Each user ID has a consistent behavior, ignoring session IDs.
- **Session IDs**: Each session ID has a consistent behavior, ignoring user IDs.
- **Random**: Consistent behavior is not guaranteed. The feature is enabled for the
selected percentage of page views randomly. User IDs and session IDs are ignored.
- **Available ID**: Consistent behavior is attempted based on the status of the user:
- If the user is logged in, make behavior consistent based on user ID.
- If the user is anonymous, make the behavior consistent based on the session ID.
- If there is no user ID or session ID, then the feature is enabled for the selected
percentage of page view randomly.
For example, set a value of 15% based on **Available ID** to enable the feature for 15% of page views. For
authenticated users this is based on their user ID. For anonymous users with a session ID it would be based on their
session ID instead as they do not have a user ID. Then if no session ID is provided, it falls back to random.
The rollout percentage can be from 0% to 100%.
Selecting a consistency based on User IDs functions the same as the [percent of Users](#percent-of-users) rollout.
{{< alert type="warning" >}}
Selecting **Random** provides inconsistent application behavior for individual users.
{{< /alert >}}
### Percent of Users
Enables the feature for a percentage of authenticated users. It uses the Unleash activation strategy
[`gradualRolloutUserId`](https://docs.getunleash.io/reference/activation-strategies#gradual-rollout).
For example, set a value of 15% to enable the feature for 15% of authenticated users.
The rollout percentage can be from 0% to 100%.
Stickiness (consistent application behavior for the same user) is guaranteed for authenticated users,
but not anonymous users.
[Percent rollout](#percent-rollout) with a consistency based on **User IDs** has the same
behavior. We recommend using percent rollout because it's more flexible than percent of users
{{< alert type="warning" >}}
If the percent of users strategy is selected, then the Unleash client **must** be given a user
ID for the feature to be enabled. See the [Ruby example](#ruby-application-example) below.
{{< /alert >}}
### User IDs
Enables the feature for a list of target users. It is implemented
using the Unleash UserIDs (`userWithId`) activation [strategy](https://docs.getunleash.io/reference/activation-strategies#userids).
Enter user IDs as a comma-separated list of values (for example,
`user@example.com, user2@example.com`, or `username1,username2,username3`, and so on).
User IDs are identifiers for your application users. They do not need to be GitLab users.
{{< alert type="warning" >}}
The Unleash client **must** be given a user ID for the feature to be enabled for
target users. See the [Ruby example](#ruby-application-example) below.
{{< /alert >}}
### User List
Enables the feature for lists of users created [in the feature flags UI](#create-a-user-list), or with the [feature flag user list API](../api/feature_flag_user_lists.md).
Similar to [User IDs](#user-ids), it uses the Unleash UsersIDs (`userWithId`) activation [strategy](https://docs.getunleash.io/reference/activation-strategies#userids).
You can't disable a specific feature for a user, but you can achieve similar results by enabling it for a user list.
For example:
- `Full-user-list` = `User1A, User1B, User2A, User2B, User3A, User3B, ...`
- `Full-user-list-excluding-B-users` = `User1A, User2A, User3A, ...`
#### Create a user list
To create a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **View user lists**
1. Select **New user list**.
1. Enter a name for the list.
1. Select **Create**.
You can view a list's User IDs by selecting **Edit** ({{< icon name="pencil" >}}) next to it.
When viewing a list, you can rename it by selecting **Edit** ({{< icon name="pencil" >}}).
#### Add users to a user list
To add users to a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Edit** ({{< icon name="pencil" >}}) next to the list you want to add users to.
1. Select **Add Users**.
1. Enter the user IDs as a comma-separated list of values. For example,
`user@example.com, user2@example.com`, or `username1,username2,username3`, and so on.
1. Select **Add**.
#### Remove users from a user list
To remove users from a user list:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Edit** ({{< icon name="pencil" >}}) next to the list you want to change.
1. Select **Remove** ({{< icon name="remove" >}}) next to the ID you want to remove.
## Search for Code References
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To remove the feature flag from the code during cleanup, find any project references to it.
To search for code references of a feature flag:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Edit the feature flag you want to remove.
1. Select **More actions** ({{< icon name="ellipsis_v" >}}).
1. Select **Search code references**.
## Disable a feature flag for a specific environment
To disable a feature flag for a specific environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. For the feature flag you want to disable, select **Edit** ({{< icon name="pencil" >}}).
1. To disable the flag:
- For each strategy it applies to, under **Environments**, delete the environment.
1. Select **Save changes**.
## Disable a feature flag for all environments
To disable a feature flag for all environments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. For the feature flag you want to disable, slide the Status toggle to **Disabled**.
The feature flag is displayed on the **Disabled** tab.
## Integrate feature flags with your application
To use feature flags with your application, get access credentials from GitLab.
Then prepare your application with a client library.
### Get access credentials
To get the access credentials that your application needs to communicate with GitLab:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Deploy > Feature flags**.
1. Select **Configure** to view the following:
- **API URL**: URL where the client (application) connects to get a list of feature flags.
- **Instance ID**: Unique token that authorizes the retrieval of the feature flags.
- **Application name**: The name of the environment the application runs in
(not the name of the application itself).
For example, if the application runs for a production server, the **Application name**
could be `production` or similar. This value is used for the environment spec evaluation.
The meaning of these fields might change over time. For example, we're not sure if
**Instance ID** is a single token or multiple tokens, assigned to the **Environment**. Also,
**Application name** could describe the application version instead of the running environment.
### Choose a client library
GitLab implements a single backend that is compatible with Unleash clients.
With the Unleash client, developers can define, in the application code, the default values for flags.
Each feature flag evaluation can express the desired outcome if the flag isn't present in the
provided configuration file.
Unleash currently [offers many SDKs for various languages and frameworks](https://github.com/Unleash/unleash#unleash-sdks).
### Feature flags API information
For API content, see:
- [Feature flags API](../api/feature_flags.md)
- [Feature flag user lists API](../api/feature_flag_user_lists.md)
### Go application example
Here's an example of how to integrate feature flags in a Go application:
```go
package main
import (
"io"
"log"
"net/http"
"github.com/Unleash/unleash-client-go/v3"
)
type metricsInterface struct {
}
func init() {
unleash.Initialize(
unleash.WithUrl("https://gitlab.com/api/v4/feature_flags/unleash/42"),
unleash.WithInstanceId("29QmjsW6KngPR5JNPMWx"),
unleash.WithAppName("production"), // Set to the running environment of your application
unleash.WithListener(&metricsInterface{}),
)
}
func helloServer(w http.ResponseWriter, req *http.Request) {
if unleash.IsEnabled("my_feature_name") {
io.WriteString(w, "Feature enabled\n")
} else {
io.WriteString(w, "hello, world!\n")
}
}
func main() {
http.HandleFunc("/", helloServer)
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
### Ruby application example
Here's an example of how to integrate feature flags in a Ruby application.
The Unleash client is given a user ID for use with a **Percent rollout (logged in users)** rollout strategy or a list of **Target Users**.
```ruby
#!/usr/bin/env ruby
require 'unleash'
require 'unleash/context'
unleash = Unleash::Client.new({
url: 'http://gitlab.com/api/v4/feature_flags/unleash/42',
app_name: 'production', # Set to the running environment of your application
instance_id: '29QmjsW6KngPR5JNPMWx'
})
unleash_context = Unleash::Context.new
# Replace "123" with the ID of an authenticated user.
# The context's user ID must be a string:
# https://unleash.github.io/docs/unleash_context
unleash_context.user_id = "123"
if unleash.is_enabled?("my_feature_name", unleash_context)
puts "Feature enabled"
else
puts "hello, world!"
end
```
### Unleash Proxy example
As of [Unleash Proxy](https://docs.getunleash.io/reference/unleash-proxy) version
0.2, the proxy is compatible with feature flags.
You should use Unleash Proxy for production on GitLab.com. See the [performance note](#maximum-supported-clients-in-application-nodes) for details.
To run a Docker container to
connect to your project's feature flags, run the following command:
```shell
docker run \
-e UNLEASH_PROXY_SECRETS=<secret> \
-e UNLEASH_URL=<project feature flags URL> \
-e UNLEASH_INSTANCE_ID=<project feature flags instance ID> \
-e UNLEASH_APP_NAME=<project environment> \
-e UNLEASH_API_TOKEN=<tokenNotUsed> \
-p 3000:3000 \
unleashorg/unleash-proxy
```
| Variable | Value |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `UNLEASH_PROXY_SECRETS` | Shared secret used to configure an [Unleash Proxy client](https://docs.getunleash.io/reference/unleash-proxy#how-to-connect-to-the-proxy). |
| `UNLEASH_URL` | Your project's API URL. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_INSTANCE_ID` | Your project's Instance ID. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_APP_NAME` | The name of the environment the application runs in. For more details, read [Get access credentials](#get-access-credentials). |
| `UNLEASH_API_TOKEN` | Required to start the Unleash Proxy, but not used to connect to GitLab. Can be set to any value. |
There is a limitation when using the Unleash Proxy where each proxy instance can request flags only for the environment named in `UNLEASH_APP_NAME`. The Proxy sends
this to GitLab on behalf of the client, which means the client can't override it.
## Feature flag related issues
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can link related issues to a feature flag. In the feature flag **Linked issues** section,
select the `+` button and input the issue reference number or the full URL of the issue.
The issues then appear in the related feature flag and the other way round.
This feature is similar to the [linked issues](../user/project/issues/related_issues.md) feature.
## Performance factors
GitLab feature flags can be used in any application. Large applications might require advance configuration.
This section explains the performance factors to help your organization to identify
what's needed to be done before using the feature.
For more information, see [using feature flags](#using-feature-flags).
### Maximum supported clients in application nodes
GitLab accepts as many client requests as possible until it hits the [rate limit](../security/rate_limits.md).
The feature flag API is considered **Unauthenticated traffic (from a given IP address)**. For GitLab.com, see the [GitLab.com specific limits](../user/gitlab_com/_index.md).
The polling rate is configurable in SDKs. Provided that all clients are requesting from the same IP:
- Request once per minute ... 500 clients can be supported.
- Request once per 15 sec ... 125 clients can be supported.
For applications looking for more scalable solution, you should use [Unleash Proxy](#unleash-proxy-example).
On GitLab.com, you should use Unleash Proxy to reduce the chance of being rate limited across endpoints.
This proxy server sits between the server and clients. It makes requests to the server on behalf of the client groups,
so the number of outbound requests can be greatly reduced. If you still get `429` responses, increase the `UNLEASH_FETCH_INTERVAL` value in the Unleash Proxy.
There is also an [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/295472) to give more
capacity to the current rate limit.
### Recovering from network errors
In general, [Unleash clients](https://github.com/Unleash/unleash#unleash-sdks) have
a fall-back mechanism when the server returns an error code.
For example, `unleash-ruby-client` reads flag data from the local backup so that
application can keep running in the current state.
Read the documentation in a SDK project for more information.
### GitLab Self-Managed
Functionality-wise, there are no differences. Both GitLab.com and GitLab Self-Managed behave the same.
In terms of scalability, it's up to the spec of the GitLab instance.
For example, GitLab.com uses HA architecture so it can handle many concurrent requests. However, GitLab Self-Managed instances on underpowered machines won't deliver comparable performance.
See [Reference architectures](../administration/reference_architectures/_index.md)
for more information.
|
https://docs.gitlab.com/sentry_error_tracking
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/sentry_error_tracking.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
sentry_error_tracking.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Sentry error tracking
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Sentry](https://sentry.io/) is an open source error tracking system. GitLab enables
administrators to connect Sentry to GitLab, so users can view a list of Sentry errors in GitLab.
GitLab integrates with both the cloud-hosted [Sentry](https://sentry.io) and Sentry
deployed in your [on-premise instance](https://github.com/getsentry/self-hosted).
## Enable Sentry integration for a project
GitLab provides a way to connect Sentry to your project.
Prerequisites:
- You must have at least the Maintainer role for the project.
To enable the Sentry integration:
1. Sign up to Sentry.io, or deploy your own [on-premise Sentry instance](https://github.com/getsentry/self-hosted).
1. [Create a new Sentry project](https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/).
For each GitLab project that you want to integrate, create a new Sentry project.
1. Find or generate a [Sentry auth token](https://docs.sentry.io/api/auth/#auth-tokens).
For the SaaS version of Sentry, you can find or generate the auth token at [https://sentry.io/api/](https://sentry.io/api/).
Give the token at least the following scopes: `project:read`, `event:read`, and
`event:write` (for resolving events).
1. In GitLab, enable and configure Error Tracking:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**, then expand **Error Tracking**.
1. For **Enable error tracking**, select **Active**.
1. For **Error tracking backend**, select **Sentry**.
1. For **Sentry API URL**, enter your Sentry hostname. For example,
enter `https://sentry.example.com`.
For the SaaS version of Sentry, the hostname is `https://sentry.io`.
For the SaaS version of Sentry hosted in the EU, the hostname is `https://de.sentry.io`.
1. For **Auth Token**, enter the token you generated previously.
1. To test the connection to Sentry and populate the **Project** dropdown list,
select **Connect**.
1. From the **Project** list, choose a Sentry project to link to your GitLab project.
1. Select **Save changes**.
To view a list of Sentry errors, on your project's sidebar, go to **Monitor > Error Tracking**.
## Enable Sentry's integration with GitLab
You might also want to enable Sentry's GitLab integration by following the steps
in the [Sentry documentation](https://docs.sentry.io/organization/integrations/source-code-mgmt/gitlab/).
## Troubleshooting
When working with Error Tracking, you might encounter the following issues.
### Error `Connection failed. Check auth token and try again`
If the **Monitor** feature is disabled in the
[project settings](../user/project/settings/_index.md#configure-project-features-and-permissions),
you might see an error when you try to [enable Sentry integration for a project](#enable-sentry-integration-for-a-project).
The resulting request to `/project/path/-/error_tracking/projects.json?api_host=https:%2F%2Fsentry.example.com%2F&token=<token>` returns a 404 error.
To fix this issue, enable the **Monitor** feature for the project.
### Error `Connection has failed. Re-check Auth Token and try again`
On-premise Sentry integrations may encounter this issue when attempting to connect.
To fix this issue:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Network**.
1. Expand **Outbound requests**.
1. Select the **Allow requests to the local network from webhooks and integrations** and **Allow requests to the local network from system hooks** checkboxes.
1. Select **Save changes**.
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Sentry error tracking
breadcrumbs:
- doc
- operations
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Sentry](https://sentry.io/) is an open source error tracking system. GitLab enables
administrators to connect Sentry to GitLab, so users can view a list of Sentry errors in GitLab.
GitLab integrates with both the cloud-hosted [Sentry](https://sentry.io) and Sentry
deployed in your [on-premise instance](https://github.com/getsentry/self-hosted).
## Enable Sentry integration for a project
GitLab provides a way to connect Sentry to your project.
Prerequisites:
- You must have at least the Maintainer role for the project.
To enable the Sentry integration:
1. Sign up to Sentry.io, or deploy your own [on-premise Sentry instance](https://github.com/getsentry/self-hosted).
1. [Create a new Sentry project](https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/).
For each GitLab project that you want to integrate, create a new Sentry project.
1. Find or generate a [Sentry auth token](https://docs.sentry.io/api/auth/#auth-tokens).
For the SaaS version of Sentry, you can find or generate the auth token at [https://sentry.io/api/](https://sentry.io/api/).
Give the token at least the following scopes: `project:read`, `event:read`, and
`event:write` (for resolving events).
1. In GitLab, enable and configure Error Tracking:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**, then expand **Error Tracking**.
1. For **Enable error tracking**, select **Active**.
1. For **Error tracking backend**, select **Sentry**.
1. For **Sentry API URL**, enter your Sentry hostname. For example,
enter `https://sentry.example.com`.
For the SaaS version of Sentry, the hostname is `https://sentry.io`.
For the SaaS version of Sentry hosted in the EU, the hostname is `https://de.sentry.io`.
1. For **Auth Token**, enter the token you generated previously.
1. To test the connection to Sentry and populate the **Project** dropdown list,
select **Connect**.
1. From the **Project** list, choose a Sentry project to link to your GitLab project.
1. Select **Save changes**.
To view a list of Sentry errors, on your project's sidebar, go to **Monitor > Error Tracking**.
## Enable Sentry's integration with GitLab
You might also want to enable Sentry's GitLab integration by following the steps
in the [Sentry documentation](https://docs.sentry.io/organization/integrations/source-code-mgmt/gitlab/).
## Troubleshooting
When working with Error Tracking, you might encounter the following issues.
### Error `Connection failed. Check auth token and try again`
If the **Monitor** feature is disabled in the
[project settings](../user/project/settings/_index.md#configure-project-features-and-permissions),
you might see an error when you try to [enable Sentry integration for a project](#enable-sentry-integration-for-a-project).
The resulting request to `/project/path/-/error_tracking/projects.json?api_host=https:%2F%2Fsentry.example.com%2F&token=<token>` returns a 404 error.
To fix this issue, enable the **Monitor** feature for the project.
### Error `Connection has failed. Re-check Auth Token and try again`
On-premise Sentry integrations may encounter this issue when attempting to connect.
To fix this issue:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Network**.
1. Expand **Outbound requests**.
1. Select the **Allow requests to the local network from webhooks and integrations** and **Allow requests to the local network from system hooks** checkboxes.
1. Select **Save changes**.
|
https://docs.gitlab.com/observability
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/observability.md
|
2025-08-13
|
doc/operations
|
[
"doc",
"operations"
] |
observability.md
|
none
|
Embody
|
This page is owned by https://handbook.gitlab.com/handbook/ceo/office-of-the-ceo/embody-team/
|
Observability
|
Monitor application performance and troubleshoot performance issues.
|
{{< details >}}
- Tier: Free
- Offering: GitLab Self-Managed
- Status: Experimental
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/experimental-observability/documentation/-/issues/6) in GitLab 18.1. This feature is an [experiment](../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
Use GitLab Observability (O11y) to:
- Monitor application performance through a unified observability dashboard.
- View distributed traces, logs, and metrics in a single platform.
- Identify and troubleshoot performance bottlenecks in your applications.
{{< alert type="disclaimer" />}}
By adding observability to GitLab itself users can gain [these (planned) features](https://gitlab.com/gitlab-org/embody-team/experimental-observability/gitlab_o11y/-/issues/8).
<i class="fa-youtube-play" aria-hidden="true"></i>
For an overview, see [GitLab Experimental Observability (O11y) Introduction](https://www.youtube.com/watch?v=XI9ZruyNEgs).
<!-- Video published on 2025-06-18 -->
Join the conversation about interesting ways to use GitLab O11y in the GitLab O11y [Discord channel](https://discord.com/channels/778180511088640070/1379585187909861546).
## Why GitLab Observability
- **Cost-effective open source model**: Only pay for compute resources rather than per-seat licensing, making observability accessible for teams of any size. Contribute features and fixes directly, helping ensure the platform evolves to meet your specific needs.
- **Simplified access management**: New engineers automatically gain access to production observability data when they receive code repository access, helping eliminate lengthy provisioning processes. This unified access model helps ensure team members can immediately contribute to troubleshooting and monitoring efforts without administrative delays.
- **Enhanced development workflow**: Developers can correlate code changes directly with application performance metrics, helping to more easily identify when deployments introduce issues. This tight integration between code commits and runtime behavior accelerates debugging and reduces mean time to resolution.
- **Shift-left observability**: Teams can catch performance issues and anomalies earlier in the development cycle, by integrating observability data into their development process. This proactive approach reduces the cost and impact of fixing problems. The open source nature can make it easier and more cost-effective to orchestrate comprehensive staging environments that mirror production observability.
- **Streamlined incident response**: When issues occur, teams can more quickly have context about recent deployments, code changes, and the developers involved, helping with faster triage and resolution. The integration provides a single pane of glass for both code and operational data.
- **Data next to decisions**: Real-time performance metrics and user behavior data become accessible in the development environment, helping teams make informed decisions about feature prioritization, technical debt, and optimization efforts.
- **Compliance and audit trails**: The integration creates comprehensive audit trails that link code changes to system behavior, which can be valuable for compliance requirements and post-incident analysis.
- **Reduced tool switching**: Your development teams can access monitoring data, alerts, and performance insights without leaving their familiar GitLab environment, helping to improve productivity and reduce cognitive overhead.
## Set up a GitLab Observability instance
Observability data is collected in a separate application outside of your GitLab.com instance. Problems with your GitLab instance do not impact collecting or viewing your observability data and vice-versa.
Prerequisites:
- You must have an EC2 instance or similar virtual machine with:
- Minimum: t3.large (2 vCPU, 8 GB RAM).
- Recommended: t3.xlarge (4 vCPU, 16 GB RAM) for production use.
- At least 100 GB storage space.
- Docker and Docker Compose must be installed.
- Your GitLab version must be 18.1 or later
- Your GitLab instance must be connected to the Observability instance.
### Provision server and storage
For AWS EC2:
1. Launch an EC2 instance with at least 2 vCPU and 8 GB RAM.
1. Add an EBS volume of at least 100 GB.
1. Connect to your instance using SSH.
### Mount storage volume
```shell
sudo mkdir -p /mnt/data
sudo mount /dev/xvdbb /mnt/data # Replace xvdbb with your volume name
sudo chown -R $(whoami):$(whoami) /mnt/data
```
For permanent mounting, add to `/etc/fstab`:
```shell
echo '/dev/xvdbb /mnt/data ext4 defaults,nofail 0 2' | sudo tee -a /etc/fstab
```
### Install Docker
For Ubuntu/Debian:
```shell
sudo apt update
sudo apt install -y docker.io docker-compose
sudo systemctl enable docker
sudo systemctl start docker
sudo usermod -aG docker $(whoami)
```
For Amazon Linux:
```shell
sudo dnf update
sudo dnf install -y docker
sudo systemctl enable docker
sudo systemctl start docker
sudo usermod -aG docker $(whoami)
```
Log out and log back in, or run:
```shell
newgrp docker
```
### Configure Docker to use the mounted volume
```shell
sudo mkdir -p /mnt/data/docker
sudo bash -c 'cat > /etc/docker/daemon.json << EOF
{
"data-root": "/mnt/data/docker"
}
EOF'
sudo systemctl restart docker
```
Verify with:
```shell
docker info | grep "Docker Root Dir"
```
### Install GitLab Observability
```shell
cd /mnt/data
git clone -b main https://gitlab.com/gitlab-org/embody-team/experimental-observability/gitlab_o11y.git
cd gitlab_o11y/deploy/docker
docker-compose up -d
```
If you encounter timeout errors, use:
```shell
COMPOSE_HTTP_TIMEOUT=300 docker-compose up -d
```
### Optional: Use an external ClickHouse database
If you'd prefer, you can use your own ClickHouse database.
Prerequisites:
- Ensure your external ClickHouse instance is accessible and properly configured with
any required authentication credentials.
Before you run `docker-compose up -d`, complete the following steps:
1. Open `docker-compose.yml` file.
1. Open `docker-compose.yml` and comment out:
- The `clickhouse` and `zookeeper` services.
- The `x-clickhouse-defaults` and `x-clickhouse-depend` sections.
1. Replace all occurrences of `clickhouse:9000` with your relevant ClickHouse endpoint and TCP port (for example, `my-clickhouse.example.com:9000`) in the following files. If your ClickHouse instance requires authentication, you may also need to update connection strings to include credentials:
- `docker-compose.yml`
- `otel-collector-config.yaml`
- `prometheus-config.yml`
### Configure network access for GitLab Observability
To properly receive telemetry data, you need to open specific ports in your GitLab O11y instance's security group:
1. Go to **AWS Console > EC2 > Security Groups**.
1. Select the security group attached to your GitLab O11y instance.
1. Select **Edit inbound rules**.
1. Add the following rules:
- Type: Custom TCP, Port: 8080, Source: Your IP or 0.0.0.0/0 (for UI access)
- Type: Custom TCP, Port: 4317, Source: Your IP or 0.0.0.0/0 (for OTLP gRPC)
- Type: Custom TCP, Port: 4318, Source: Your IP or 0.0.0.0/0 (for OTLP HTTP)
- Type: Custom TCP, Port: 9411, Source: Your IP or 0.0.0.0/0 (for Zipkin - optional)
- Type: Custom TCP, Port: 14268, Source: Your IP or 0.0.0.0/0 (for Jaeger HTTP - optional)
- Type: Custom TCP, Port: 14250, Source: Your IP or 0.0.0.0/0 (for Jaeger gRPC - optional)
1. Select **Save rules**.
### Access GitLab Observability
Access the GitLab O11y UI at:
```plaintext
http://[your-instance-ip]:8080
```
## Connect GitLab to GitLab Observability
### Configure GitLab and Enable the feature flag
Configure the GitLab O11y URL for your group and enable the feature flag using the Rails console:
1. Access the Rails console:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rails console
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it gitlab gitlab-rails console
```
{{< /tab >}}
{{< /tabs >}}
1. Configure the observability settings for your group and enable the feature flag:
```ruby
group = Group.find_by_path('your-group-name')
Observability::GroupO11ySetting.create!(
group_id: group.id,
o11y_service_url: 'your-o11y-instance-url',
o11y_service_user_email: 'your-email@example.com',
o11y_service_password: 'your-secure-password',
o11y_service_post_message_encryption_key: 'your-super-secret-encryption-key-here-32-chars-minimum'
)
Feature.enable(:observability_sass_features, group)
Feature.enabled?(:observability_sass_features, group)
```
Replace:
- `your-group-name` with your actual group path
- `your-o11y-instance-url` with your GitLab O11y instance URL (for example: `http://192.168.1.100:8080`)
- Email and password with your preferred credentials
- Encryption key with a secure 32+ character string
The last command should return `true` to confirm the feature is enabled.
## Use Observability with GitLab
After you have configured GitLab O11y, to access the dashboard embedded in GitLab:
1. On the left sidebar, select **Search or go to** and find your group where the feature flag is enabled.
1. On the left sidebar, select **Observability**.
If **Observability** isn't displayed on the left sidebar,
go directly to `http://<gitlab_instance>/groups/<group_path>/-/observability/services`.

## Send telemetry data to GitLab Observability
You can test your GitLab O11y installation by sending sample telemetry data using the OpenTelemetry SDK. This example uses Ruby, but OpenTelemetry has SDKs for many languages.
Prerequisites:
- Ruby installed on your local machine
- Required gems:
```shell
gem install opentelemetry-sdk opentelemetry-exporter-otlp
```
### Create a basic test script
Create a file named `test_o11y.rb` with the following content:
```ruby
require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
OpenTelemetry::SDK.configure do |c|
# Define service information
resource = OpenTelemetry::SDK::Resources::Resource.create({
'service.name' => 'test-service',
'service.version' => '1.0.0',
'deployment.environment' => 'production'
})
c.resource = resource
# Configure OTLP exporter to send to GitLab O11y
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::Exporter::OTLP::Exporter.new(
endpoint: 'http://[your-o11y-instance-ip]:4318/v1/traces'
)
)
)
end
# Get tracer and create spans
tracer = OpenTelemetry.tracer_provider.tracer('basic-demo')
# Create parent span
tracer.in_span('parent-operation') do |parent|
parent.set_attribute('custom.attribute', 'test-value')
puts "Created parent span: #{parent.context.hex_span_id}"
# Create child span
tracer.in_span('child-operation') do |child|
child.set_attribute('custom.child', 'child-value')
puts "Created child span: #{child.context.hex_span_id}"
sleep(1)
end
end
puts "Waiting for export..."
sleep(5)
puts "Done!"
```
Replace `[your-o11y-instance-ip]` with your GitLab O11y instance's IP address or hostname.
### Run the test
1. Run the script:
```shell
ruby test_o11y.rb
```
1. Check your GitLab O11y dashboard:
- Open `http://[your-o11y-instance-ip]:8080`
- Go to the "Services" section
- Look for the "test-service" service
- Select on it to see traces and spans
## Instrument your application
To add OpenTelemetry instrumentation to your applications:
1. Add the OpenTelemetry SDK for your language.
1. Configure the OTLP exporter to point to your GitLab O11y instance.
1. Add spans and attributes to track operations and metadata.
Refer to the [OpenTelemetry documentation](https://opentelemetry.io/docs/instrumentation/) for language-specific guidelines.
## GitLab Observability Templates
GitLab provides pre-built dashboard templates to help you get started with observability quickly. These templates are available at [Experimental Observability O11y Templates](https://gitlab.com/gitlab-org/embody-team/experimental-observability/o11y-templates/).
### Available templates
**Standard OpenTelemetry dashboards**: If you instrument your application with standard OpenTelemetry libraries, you can use these plug-and-play dashboard templates:
- Application performance monitoring dashboards
- Service dependency visualizations
- Error rate and latency tracking
**GitLab-specific dashboards**: When you send GitLab OpenTelemetry data to your GitLab O11y instance, use these dashboards for out-of-the-box insights:
- GitLab application performance metrics
- GitLab service health monitoring
- GitLab-specific trace analysis
**CI/CD observability**: The repository includes an example GitLab CI/CD pipeline with OpenTelemetry instrumentation that works with the GitLab O11y CI/CD dashboard template JSON file. This helps you monitor your CI/CD pipeline performance and identify bottlenecks.
### Using the templates
1. Clone or download the templates from the repository.
1. Update the service name in the example application dashboards to match your service name.
1. Import the JSON files into your GitLab O11y instance.
1. Configure your applications to send telemetry data using standard OpenTelemetry libraries as described in the [Instrument your application](#instrument-your-application) section.
1. The dashboards are now available with your application's telemetry data in GitLab O11y.
## Troubleshooting
### GitLab Observability instance issues
Check container status:
```shell
docker ps
```
View container logs:
```shell
docker logs [container_name]
```
### Menu doesn't appear
1. Verify the feature flag is enabled for your group:
```ruby
Feature.enabled?(:observability_sass_features, Group.find_by_path('your-group-name'))
```
1. Check that the O11Y_URL environment variable is set:
```ruby
group = Group.find_by_path('your-group-name')
group.observability_group_o11y_setting&.o11y_service_url
```
1. Ensure the routes are properly registered:
```ruby
Rails.application.routes.routes.select { |r| r.path.spec.to_s.include?('observability') }.map(&:path)
```
### Performance issues
If experiencing SSH connection issues or poor performance:
- Verify instance type meets minimum requirements (2 vCPU, 8 GB RAM)
- Consider resizing to a larger instance type
- Check disk space and increase if needed
### Telemetry doesn't show up
If your telemetry data isn't appearing in GitLab O11y:
1. Verify ports 4317 and 4318 are open in your security group.
1. Test connectivity with:
```shell
nc -zv [your-o11y-instance-ip] 4317
nc -zv [your-o11y-instance-ip] 4318
```
1. Check container logs for any errors:
```shell
docker logs otel-collector-standard
docker logs o11y-otel-collector
docker logs o11y
```
1. Try using the HTTP endpoint (4318) instead of gRPC (4317).
1. Add more debugging information to your OpenTelemetry setup.
|
---
stage: none
group: Embody
info: This page is owned by https://handbook.gitlab.com/handbook/ceo/office-of-the-ceo/embody-team/
description: Monitor application performance and troubleshoot performance issues.
ignore_in_report: true
title: Observability
breadcrumbs:
- doc
- operations
---
{{< details >}}
- Tier: Free
- Offering: GitLab Self-Managed
- Status: Experimental
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/experimental-observability/documentation/-/issues/6) in GitLab 18.1. This feature is an [experiment](../policy/development_stages_support.md).
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
Use GitLab Observability (O11y) to:
- Monitor application performance through a unified observability dashboard.
- View distributed traces, logs, and metrics in a single platform.
- Identify and troubleshoot performance bottlenecks in your applications.
{{< alert type="disclaimer" />}}
By adding observability to GitLab itself users can gain [these (planned) features](https://gitlab.com/gitlab-org/embody-team/experimental-observability/gitlab_o11y/-/issues/8).
<i class="fa-youtube-play" aria-hidden="true"></i>
For an overview, see [GitLab Experimental Observability (O11y) Introduction](https://www.youtube.com/watch?v=XI9ZruyNEgs).
<!-- Video published on 2025-06-18 -->
Join the conversation about interesting ways to use GitLab O11y in the GitLab O11y [Discord channel](https://discord.com/channels/778180511088640070/1379585187909861546).
## Why GitLab Observability
- **Cost-effective open source model**: Only pay for compute resources rather than per-seat licensing, making observability accessible for teams of any size. Contribute features and fixes directly, helping ensure the platform evolves to meet your specific needs.
- **Simplified access management**: New engineers automatically gain access to production observability data when they receive code repository access, helping eliminate lengthy provisioning processes. This unified access model helps ensure team members can immediately contribute to troubleshooting and monitoring efforts without administrative delays.
- **Enhanced development workflow**: Developers can correlate code changes directly with application performance metrics, helping to more easily identify when deployments introduce issues. This tight integration between code commits and runtime behavior accelerates debugging and reduces mean time to resolution.
- **Shift-left observability**: Teams can catch performance issues and anomalies earlier in the development cycle, by integrating observability data into their development process. This proactive approach reduces the cost and impact of fixing problems. The open source nature can make it easier and more cost-effective to orchestrate comprehensive staging environments that mirror production observability.
- **Streamlined incident response**: When issues occur, teams can more quickly have context about recent deployments, code changes, and the developers involved, helping with faster triage and resolution. The integration provides a single pane of glass for both code and operational data.
- **Data next to decisions**: Real-time performance metrics and user behavior data become accessible in the development environment, helping teams make informed decisions about feature prioritization, technical debt, and optimization efforts.
- **Compliance and audit trails**: The integration creates comprehensive audit trails that link code changes to system behavior, which can be valuable for compliance requirements and post-incident analysis.
- **Reduced tool switching**: Your development teams can access monitoring data, alerts, and performance insights without leaving their familiar GitLab environment, helping to improve productivity and reduce cognitive overhead.
## Set up a GitLab Observability instance
Observability data is collected in a separate application outside of your GitLab.com instance. Problems with your GitLab instance do not impact collecting or viewing your observability data and vice-versa.
Prerequisites:
- You must have an EC2 instance or similar virtual machine with:
- Minimum: t3.large (2 vCPU, 8 GB RAM).
- Recommended: t3.xlarge (4 vCPU, 16 GB RAM) for production use.
- At least 100 GB storage space.
- Docker and Docker Compose must be installed.
- Your GitLab version must be 18.1 or later
- Your GitLab instance must be connected to the Observability instance.
### Provision server and storage
For AWS EC2:
1. Launch an EC2 instance with at least 2 vCPU and 8 GB RAM.
1. Add an EBS volume of at least 100 GB.
1. Connect to your instance using SSH.
### Mount storage volume
```shell
sudo mkdir -p /mnt/data
sudo mount /dev/xvdbb /mnt/data # Replace xvdbb with your volume name
sudo chown -R $(whoami):$(whoami) /mnt/data
```
For permanent mounting, add to `/etc/fstab`:
```shell
echo '/dev/xvdbb /mnt/data ext4 defaults,nofail 0 2' | sudo tee -a /etc/fstab
```
### Install Docker
For Ubuntu/Debian:
```shell
sudo apt update
sudo apt install -y docker.io docker-compose
sudo systemctl enable docker
sudo systemctl start docker
sudo usermod -aG docker $(whoami)
```
For Amazon Linux:
```shell
sudo dnf update
sudo dnf install -y docker
sudo systemctl enable docker
sudo systemctl start docker
sudo usermod -aG docker $(whoami)
```
Log out and log back in, or run:
```shell
newgrp docker
```
### Configure Docker to use the mounted volume
```shell
sudo mkdir -p /mnt/data/docker
sudo bash -c 'cat > /etc/docker/daemon.json << EOF
{
"data-root": "/mnt/data/docker"
}
EOF'
sudo systemctl restart docker
```
Verify with:
```shell
docker info | grep "Docker Root Dir"
```
### Install GitLab Observability
```shell
cd /mnt/data
git clone -b main https://gitlab.com/gitlab-org/embody-team/experimental-observability/gitlab_o11y.git
cd gitlab_o11y/deploy/docker
docker-compose up -d
```
If you encounter timeout errors, use:
```shell
COMPOSE_HTTP_TIMEOUT=300 docker-compose up -d
```
### Optional: Use an external ClickHouse database
If you'd prefer, you can use your own ClickHouse database.
Prerequisites:
- Ensure your external ClickHouse instance is accessible and properly configured with
any required authentication credentials.
Before you run `docker-compose up -d`, complete the following steps:
1. Open `docker-compose.yml` file.
1. Open `docker-compose.yml` and comment out:
- The `clickhouse` and `zookeeper` services.
- The `x-clickhouse-defaults` and `x-clickhouse-depend` sections.
1. Replace all occurrences of `clickhouse:9000` with your relevant ClickHouse endpoint and TCP port (for example, `my-clickhouse.example.com:9000`) in the following files. If your ClickHouse instance requires authentication, you may also need to update connection strings to include credentials:
- `docker-compose.yml`
- `otel-collector-config.yaml`
- `prometheus-config.yml`
### Configure network access for GitLab Observability
To properly receive telemetry data, you need to open specific ports in your GitLab O11y instance's security group:
1. Go to **AWS Console > EC2 > Security Groups**.
1. Select the security group attached to your GitLab O11y instance.
1. Select **Edit inbound rules**.
1. Add the following rules:
- Type: Custom TCP, Port: 8080, Source: Your IP or 0.0.0.0/0 (for UI access)
- Type: Custom TCP, Port: 4317, Source: Your IP or 0.0.0.0/0 (for OTLP gRPC)
- Type: Custom TCP, Port: 4318, Source: Your IP or 0.0.0.0/0 (for OTLP HTTP)
- Type: Custom TCP, Port: 9411, Source: Your IP or 0.0.0.0/0 (for Zipkin - optional)
- Type: Custom TCP, Port: 14268, Source: Your IP or 0.0.0.0/0 (for Jaeger HTTP - optional)
- Type: Custom TCP, Port: 14250, Source: Your IP or 0.0.0.0/0 (for Jaeger gRPC - optional)
1. Select **Save rules**.
### Access GitLab Observability
Access the GitLab O11y UI at:
```plaintext
http://[your-instance-ip]:8080
```
## Connect GitLab to GitLab Observability
### Configure GitLab and Enable the feature flag
Configure the GitLab O11y URL for your group and enable the feature flag using the Rails console:
1. Access the Rails console:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rails console
```
{{< /tab >}}
{{< tab title="Docker" >}}
```shell
docker exec -it gitlab gitlab-rails console
```
{{< /tab >}}
{{< /tabs >}}
1. Configure the observability settings for your group and enable the feature flag:
```ruby
group = Group.find_by_path('your-group-name')
Observability::GroupO11ySetting.create!(
group_id: group.id,
o11y_service_url: 'your-o11y-instance-url',
o11y_service_user_email: 'your-email@example.com',
o11y_service_password: 'your-secure-password',
o11y_service_post_message_encryption_key: 'your-super-secret-encryption-key-here-32-chars-minimum'
)
Feature.enable(:observability_sass_features, group)
Feature.enabled?(:observability_sass_features, group)
```
Replace:
- `your-group-name` with your actual group path
- `your-o11y-instance-url` with your GitLab O11y instance URL (for example: `http://192.168.1.100:8080`)
- Email and password with your preferred credentials
- Encryption key with a secure 32+ character string
The last command should return `true` to confirm the feature is enabled.
## Use Observability with GitLab
After you have configured GitLab O11y, to access the dashboard embedded in GitLab:
1. On the left sidebar, select **Search or go to** and find your group where the feature flag is enabled.
1. On the left sidebar, select **Observability**.
If **Observability** isn't displayed on the left sidebar,
go directly to `http://<gitlab_instance>/groups/<group_path>/-/observability/services`.

## Send telemetry data to GitLab Observability
You can test your GitLab O11y installation by sending sample telemetry data using the OpenTelemetry SDK. This example uses Ruby, but OpenTelemetry has SDKs for many languages.
Prerequisites:
- Ruby installed on your local machine
- Required gems:
```shell
gem install opentelemetry-sdk opentelemetry-exporter-otlp
```
### Create a basic test script
Create a file named `test_o11y.rb` with the following content:
```ruby
require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
OpenTelemetry::SDK.configure do |c|
# Define service information
resource = OpenTelemetry::SDK::Resources::Resource.create({
'service.name' => 'test-service',
'service.version' => '1.0.0',
'deployment.environment' => 'production'
})
c.resource = resource
# Configure OTLP exporter to send to GitLab O11y
c.add_span_processor(
OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
OpenTelemetry::Exporter::OTLP::Exporter.new(
endpoint: 'http://[your-o11y-instance-ip]:4318/v1/traces'
)
)
)
end
# Get tracer and create spans
tracer = OpenTelemetry.tracer_provider.tracer('basic-demo')
# Create parent span
tracer.in_span('parent-operation') do |parent|
parent.set_attribute('custom.attribute', 'test-value')
puts "Created parent span: #{parent.context.hex_span_id}"
# Create child span
tracer.in_span('child-operation') do |child|
child.set_attribute('custom.child', 'child-value')
puts "Created child span: #{child.context.hex_span_id}"
sleep(1)
end
end
puts "Waiting for export..."
sleep(5)
puts "Done!"
```
Replace `[your-o11y-instance-ip]` with your GitLab O11y instance's IP address or hostname.
### Run the test
1. Run the script:
```shell
ruby test_o11y.rb
```
1. Check your GitLab O11y dashboard:
- Open `http://[your-o11y-instance-ip]:8080`
- Go to the "Services" section
- Look for the "test-service" service
- Select on it to see traces and spans
## Instrument your application
To add OpenTelemetry instrumentation to your applications:
1. Add the OpenTelemetry SDK for your language.
1. Configure the OTLP exporter to point to your GitLab O11y instance.
1. Add spans and attributes to track operations and metadata.
Refer to the [OpenTelemetry documentation](https://opentelemetry.io/docs/instrumentation/) for language-specific guidelines.
## GitLab Observability Templates
GitLab provides pre-built dashboard templates to help you get started with observability quickly. These templates are available at [Experimental Observability O11y Templates](https://gitlab.com/gitlab-org/embody-team/experimental-observability/o11y-templates/).
### Available templates
**Standard OpenTelemetry dashboards**: If you instrument your application with standard OpenTelemetry libraries, you can use these plug-and-play dashboard templates:
- Application performance monitoring dashboards
- Service dependency visualizations
- Error rate and latency tracking
**GitLab-specific dashboards**: When you send GitLab OpenTelemetry data to your GitLab O11y instance, use these dashboards for out-of-the-box insights:
- GitLab application performance metrics
- GitLab service health monitoring
- GitLab-specific trace analysis
**CI/CD observability**: The repository includes an example GitLab CI/CD pipeline with OpenTelemetry instrumentation that works with the GitLab O11y CI/CD dashboard template JSON file. This helps you monitor your CI/CD pipeline performance and identify bottlenecks.
### Using the templates
1. Clone or download the templates from the repository.
1. Update the service name in the example application dashboards to match your service name.
1. Import the JSON files into your GitLab O11y instance.
1. Configure your applications to send telemetry data using standard OpenTelemetry libraries as described in the [Instrument your application](#instrument-your-application) section.
1. The dashboards are now available with your application's telemetry data in GitLab O11y.
## Troubleshooting
### GitLab Observability instance issues
Check container status:
```shell
docker ps
```
View container logs:
```shell
docker logs [container_name]
```
### Menu doesn't appear
1. Verify the feature flag is enabled for your group:
```ruby
Feature.enabled?(:observability_sass_features, Group.find_by_path('your-group-name'))
```
1. Check that the O11Y_URL environment variable is set:
```ruby
group = Group.find_by_path('your-group-name')
group.observability_group_o11y_setting&.o11y_service_url
```
1. Ensure the routes are properly registered:
```ruby
Rails.application.routes.routes.select { |r| r.path.spec.to_s.include?('observability') }.map(&:path)
```
### Performance issues
If experiencing SSH connection issues or poor performance:
- Verify instance type meets minimum requirements (2 vCPU, 8 GB RAM)
- Consider resizing to a larger instance type
- Check disk space and increase if needed
### Telemetry doesn't show up
If your telemetry data isn't appearing in GitLab O11y:
1. Verify ports 4317 and 4318 are open in your security group.
1. Test connectivity with:
```shell
nc -zv [your-o11y-instance-ip] 4317
nc -zv [your-o11y-instance-ip] 4318
```
1. Check container logs for any errors:
```shell
docker logs otel-collector-standard
docker logs o11y-otel-collector
docker logs o11y
```
1. Try using the HTTP endpoint (4318) instead of gRPC (4317).
1. Add more debugging information to your OpenTelemetry setup.
|
https://docs.gitlab.com/operations/incident_timeline_events
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/operations/incident_timeline_events.md
|
2025-08-13
|
doc/operations/incident_management
|
[
"doc",
"operations",
"incident_management"
] |
incident_timeline_events.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Timeline events
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/344059) in GitLab 15.2 [with a flag](../../administration/feature_flags/_index.md) named `incident_timeline`. Enabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/353426) in GitLab 15.3.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/353426) in GitLab 15.5. [Feature flag `incident_timeline`](https://gitlab.com/gitlab-org/gitlab/-/issues/343386) removed.
{{< /history >}}
Incident timelines are an important part of record keeping for incidents.
Timelines can show executives and external viewers what happened during an incident,
and which steps were taken for it to be resolved.
## View the timeline
Incident timeline events are listed in ascending order of the date and time.
They are grouped with dates and are listed in ascending order of the time when they occurred:

To view the event timeline of an incident:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
## Create an event
You can create a timeline event in many ways in GitLab.
### Using the form
Create a timeline event manually using the form.
Prerequisites:
- You must have at least the Developer role for the project.
To create a timeline event:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
1. Select **Add new timeline event**.
1. Complete the required fields.
1. Select **Save** or **Save and add another event**.
### Using a quick action
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/368721) in GitLab 15.4.
{{< /history >}}
You can create a timeline event using the `/timeline` [quick action](../../user/project/quick_actions.md).
### From a comment on the incident
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/344058) in GitLab 15.4.
{{< /history >}}
Prerequisites:
- You must have at least the Developer role for the project.
{{< alert type="warning" >}}
Internal notes added to incident timelines in public and internal
incidents are visible to anyone with access to the incident.
{{< /alert >}}
To create a timeline event from a comment on the incident:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Create a comment or choose an existing comment.
1. On the comment you want to add, select **Add comment to incident timeline** ({{< icon name="clock" >}}).
The comment is shown on the incident timeline as a timeline event.
### When incident severity changes
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/375280) in GitLab 15.6.
{{< /history >}}
A new timeline event is created when someone [changes the severity](manage_incidents.md#change-severity)
of an incident.

### When labels change
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365489) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `incident_timeline_events_from_labels`. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
A new timeline event is created when someone adds or removes [labels](../../user/project/labels.md) on an incident.
## Delete an event
{{< history >}}
- Ability to delete an event when editing it [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/372265) in GitLab 15.7.
{{< /history >}}
You can also delete timeline events.
Prerequisites:
- You must have at least the Developer role for the project.
To delete a timeline event:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
1. On the right of a timeline event, select **More actions** ({{< icon name="ellipsis_v" >}}) and then select **Delete**.
1. To confirm, select **Delete Event**.
Alternatively:
1. On the right of a timeline event, select **More actions** ({{< icon name="ellipsis_v" >}}) and then select **Edit**.
1. Select **Delete**.
1. To confirm, select **Delete event**.
## Incident tags
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/8741) in GitLab 15.9 [with a flag](../../administration/feature_flags/_index.md) named `incident_event_tags`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.9.
- [Enabled on GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.10.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.11. Feature flag `incident_event_tags` removed.
{{< /history >}}
[When creating an event using the form](#using-the-form) or editing it,
you can specify incident tags to capture relevant incident timestamps.
Timeline tags are optional. You can choose more than one tag per event.
When you create a timeline event and select the tags, the event note
is populated with a default message.
This allows for a quick event creation. If a note has already been set, it isn't changed.
Added tags are displayed next to the timestamp.
## Formatting rules
Incident timeline events support the following [GitLab Flavored Markdown](../../user/markdown.md) features.
- [Code](../../user/markdown.md#code-spans-and-blocks).
- [Emoji](../../user/markdown.md#emoji).
- [Emphasis](../../user/markdown.md#emphasis).
- [GitLab-specific references](../../user/markdown.md#gitlab-specific-references).
- [Images](../../user/markdown.md#images), rendered as a link to the uploaded image.
- [Links](../../user/markdown.md#links).
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Timeline events
breadcrumbs:
- doc
- operations
- incident_management
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/344059) in GitLab 15.2 [with a flag](../../administration/feature_flags/_index.md) named `incident_timeline`. Enabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/353426) in GitLab 15.3.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/353426) in GitLab 15.5. [Feature flag `incident_timeline`](https://gitlab.com/gitlab-org/gitlab/-/issues/343386) removed.
{{< /history >}}
Incident timelines are an important part of record keeping for incidents.
Timelines can show executives and external viewers what happened during an incident,
and which steps were taken for it to be resolved.
## View the timeline
Incident timeline events are listed in ascending order of the date and time.
They are grouped with dates and are listed in ascending order of the time when they occurred:

To view the event timeline of an incident:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
## Create an event
You can create a timeline event in many ways in GitLab.
### Using the form
Create a timeline event manually using the form.
Prerequisites:
- You must have at least the Developer role for the project.
To create a timeline event:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
1. Select **Add new timeline event**.
1. Complete the required fields.
1. Select **Save** or **Save and add another event**.
### Using a quick action
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/368721) in GitLab 15.4.
{{< /history >}}
You can create a timeline event using the `/timeline` [quick action](../../user/project/quick_actions.md).
### From a comment on the incident
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/344058) in GitLab 15.4.
{{< /history >}}
Prerequisites:
- You must have at least the Developer role for the project.
{{< alert type="warning" >}}
Internal notes added to incident timelines in public and internal
incidents are visible to anyone with access to the incident.
{{< /alert >}}
To create a timeline event from a comment on the incident:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Create a comment or choose an existing comment.
1. On the comment you want to add, select **Add comment to incident timeline** ({{< icon name="clock" >}}).
The comment is shown on the incident timeline as a timeline event.
### When incident severity changes
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/375280) in GitLab 15.6.
{{< /history >}}
A new timeline event is created when someone [changes the severity](manage_incidents.md#change-severity)
of an incident.

### When labels change
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365489) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `incident_timeline_events_from_labels`. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
A new timeline event is created when someone adds or removes [labels](../../user/project/labels.md) on an incident.
## Delete an event
{{< history >}}
- Ability to delete an event when editing it [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/372265) in GitLab 15.7.
{{< /history >}}
You can also delete timeline events.
Prerequisites:
- You must have at least the Developer role for the project.
To delete a timeline event:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select an incident.
1. Select the **Timeline** tab.
1. On the right of a timeline event, select **More actions** ({{< icon name="ellipsis_v" >}}) and then select **Delete**.
1. To confirm, select **Delete Event**.
Alternatively:
1. On the right of a timeline event, select **More actions** ({{< icon name="ellipsis_v" >}}) and then select **Edit**.
1. Select **Delete**.
1. To confirm, select **Delete event**.
## Incident tags
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/8741) in GitLab 15.9 [with a flag](../../administration/feature_flags/_index.md) named `incident_event_tags`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.9.
- [Enabled on GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.10.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/387647) in GitLab 15.11. Feature flag `incident_event_tags` removed.
{{< /history >}}
[When creating an event using the form](#using-the-form) or editing it,
you can specify incident tags to capture relevant incident timestamps.
Timeline tags are optional. You can choose more than one tag per event.
When you create a timeline event and select the tags, the event note
is populated with a default message.
This allows for a quick event creation. If a note has already been set, it isn't changed.
Added tags are displayed next to the timestamp.
## Formatting rules
Incident timeline events support the following [GitLab Flavored Markdown](../../user/markdown.md) features.
- [Code](../../user/markdown.md#code-spans-and-blocks).
- [Emoji](../../user/markdown.md#emoji).
- [Emphasis](../../user/markdown.md#emphasis).
- [GitLab-specific references](../../user/markdown.md#gitlab-specific-references).
- [Images](../../user/markdown.md#images), rendered as a link to the uploaded image.
- [Links](../../user/markdown.md#links).
|
https://docs.gitlab.com/operations/incident_management
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/operations/_index.md
|
2025-08-13
|
doc/operations/incident_management
|
[
"doc",
"operations",
"incident_management"
] |
_index.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Incident management
|
Alert handling, response coordination, and escalation procedures.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="note" >}}
This feature is not under active development, but [community contributions](https://about.gitlab.com/community/contribute/) are welcome.
For more information, see [issue 468607](https://gitlab.com/gitlab-org/gitlab/-/issues/468607#note_1967939452).
To determine if the feature meets your needs, see the [open bug issues](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=updated_desc&state=opened&label_name%5B%5D=Category%3AIncident%20Management&label_name%5B%5D=type%3A%3Abug&first_page_size=20).
{{< /alert >}}
Incident Management enables developers to easily triage and view the alerts and incidents
generated by their application. By surfacing alerts and incidents where the code is
being developed, efficiency and awareness can be increased. Check out the following sections for more information:
- [Integrate your monitoring tools](integrations.md).
- Manage [on-call schedules](oncall_schedules.md) and receive [notifications](paging.md) for
triggered alerts.
- Triage [Alerts](alerts.md) and [Incidents](incidents.md).
- Inform stakeholders with [Status Page](status_page.md).
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Incident management
description: Alert handling, response coordination, and escalation procedures.
breadcrumbs:
- doc
- operations
- incident_management
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="note" >}}
This feature is not under active development, but [community contributions](https://about.gitlab.com/community/contribute/) are welcome.
For more information, see [issue 468607](https://gitlab.com/gitlab-org/gitlab/-/issues/468607#note_1967939452).
To determine if the feature meets your needs, see the [open bug issues](https://gitlab.com/gitlab-org/gitlab/-/issues/?sort=updated_desc&state=opened&label_name%5B%5D=Category%3AIncident%20Management&label_name%5B%5D=type%3A%3Abug&first_page_size=20).
{{< /alert >}}
Incident Management enables developers to easily triage and view the alerts and incidents
generated by their application. By surfacing alerts and incidents where the code is
being developed, efficiency and awareness can be increased. Check out the following sections for more information:
- [Integrate your monitoring tools](integrations.md).
- Manage [on-call schedules](oncall_schedules.md) and receive [notifications](paging.md) for
triggered alerts.
- Triage [Alerts](alerts.md) and [Incidents](incidents.md).
- Inform stakeholders with [Status Page](status_page.md).
|
https://docs.gitlab.com/operations/manage_incidents
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/operations/manage_incidents.md
|
2025-08-13
|
doc/operations/incident_management
|
[
"doc",
"operations",
"incident_management"
] |
manage_incidents.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Manage incidents
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- Ability to add an [incident](_index.md) to an iteration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/347153) in GitLab 17.0.
{{< /history >}}
This page collects instructions for all the things you can do with [incidents](incidents.md) or in relation to them.
## Create an incident
You can create an incident manually or automatically.
## Add an incident to an iteration
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To add an incident to an [iteration](../../user/group/iterations/_index.md):
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Plan > Issues** or **Monitor > Incidents**, then select your incident to view it.
1. On the right sidebar, in the **Iteration** section, select **Edit**.
1. From the dropdown list, select the iteration to add this incident to.
1. Select any area outside the dropdown list.
Alternatively, you can use the `/iteration` [quick action](../../user/project/quick_actions.md#issues-merge-requests-and-epics).
### From the Incidents page
Prerequisites:
- You must have at least the Reporter role for the project.
To create an incident from the **Incidents** page:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select **Create incident**.
### From the Issues page
Prerequisites:
- You must have at least the Reporter role for the project.
To create an incident from the **Issues** page:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Plan > Issues**, and select **New issue**.
1. From the **Type** dropdown list, select **Incident**. Only fields relevant to
incidents are available on the page.
1. Select **Create issue**.
### From an alert
Create an incident issue when viewing an [alert](alerts.md).
The incident description is populated from the alert.
Prerequisites:
- You must have at least the Developer role for the project.
To create an incident from an alert:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Alerts**.
1. Select your desired alert.
1. Select **Create incident**.
After an incident is created, to view it from the alert, select **View incident**.
When you [close an incident](#close-an-incident) linked to an alert, GitLab
[changes the alert's status](alerts.md#change-an-alerts-status) to **Resolved**.
You are then credited with the alert's status change.
### Automatically, when an alert is triggered
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In the project settings, you can turn on [creating an incident automatically](alerts.md#trigger-actions-from-alerts)
whenever an alert is triggered.
### Using the PagerDuty webhook
{{< history >}}
- [PagerDuty V3 Webhook](https://support.pagerduty.com/docs/webhooks) support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383029) in GitLab 15.7.
{{< /history >}}
You can set up a webhook with PagerDuty to automatically create a GitLab incident
for each PagerDuty incident. This configuration requires you to make changes
in both PagerDuty and GitLab.
Prerequisites:
- You must have at least the Maintainer role for the project.
To set up a webhook with PagerDuty:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**
1. Expand **Incidents**.
1. Select the **PagerDuty integration** tab.
1. Turn on the **Active** toggle.
1. Select **Save integration**.
1. Copy the value of **Webhook URL** for use in a later step.
1. To add the webhook URL to a PagerDuty webhook integration, follow the steps described in the [PagerDuty documentation](https://support.pagerduty.com/docs/webhooks#manage-v3-webhook-subscriptions).
To confirm the integration is successful, trigger a test incident from PagerDuty to
check if a GitLab incident is created from the incident.
## View a list of incidents
To view a list of the [incidents](incidents.md#incidents-list):
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
To view an incident's [details page](incidents.md#incident-details), select it from the list.
### Who can view an incident
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/169256) the minimum user role from Reporter to Planner in GitLab 17.7.
{{< /history >}}
Whether you can view an incident depends on the [project visibility level](../../user/public_access.md) and
the incident's confidentiality status:
- Public project and a non-confidential incident: Anyone can view the incident.
- Private project and non-confidential incident: You must have at least the Guest role for the project.
- Confidential incident (regardless of project visibility): You must have at least the Planner role for the project.
## Assign to a user
Assign incidents to users that are actively responding.
Prerequisites:
- You must have at least the Reporter role for the project.
To assign a user:
1. In an incident, on the right sidebar, next to **Assignees**, select **Edit**.
1. From the dropdown list, select one or [multiple users](../../user/project/issues/multiple_assignees_for_issues.md) to add as **assignees**.
1. Select any area outside the dropdown list.
## Change severity
See the [incidents list](incidents.md#incidents-list) topic for a full description of the severity levels available.
Prerequisites:
- You must have at least the Reporter role for the project.
To change an incident's severity:
1. In an incident, on the right sidebar, next to **Severity**, select **Edit**.
1. From the dropdown list, select the new severity.
You can also change the severity using the `/severity` [quick action](../../user/project/quick_actions.md).
## Change status
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/5716) in GitLab 14.9 [with a flag](../../administration/feature_flags/_index.md) named `incident_escalations`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/345769) in GitLab 14.10.
- [Feature flag `incident_escalations`](https://gitlab.com/gitlab-org/gitlab/-/issues/345769) removed in GitLab 15.1.
{{< /history >}}
Prerequisites:
- You must have at least the Developer role for the project.
To change the status of an incident:
1. In an incident, on the right sidebar, next to **Status**, select **Edit**.
1. From the dropdown list, select the new severity.
**Triggered** is the default status for new incidents.
### As an on-call responder
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
On-call responders can respond to [incident pages](paging.md#escalating-an-incident)
by changing the status.
Changing the status has the following effects:
- To **Acknowledged**: limits on-call pages based on the project's [escalation policy](escalation_policies.md).
- To **Resolved**: silences all on-call pages for the incident.
- From **Resolved** to **Triggered**: restarts the incident escalating.
In GitLab 15.1 and earlier, changing the status of an [incident created from an alert](#from-an-alert)
also changes the alert status. In [GitLab 15.2 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/356057),
the alert status is independent and does not change when the incident status changes.
## Change escalation policy
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Prerequisites:
- You must have at least the Developer role for the project.
To change the escalation policy of an incident:
1. In an incident, on the right sidebar, next to **Escalation policy**, select **Edit**.
1. From the dropdown list, select the escalation policy.
By default, new incidents do not have an escalation policy selected.
Selecting an escalation policy [changes the incident status](#change-status) to **Triggered** and begins
[escalating the incident to on-call responders](paging.md#escalating-an-incident).
In GitLab 15.1 and earlier, the escalation policy for [incidents created from alerts](#from-an-alert)
reflects the alert's escalation policy and cannot be changed. In [GitLab 15.2 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/356057),
the incident escalation policy is independent and can be changed.
## Close an incident
Prerequisites:
- You must have at least the Reporter role for the project.
To close an incident, in the upper-right corner, select **Incident actions** ({{< icon name="ellipsis_v" >}}) and then **Close incident**.
When you close an incident that is linked to an [alert](alerts.md),
the linked alert's status changes to **Resolved**.
You are then credited with the alert's status change.
### Automatically close incidents via recovery alerts
Turn on closing an incident automatically when GitLab receives a recovery alert
from an HTTP or Prometheus webhook.
Prerequisites:
- You must have at least the Maintainer role for the project.
To configure the setting:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**.
1. Expand the **Incidents** section.
1. Select the **Automatically close associated incident** checkbox.
1. Select **Save changes**.
When GitLab receives a [recovery alert](integrations.md#recovery-alerts), it closes the associated incident.
This action is recorded as a system note on the incident indicating that it
was closed automatically by the GitLab Alert bot.
## Delete an incident
Prerequisites:
- You must have the Owner role for a project.
To delete an incident:
1. In an incident, select **Incident actions** ({{< icon name="ellipsis_v" >}}).
1. Select **Delete incident**.
Alternatively:
1. In an incident, select **Edit title and description** ({{< icon name="pencil" >}}).
1. Select **Delete incident**.
## Other actions
Because incidents in GitLab are built on top of [issues](../../user/project/issues/_index.md),
they have the following actions in common:
- [Add a to-do item](../../user/todos.md#create-a-to-do-item)
- [Add labels](../../user/project/labels.md#assign-and-unassign-labels)
- [Assign a milestone](../../user/project/milestones/_index.md#assign-a-milestone-to-an-item)
- [Make an incident confidential](../../user/project/issues/confidential_issues.md)
- [Set a due date](../../user/project/issues/due_dates.md)
- [Toggle notifications](../../user/profile/notifications.md#edit-notification-settings-for-issues-merge-requests-and-epics)
- [Track time spent](../../user/project/time_tracking.md)
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Manage incidents
breadcrumbs:
- doc
- operations
- incident_management
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- Ability to add an [incident](_index.md) to an iteration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/347153) in GitLab 17.0.
{{< /history >}}
This page collects instructions for all the things you can do with [incidents](incidents.md) or in relation to them.
## Create an incident
You can create an incident manually or automatically.
## Add an incident to an iteration
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To add an incident to an [iteration](../../user/group/iterations/_index.md):
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Plan > Issues** or **Monitor > Incidents**, then select your incident to view it.
1. On the right sidebar, in the **Iteration** section, select **Edit**.
1. From the dropdown list, select the iteration to add this incident to.
1. Select any area outside the dropdown list.
Alternatively, you can use the `/iteration` [quick action](../../user/project/quick_actions.md#issues-merge-requests-and-epics).
### From the Incidents page
Prerequisites:
- You must have at least the Reporter role for the project.
To create an incident from the **Incidents** page:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
1. Select **Create incident**.
### From the Issues page
Prerequisites:
- You must have at least the Reporter role for the project.
To create an incident from the **Issues** page:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Plan > Issues**, and select **New issue**.
1. From the **Type** dropdown list, select **Incident**. Only fields relevant to
incidents are available on the page.
1. Select **Create issue**.
### From an alert
Create an incident issue when viewing an [alert](alerts.md).
The incident description is populated from the alert.
Prerequisites:
- You must have at least the Developer role for the project.
To create an incident from an alert:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Alerts**.
1. Select your desired alert.
1. Select **Create incident**.
After an incident is created, to view it from the alert, select **View incident**.
When you [close an incident](#close-an-incident) linked to an alert, GitLab
[changes the alert's status](alerts.md#change-an-alerts-status) to **Resolved**.
You are then credited with the alert's status change.
### Automatically, when an alert is triggered
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In the project settings, you can turn on [creating an incident automatically](alerts.md#trigger-actions-from-alerts)
whenever an alert is triggered.
### Using the PagerDuty webhook
{{< history >}}
- [PagerDuty V3 Webhook](https://support.pagerduty.com/docs/webhooks) support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383029) in GitLab 15.7.
{{< /history >}}
You can set up a webhook with PagerDuty to automatically create a GitLab incident
for each PagerDuty incident. This configuration requires you to make changes
in both PagerDuty and GitLab.
Prerequisites:
- You must have at least the Maintainer role for the project.
To set up a webhook with PagerDuty:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**
1. Expand **Incidents**.
1. Select the **PagerDuty integration** tab.
1. Turn on the **Active** toggle.
1. Select **Save integration**.
1. Copy the value of **Webhook URL** for use in a later step.
1. To add the webhook URL to a PagerDuty webhook integration, follow the steps described in the [PagerDuty documentation](https://support.pagerduty.com/docs/webhooks#manage-v3-webhook-subscriptions).
To confirm the integration is successful, trigger a test incident from PagerDuty to
check if a GitLab incident is created from the incident.
## View a list of incidents
To view a list of the [incidents](incidents.md#incidents-list):
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Monitor > Incidents**.
To view an incident's [details page](incidents.md#incident-details), select it from the list.
### Who can view an incident
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/169256) the minimum user role from Reporter to Planner in GitLab 17.7.
{{< /history >}}
Whether you can view an incident depends on the [project visibility level](../../user/public_access.md) and
the incident's confidentiality status:
- Public project and a non-confidential incident: Anyone can view the incident.
- Private project and non-confidential incident: You must have at least the Guest role for the project.
- Confidential incident (regardless of project visibility): You must have at least the Planner role for the project.
## Assign to a user
Assign incidents to users that are actively responding.
Prerequisites:
- You must have at least the Reporter role for the project.
To assign a user:
1. In an incident, on the right sidebar, next to **Assignees**, select **Edit**.
1. From the dropdown list, select one or [multiple users](../../user/project/issues/multiple_assignees_for_issues.md) to add as **assignees**.
1. Select any area outside the dropdown list.
## Change severity
See the [incidents list](incidents.md#incidents-list) topic for a full description of the severity levels available.
Prerequisites:
- You must have at least the Reporter role for the project.
To change an incident's severity:
1. In an incident, on the right sidebar, next to **Severity**, select **Edit**.
1. From the dropdown list, select the new severity.
You can also change the severity using the `/severity` [quick action](../../user/project/quick_actions.md).
## Change status
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/5716) in GitLab 14.9 [with a flag](../../administration/feature_flags/_index.md) named `incident_escalations`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/345769) in GitLab 14.10.
- [Feature flag `incident_escalations`](https://gitlab.com/gitlab-org/gitlab/-/issues/345769) removed in GitLab 15.1.
{{< /history >}}
Prerequisites:
- You must have at least the Developer role for the project.
To change the status of an incident:
1. In an incident, on the right sidebar, next to **Status**, select **Edit**.
1. From the dropdown list, select the new severity.
**Triggered** is the default status for new incidents.
### As an on-call responder
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
On-call responders can respond to [incident pages](paging.md#escalating-an-incident)
by changing the status.
Changing the status has the following effects:
- To **Acknowledged**: limits on-call pages based on the project's [escalation policy](escalation_policies.md).
- To **Resolved**: silences all on-call pages for the incident.
- From **Resolved** to **Triggered**: restarts the incident escalating.
In GitLab 15.1 and earlier, changing the status of an [incident created from an alert](#from-an-alert)
also changes the alert status. In [GitLab 15.2 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/356057),
the alert status is independent and does not change when the incident status changes.
## Change escalation policy
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Prerequisites:
- You must have at least the Developer role for the project.
To change the escalation policy of an incident:
1. In an incident, on the right sidebar, next to **Escalation policy**, select **Edit**.
1. From the dropdown list, select the escalation policy.
By default, new incidents do not have an escalation policy selected.
Selecting an escalation policy [changes the incident status](#change-status) to **Triggered** and begins
[escalating the incident to on-call responders](paging.md#escalating-an-incident).
In GitLab 15.1 and earlier, the escalation policy for [incidents created from alerts](#from-an-alert)
reflects the alert's escalation policy and cannot be changed. In [GitLab 15.2 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/356057),
the incident escalation policy is independent and can be changed.
## Close an incident
Prerequisites:
- You must have at least the Reporter role for the project.
To close an incident, in the upper-right corner, select **Incident actions** ({{< icon name="ellipsis_v" >}}) and then **Close incident**.
When you close an incident that is linked to an [alert](alerts.md),
the linked alert's status changes to **Resolved**.
You are then credited with the alert's status change.
### Automatically close incidents via recovery alerts
Turn on closing an incident automatically when GitLab receives a recovery alert
from an HTTP or Prometheus webhook.
Prerequisites:
- You must have at least the Maintainer role for the project.
To configure the setting:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**.
1. Expand the **Incidents** section.
1. Select the **Automatically close associated incident** checkbox.
1. Select **Save changes**.
When GitLab receives a [recovery alert](integrations.md#recovery-alerts), it closes the associated incident.
This action is recorded as a system note on the incident indicating that it
was closed automatically by the GitLab Alert bot.
## Delete an incident
Prerequisites:
- You must have the Owner role for a project.
To delete an incident:
1. In an incident, select **Incident actions** ({{< icon name="ellipsis_v" >}}).
1. Select **Delete incident**.
Alternatively:
1. In an incident, select **Edit title and description** ({{< icon name="pencil" >}}).
1. Select **Delete incident**.
## Other actions
Because incidents in GitLab are built on top of [issues](../../user/project/issues/_index.md),
they have the following actions in common:
- [Add a to-do item](../../user/todos.md#create-a-to-do-item)
- [Add labels](../../user/project/labels.md#assign-and-unassign-labels)
- [Assign a milestone](../../user/project/milestones/_index.md#assign-a-milestone-to-an-item)
- [Make an incident confidential](../../user/project/issues/confidential_issues.md)
- [Set a due date](../../user/project/issues/due_dates.md)
- [Toggle notifications](../../user/profile/notifications.md#edit-notification-settings-for-issues-merge-requests-and-epics)
- [Track time spent](../../user/project/time_tracking.md)
|
https://docs.gitlab.com/operations/incidents
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/operations/incidents.md
|
2025-08-13
|
doc/operations/incident_management
|
[
"doc",
"operations",
"incident_management"
] |
incidents.md
|
Monitor
|
Platform Insights
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Incidents
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
An incident is a service disruption or outage that needs to be restored urgently.
Incidents are critical in incident management workflows.
Use GitLab to triage, respond, and remediate incidents.
## Incidents list
When you [view the incidents list](manage_incidents.md#view-a-list-of-incidents), it contains the following:
- **State**: To filter incidents by their state, select **Open**, **Closed**,
or **All** above the incident list.
- **Search**: Search for incident titles and descriptions or [filter the list](#filter-the-incidents-list).
- **Severity**: Severity of a particular incident, which can be one of the following
values:
- {{< icon name="severity-critical" >}} Critical - S1
- {{< icon name="severity-high" >}} High - S2
- {{< icon name="severity-medium" >}} Medium - S3
- {{< icon name="severity-low" >}} Low - S4
- {{< icon name="severity-unknown" >}} Unknown
- **Incident**: The title of the incident, which attempts to capture the
most meaningful information.
- **Status**: The status of the incident, which can be one of the following values:
- Triggered
- Acknowledged
- Resolved
In the Premium or Ultimate tier, this field is also linked to [on-call escalation](paging.md#escalating-an-incident) for the incident.
- **Date created**: How long ago the incident was created. This field uses the
standard GitLab pattern of `X time ago`. Hover over this value to see the exact date and time formatted according to your locale.
- **Assignees**: The user assigned to the incident.
- **Published**: Whether the incident is published to a [status page](status_page.md).

For an example of the incident list in action, see this
[demo project](https://gitlab.com/gitlab-org/monitor/monitor-sandbox/-/incidents).
### Sort the incident list
The incident list shows incidents sorted by incident created date, showing the newest first.
To sort by another column, or to change the sorting order, select the column.
The columns you can sort by:
- Severity
- Status
- Time to SLA
- Published
### Filter the incidents list
To filter the incident list by author or assignee, enter these values in the search box.
## Incident details
### Summary
The summary section for incidents provides critical details about the
incident and the contents of the issue template (if [selected](alerts.md#trigger-actions-from-alerts)). The highlighted
bar at the top of the incident displays from left to right:
- The link to the original alert.
- The alert start time.
- The event count.
Below the highlight bar, a summary includes the following fields:
- Start time
- Severity
- `full_query`
- Monitoring tool
The incident summary can be further customized using
[GitLab Flavored Markdown](../../user/markdown.md).
If an incident is [created from an alert](alerts.md#trigger-actions-from-alerts)
that provided Markdown for the incident, then the Markdown is appended to the summary.
If an incident template is configured for the project, then the template content is appended at the end.
Comments are displayed in threads, but can be displayed chronologically
[by toggling on the recent updates view](#recent-updates-view).
When you make changes to an incident, GitLab creates [system notes](../../user/project/system_notes.md) and
displays them below the summary.
### Metrics
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In many cases, incidents are associated to metrics. You can upload screenshots of metric
charts in the **Metrics** tab:

When you upload an image, you can associate the image with text or a link to the original graph.

If you add a link, you can access the original graph by selecting the hyperlink above the uploaded image.
### Alert details
Incidents show the details of linked alerts in a separate tab. To populate this
tab, the incident must have been created with a linked alert. Incidents
created automatically from alerts have this
field populated.

### Timeline events
Incident timelines give a high-level overview of what happened
during an incident, and the steps that were taken for it to be resolved.
Read more about [timeline events](incident_timeline_events.md) and how to enable this feature.
### Recent updates view
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To see the latest updates on an incident, select
**Turn recent updates view on** ({{< icon name="history" >}}) on the comment bar. Comments display
un-threaded and chronologically, newest to oldest.
### Service Level Agreement countdown timer
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can enable the Service Level Agreement Countdown timer on incidents to track
the Service Level Agreements (SLA) you hold with your customers. The timer is
automatically started when the incident is created, and shows the time
remaining before the SLA period expires. The timer is also dynamically updated
every 15 minutes so you do not have to refresh the page to see the time remaining.
Prerequisites:
- You must have at least the Maintainer role for the project.
To configure the timer:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**.
1. Expand the **Incidents** section, then select the **Incident settings** tab.
1. Select **Activate "time to SLA" countdown timer**.
1. Set a time limit in increments of 15 minutes.
1. Select **Save changes**.
After you enable the SLA countdown timer, the **Time to SLA** column is available in the
incidents list and as a field on new incidents. If
the incident isn't closed before the SLA period ends, GitLab adds a `missed::SLA`
label to the incident.
## Related topics
- [Create an incident](manage_incidents.md#create-an-incident)
- [Create an incident automatically](alerts.md#trigger-actions-from-alerts)
whenever an alert is triggered
- [View incidents list](manage_incidents.md#view-a-list-of-incidents)
- [Assign to a user](manage_incidents.md#assign-to-a-user)
- [Change incident severity](manage_incidents.md#change-severity)
- [Change incident status](manage_incidents.md#change-status)
- [Change escalation policy](manage_incidents.md#change-escalation-policy)
- [Close an incident](manage_incidents.md#close-an-incident)
- [Automatically close incidents via recovery alerts](manage_incidents.md#automatically-close-incidents-via-recovery-alerts)
- [Add a to-do item](../../user/todos.md#create-a-to-do-item)
- [Add labels](../../user/project/labels.md)
- [Assign a milestone](../../user/project/milestones/_index.md)
- [Make an incident confidential](../../user/project/issues/confidential_issues.md)
- [Set a due date](../../user/project/issues/due_dates.md)
- [Toggle notifications](../../user/profile/notifications.md#edit-notification-settings-for-issues-merge-requests-and-epics)
- [Track spent time](../../user/project/time_tracking.md)
- [Add a Zoom meeting to an incident](../../user/project/issues/associate_zoom_meeting.md) the same
way you add it to an issue
- [Linked resources in incidents](linked_resources.md)
- Create incidents and receive incident notifications [directly from Slack](slack.md)
- Use the [Issues API](../../api/issues.md) to interact with incidents
|
---
stage: Monitor
group: Platform Insights
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Incidents
breadcrumbs:
- doc
- operations
- incident_management
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
An incident is a service disruption or outage that needs to be restored urgently.
Incidents are critical in incident management workflows.
Use GitLab to triage, respond, and remediate incidents.
## Incidents list
When you [view the incidents list](manage_incidents.md#view-a-list-of-incidents), it contains the following:
- **State**: To filter incidents by their state, select **Open**, **Closed**,
or **All** above the incident list.
- **Search**: Search for incident titles and descriptions or [filter the list](#filter-the-incidents-list).
- **Severity**: Severity of a particular incident, which can be one of the following
values:
- {{< icon name="severity-critical" >}} Critical - S1
- {{< icon name="severity-high" >}} High - S2
- {{< icon name="severity-medium" >}} Medium - S3
- {{< icon name="severity-low" >}} Low - S4
- {{< icon name="severity-unknown" >}} Unknown
- **Incident**: The title of the incident, which attempts to capture the
most meaningful information.
- **Status**: The status of the incident, which can be one of the following values:
- Triggered
- Acknowledged
- Resolved
In the Premium or Ultimate tier, this field is also linked to [on-call escalation](paging.md#escalating-an-incident) for the incident.
- **Date created**: How long ago the incident was created. This field uses the
standard GitLab pattern of `X time ago`. Hover over this value to see the exact date and time formatted according to your locale.
- **Assignees**: The user assigned to the incident.
- **Published**: Whether the incident is published to a [status page](status_page.md).

For an example of the incident list in action, see this
[demo project](https://gitlab.com/gitlab-org/monitor/monitor-sandbox/-/incidents).
### Sort the incident list
The incident list shows incidents sorted by incident created date, showing the newest first.
To sort by another column, or to change the sorting order, select the column.
The columns you can sort by:
- Severity
- Status
- Time to SLA
- Published
### Filter the incidents list
To filter the incident list by author or assignee, enter these values in the search box.
## Incident details
### Summary
The summary section for incidents provides critical details about the
incident and the contents of the issue template (if [selected](alerts.md#trigger-actions-from-alerts)). The highlighted
bar at the top of the incident displays from left to right:
- The link to the original alert.
- The alert start time.
- The event count.
Below the highlight bar, a summary includes the following fields:
- Start time
- Severity
- `full_query`
- Monitoring tool
The incident summary can be further customized using
[GitLab Flavored Markdown](../../user/markdown.md).
If an incident is [created from an alert](alerts.md#trigger-actions-from-alerts)
that provided Markdown for the incident, then the Markdown is appended to the summary.
If an incident template is configured for the project, then the template content is appended at the end.
Comments are displayed in threads, but can be displayed chronologically
[by toggling on the recent updates view](#recent-updates-view).
When you make changes to an incident, GitLab creates [system notes](../../user/project/system_notes.md) and
displays them below the summary.
### Metrics
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In many cases, incidents are associated to metrics. You can upload screenshots of metric
charts in the **Metrics** tab:

When you upload an image, you can associate the image with text or a link to the original graph.

If you add a link, you can access the original graph by selecting the hyperlink above the uploaded image.
### Alert details
Incidents show the details of linked alerts in a separate tab. To populate this
tab, the incident must have been created with a linked alert. Incidents
created automatically from alerts have this
field populated.

### Timeline events
Incident timelines give a high-level overview of what happened
during an incident, and the steps that were taken for it to be resolved.
Read more about [timeline events](incident_timeline_events.md) and how to enable this feature.
### Recent updates view
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
To see the latest updates on an incident, select
**Turn recent updates view on** ({{< icon name="history" >}}) on the comment bar. Comments display
un-threaded and chronologically, newest to oldest.
### Service Level Agreement countdown timer
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can enable the Service Level Agreement Countdown timer on incidents to track
the Service Level Agreements (SLA) you hold with your customers. The timer is
automatically started when the incident is created, and shows the time
remaining before the SLA period expires. The timer is also dynamically updated
every 15 minutes so you do not have to refresh the page to see the time remaining.
Prerequisites:
- You must have at least the Maintainer role for the project.
To configure the timer:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Monitor**.
1. Expand the **Incidents** section, then select the **Incident settings** tab.
1. Select **Activate "time to SLA" countdown timer**.
1. Set a time limit in increments of 15 minutes.
1. Select **Save changes**.
After you enable the SLA countdown timer, the **Time to SLA** column is available in the
incidents list and as a field on new incidents. If
the incident isn't closed before the SLA period ends, GitLab adds a `missed::SLA`
label to the incident.
## Related topics
- [Create an incident](manage_incidents.md#create-an-incident)
- [Create an incident automatically](alerts.md#trigger-actions-from-alerts)
whenever an alert is triggered
- [View incidents list](manage_incidents.md#view-a-list-of-incidents)
- [Assign to a user](manage_incidents.md#assign-to-a-user)
- [Change incident severity](manage_incidents.md#change-severity)
- [Change incident status](manage_incidents.md#change-status)
- [Change escalation policy](manage_incidents.md#change-escalation-policy)
- [Close an incident](manage_incidents.md#close-an-incident)
- [Automatically close incidents via recovery alerts](manage_incidents.md#automatically-close-incidents-via-recovery-alerts)
- [Add a to-do item](../../user/todos.md#create-a-to-do-item)
- [Add labels](../../user/project/labels.md)
- [Assign a milestone](../../user/project/milestones/_index.md)
- [Make an incident confidential](../../user/project/issues/confidential_issues.md)
- [Set a due date](../../user/project/issues/due_dates.md)
- [Toggle notifications](../../user/profile/notifications.md#edit-notification-settings-for-issues-merge-requests-and-epics)
- [Track spent time](../../user/project/time_tracking.md)
- [Add a Zoom meeting to an incident](../../user/project/issues/associate_zoom_meeting.md) the same
way you add it to an issue
- [Linked resources in incidents](linked_resources.md)
- Create incidents and receive incident notifications [directly from Slack](slack.md)
- Use the [Issues API](../../api/issues.md) to interact with incidents
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.