Aller au contenu

Déployer un serveur Git Gitea infogéré sur AlmaLinux 9 (prêt pour la production)

Monter un Gitea durci sur AlmaLinux 9 — PostgreSQL en localhost, reverse proxy nginx, SSH sur 2222, TLS Let's Encrypt, cycle de vie systemd, SELinux enforcing.

On vous demande de monter un Git auto-hébergé pour l’équipe. La documentation Gitea vous guide pour déballer le binaire, vous le démarrez sous votre propre utilisateur, l’interface web charge sur le port 3000, et vous remettez ça à l’équipe. Dix-huit mois plus tard, la base SQLite vit sur un chemin que personne n’a sauvegardé, le Git SSH n’a jamais été séparé du SSH hôte donc chaque push entre en compétition avec le SSH admin sur le port 22, PostgreSQL écoute sur 0.0.0.0, le certificat TLS s’est renouvelé une fois puis a commencé à échouer en silence, et la source de vérité de toute l’organisation tient avec un répertoire ~/gitea.

Ce qui se passe

Un déploiement Gitea réellement prêt pour la production demande plus que ./gitea web. PostgreSQL doit être lié à 127.0.0.1 uniquement ; l’écouteur Git SSH de Gitea doit tourner sur un port dédié (2222 est la convention) pour que le SSH hôte sur 22 reste propre pour les opérateurs ; l’interface web s’assoit derrière nginx avec un certificat Let’s Encrypt et HSTS ; le service tourne sous un utilisateur non privilégié dédié avec LimitNOFILE=64000 parce que les rafales de clone font apparaître la pression sur les descripteurs de fichiers en premier ; SELinux reste enforcing ; et la paire de secrets (SECRET_KEY et INTERNAL_TOKEN) est générée une fois et n’est commitée nulle part. Le répertoire des données Git est la source de vérité — il doit vivre sur un chemin que l’instantané au niveau VM couvre vraiment.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(80|443|2222|3000|5432)\b'
# 127.0.0.1:3000   gitea (loopback seulement — nginx est devant)
# 127.0.0.1:5432   postgres
# 0.0.0.0:2222     gitea (Git SSH)
# 0.0.0.0:80       nginx (redirection HTTP -> HTTPS)
# 0.0.0.0:443      nginx (TLS)

PostgreSQL sur 5432 doit être 127.0.0.1, jamais 0.0.0.0. Confirmez que le certificat est réel et chaîné :

echo | openssl s_client -servername git.example.com -connect git.example.com:443 2>/dev/null | openssl x509 -noout -subject -issuer -dates

Et confirmez que Git par SSH répond bien sur 2222 (pas 22) :

ssh -T -p 2222 git@git.example.com
# Hi there, You've successfully authenticated...

Si le clone par le port 22 fonctionne encore, le SSH hôte expose l’accès Git par accident — corrigez-le avant d’ajouter des utilisateurs.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-gitea-almalinux9.sh, puis exécutez-le. Il tourne sur une VM AlmaLinux 9.x fraîche : mise à jour de base + EPEL, ajustement noyau/descripteurs, durcissement SSH (clé uniquement, clé root préservée), un utilisateur système git dédié, PostgreSQL 16 lié à 127.0.0.1, le binaire Gitea téléchargé avec vérification du checksum, un app.ini avec le port SSH à 2222 et INSTALL_LOCK=true, une unité systemd avec LimitNOFILE=64000, nginx + certbot pour un certificat Let’s Encrypt, et une boucle d’attente d’écouteur avant de déclarer la réussite.

#!/usr/bin/env bash
set -euo pipefail

### AlmaLinux 9.x Gitea clean VM installer
### Keeps root SSH key login enabled on port 22
### Disables SSH password login
### Runs Git SSH on port 2222 under the gitea binary
### PostgreSQL bound to 127.0.0.1 only
### nginx reverse proxy with Let's Encrypt
### No local backups; assumes VM-level backup

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${GITEA_DOMAIN:?Set GITEA_DOMAIN to the FQDN, e.g. git.example.com}"
: "${LE_EMAIL:?Set LE_EMAIL to the Let's Encrypt contact address}"

GITEA_VERSION="${GITEA_VERSION:-1.22.3}"
DB_NAME="gitea"
DB_USER="gitea"
DB_PASS="$(openssl rand -hex 24)"

echo
echo "========================================"
echo "Gitea AlmaLinux 9.x Setup"
echo "Domain: ${GITEA_DOMAIN}"
echo "Version: ${GITEA_VERSION}"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y update

echo "==> Installing base packages"
dnf -y install \
  vim curl wget ca-certificates gnupg2 chrony fail2ban \
  dnf-automatic policycoreutils-python-utils lsof tcpdump \
  bind-utils tar gzip unzip iproute git-core nginx

echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true

echo "==> Configuring SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

echo "==> Applying sysctl tuning"
cat > /etc/sysctl.d/99-gitea.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-gitea.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Hardening SSH (host SSH stays on port 22)"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart sshd

echo "==> Configuring fail2ban for SSH"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Configuring automatic security updates"
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
network_online_timeout = 60
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
[base]
debuglevel = 1
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> Installing PostgreSQL 16 from PGDG"
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -qy module disable postgresql || true
dnf -y install postgresql16-server postgresql16-contrib
/usr/pgsql-16/bin/postgresql-16-setup initdb

echo "==> Locking PostgreSQL to 127.0.0.1"
PGDATA=/var/lib/pgsql/16/data
sed -i "s|^#listen_addresses.*|listen_addresses = '127.0.0.1'|" ${PGDATA}/postgresql.conf
cat > ${PGDATA}/pg_hba.conf <<'PGHBA'
local   all             all                                     peer
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             ::1/128                 scram-sha-256
PGHBA
chown postgres:postgres ${PGDATA}/pg_hba.conf
systemctl enable --now postgresql-16

echo "==> Creating Gitea database and role"
sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
CREATE ROLE ${DB_USER} WITH LOGIN PASSWORD '${DB_PASS}';
CREATE DATABASE ${DB_NAME} WITH OWNER ${DB_USER} ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' TEMPLATE template0;
SQL

echo "==> Creating gitea system user"
getent passwd git >/dev/null || \
  useradd --system --create-home --home-dir /var/lib/gitea \
    --shell /bin/bash --comment 'Git Version Control' git

mkdir -p /var/lib/gitea/{custom,data,log,repositories} /etc/gitea
chown -R git:git /var/lib/gitea
chmod -R 750 /var/lib/gitea
chown root:git /etc/gitea
chmod 770 /etc/gitea

echo "==> Downloading Gitea ${GITEA_VERSION}"
curl -fsSL -o /usr/local/bin/gitea \
  "https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-linux-amd64"
curl -fsSL -o /tmp/gitea.sha256 \
  "https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-linux-amd64.sha256"
( cd /usr/local/bin && awk '{print $1"  /usr/local/bin/gitea"}' /tmp/gitea.sha256 | sha256sum -c - )
chmod 755 /usr/local/bin/gitea

echo "==> Generating Gitea secrets"
SECRET_KEY="$(gitea generate secret SECRET_KEY)"
INTERNAL_TOKEN="$(gitea generate secret INTERNAL_TOKEN)"
LFS_JWT_SECRET="$(gitea generate secret LFS_JWT_SECRET)"
JWT_SECRET="$(gitea generate secret JWT_SECRET)"

echo "==> Writing /etc/gitea/app.ini"
cat > /etc/gitea/app.ini <<INI
APP_NAME = Gitea
RUN_USER = git
RUN_MODE = prod

[server]
PROTOCOL = http
DOMAIN = ${GITEA_DOMAIN}
ROOT_URL = https://${GITEA_DOMAIN}/
HTTP_ADDR = 127.0.0.1
HTTP_PORT = 3000
DISABLE_SSH = false
SSH_DOMAIN = ${GITEA_DOMAIN}
START_SSH_SERVER = true
SSH_LISTEN_HOST = 0.0.0.0
SSH_PORT = 2222
SSH_LISTEN_PORT = 2222
LFS_START_SERVER = true
LFS_JWT_SECRET = ${LFS_JWT_SECRET}
OFFLINE_MODE = true

[database]
DB_TYPE = postgres
HOST = 127.0.0.1:5432
NAME = ${DB_NAME}
USER = ${DB_USER}
PASSWD = ${DB_PASS}
SSL_MODE = disable
LOG_SQL = false

[repository]
ROOT = /var/lib/gitea/repositories
DEFAULT_BRANCH = main

[security]
INSTALL_LOCK = true
SECRET_KEY = ${SECRET_KEY}
INTERNAL_TOKEN = ${INTERNAL_TOKEN}
PASSWORD_HASH_ALGO = pbkdf2
MIN_PASSWORD_LENGTH = 12
PASSWORD_COMPLEXITY = lower,upper,digit,spec

[oauth2]
JWT_SECRET = ${JWT_SECRET}

[service]
DISABLE_REGISTRATION = true
REQUIRE_SIGNIN_VIEW = true
ENABLE_NOTIFY_MAIL = false

[session]
PROVIDER = file
COOKIE_SECURE = true

[log]
ROOT_PATH = /var/lib/gitea/log
MODE = file
LEVEL = info

[indexer]
ISSUE_INDEXER_TYPE = bleve
REPO_INDEXER_ENABLED = true

[mailer]
ENABLED = false

[metrics]
ENABLED = true
TOKEN =
INI
chown root:git /etc/gitea/app.ini
chmod 640 /etc/gitea/app.ini

echo "==> Installing Gitea systemd unit"
cat > /etc/systemd/system/gitea.service <<'UNIT'
[Unit]
Description=Gitea (Git with a cup of tea)
After=network-online.target postgresql-16.service
Wants=network-online.target
Requires=postgresql-16.service

[Service]
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea
ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
Restart=always
RestartSec=5
Environment=USER=git HOME=/var/lib/gitea GITEA_WORK_DIR=/var/lib/gitea
LimitNOFILE=64000
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now gitea

echo "==> Waiting for Gitea on 127.0.0.1:3000 and 0.0.0.0:2222"
for i in {1..60}; do
  if ss -lntp | grep -q '127.0.0.1:3000' && ss -lntp | grep -q ':2222'; then
    break
  fi
  sleep 1
done

if ! ss -lntp | grep -q '127.0.0.1:3000'; then
  echo "Gitea failed to bind on 127.0.0.1:3000"
  systemctl status gitea --no-pager -l || true
  journalctl -u gitea -n 120 --no-pager || true
  exit 1
fi

echo "==> Installing certbot and obtaining cert"
dnf -y install certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/gitea.conf <<NGINX
server {
    listen 80;
    listen [::]:80;
    server_name ${GITEA_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/lib/letsencrypt; }
    location / { return 301 https://\$host\$request_uri; }
}
NGINX

mkdir -p /var/lib/letsencrypt
nginx -t
systemctl enable --now nginx
systemctl reload nginx

certbot certonly --webroot -w /var/lib/letsencrypt \
  -d "${GITEA_DOMAIN}" --email "${LE_EMAIL}" \
  --agree-tos --no-eff-email --non-interactive

cat > /etc/nginx/conf.d/gitea.conf <<NGINX
server {
    listen 80;
    listen [::]:80;
    server_name ${GITEA_DOMAIN};
    location /.well-known/acme-challenge/ { root /var/lib/letsencrypt; }
    location / { return 301 https://\$host\$request_uri; }
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name ${GITEA_DOMAIN};

    ssl_certificate     /etc/letsencrypt/live/${GITEA_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${GITEA_DOMAIN}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    client_max_body_size 512m;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host \$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 https;
        proxy_read_timeout 300s;
    }
}
NGINX

nginx -t
systemctl reload nginx

echo "==> Enabling certbot renewal timer"
systemctl enable --now certbot-renew.timer 2>/dev/null || \
  systemctl enable --now certbot.timer

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "SELinux:"
getenforce || true
echo
echo "Services:"
systemctl is-active postgresql-16 gitea nginx chronyd fail2ban || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|2222|3000|5432)\b' || true
echo
echo "Web UI:"
echo "https://${GITEA_DOMAIN}/"
echo
echo "Git SSH:"
echo "ssh://git@${GITEA_DOMAIN}:2222/<owner>/<repo>.git"
echo
echo "Initial admin (run as root, one-time):"
echo "  sudo -u git gitea admin user create --admin \\"
echo "    --username admin --email ${LE_EMAIL} --random-password \\"
echo "    --config /etc/gitea/app.ini"
echo
echo "Final step:"
echo "reboot"

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-gitea-almalinux9.sh
GITEA_DOMAIN=git.example.com LE_EMAIL=ops@example.com /root/setup-gitea-almalinux9.sh

La création de l’admin initial est laissée volontairement comme une étape manuelle ponctuelle imprimée à la fin — déposer le premier mot de passe admin dans le journal systemd est le genre de chose qui hante un audit. Lancez la ligne gitea admin user create --admin imprimée, capturez le mot de passe aléatoire dans votre gestionnaire de secrets, et c’est terminé. Les sauvegardes au niveau hôte sont hors périmètre : /var/lib/gitea/repositories et /var/lib/pgsql/16/data sont les chemins avec état, et l’hypothèse est que la VM a des instantanés/sauvegardes au niveau cloud.

Faites tourner le Gitea de production sur un environnement infogéré Stack Harbor avec supervision, cadence de patching et appropriation de la chaîne de déploiement en place : Gestion du déploiement →.