Skip to content

Deploying Gitea self-hosted Git on AlmaLinux 9 (production-ready)

Stand up a hardened Gitea on AlmaLinux 9 — PostgreSQL on localhost, nginx reverse proxy, SSH on 2222, Let's Encrypt TLS, systemd lifecycle, SELinux enforcing.

You’ve been asked to stand up a self-hosted Git for the team. The Gitea docs walk you through unpacking the binary, you start it under your own user, the web UI loads on port 3000, and you call it done. Eighteen months later, the SQLite database lives on a path no one backed up, Git SSH was never separated from host SSH so pushes compete with admin SSH on port 22, PostgreSQL is listening on 0.0.0.0, the TLS cert renewed once and then started failing silently, and the engineering org’s source of truth is held together by a ~/gitea directory.

What’s happening

A Gitea deployment that is actually production-ready needs more than ./gitea web. PostgreSQL has to be bound to 127.0.0.1 only; Gitea’s Git SSH listener has to run on a dedicated port (2222 is the convention) so host SSH on 22 stays clean for operators; the web UI sits behind nginx with a Let’s Encrypt cert and HSTS; the service runs under a dedicated unprivileged user with LimitNOFILE=64000 because clone storms surface FD pressure first; SELinux stays enforcing; and the secret pair (SECRET_KEY and INTERNAL_TOKEN) is generated once and never committed anywhere. The Git data directory is the source of truth — it needs to be on a path the VM-level snapshot actually covers.

How to verify

After install, the listeners should look like this:

ss -lntp | grep -E ':(80|443|2222|3000|5432)\b'
# 127.0.0.1:3000   gitea (loopback only — nginx fronts it)
# 127.0.0.1:5432   postgres
# 0.0.0.0:2222     gitea (Git SSH)
# 0.0.0.0:80       nginx (HTTP -> HTTPS redirect)
# 0.0.0.0:443      nginx (TLS)

PostgreSQL on 5432 must be 127.0.0.1, never 0.0.0.0. Confirm the cert is real and chained:

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

And confirm Git over SSH actually answers on 2222 (not 22):

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

If clone over port 22 still works, the host SSH is exposing Git access by accident — fix it before adding users.

The fix

Save the script below as /root/setup-gitea-almalinux9.sh, then run it. It runs on a fresh AlmaLinux 9.x VM: base update + EPEL, kernel/FD tuning, SSH hardening (key-only, root key preserved), a dedicated git system user, PostgreSQL 16 bound to 127.0.0.1, the Gitea binary fetched with checksum verification, an app.ini with the SSH port set to 2222 and INSTALL_LOCK=true, a systemd unit with LimitNOFILE=64000, nginx + certbot for a Let’s Encrypt cert, and a listener wait loop before declaring success.

#!/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"

Make it executable and run it:

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

Admin user creation is intentionally left as a one-shot manual step printed at the end — committing the first admin password to the systemd journal is the kind of thing that haunts an audit. Run the printed gitea admin user create --admin line, capture the random password into your secrets manager, and you’re done. Host-level backups are out of scope: /var/lib/gitea/repositories and /var/lib/pgsql/16/data are the stateful paths, and the assumption is the VM has snapshot/backup at the cloud layer.

Run the production Gitea on a Stack Harbor-managed environment with monitoring, patching cadence, and deploy-pipeline ownership in place: Deployment management →.