Skip to content

Deploying Authentik SSO on Ubuntu 22.04 (production-ready)

Stand up a hardened Authentik IdP on Ubuntu 22.04 with Docker Compose — PostgreSQL + Redis on the internal compose network, nginx, Let's Encrypt TLS.

You’ve been asked to stand up Authentik as the company SSO. The quickstart works, you wire OIDC into the first app, the team gets in, you hand it over. Six months later, the SAML metadata URL is on plain HTTP because nginx never got pointed at the right vhost, PostgreSQL is reachable on the host’s public interface because the compose file mapped 5432:5432, the Let’s Encrypt cert expired because nobody enabled the renewal timer, and the IdP — the one thing every other service trusts — is the weakest VM in the fleet.

What’s happening

An Authentik deployment that is actually production-ready needs more than docker compose up -d. PostgreSQL and Redis must stay on the internal compose network — never bound to the host’s public interface. The authentik-server HTTP listener has to sit behind nginx terminating TLS on a real Let’s Encrypt cert, with HSTS, WebSocket upgrades for the realtime UI, and a renewal timer that’s actively monitored. Metadata endpoints have to be HTTPS-only because every relying party fetches and caches the keys; if they fetch over HTTP the trust chain is gone. The admin user needs MFA from day one, the bootstrap token has to be rotated, and SSH needs password auth disabled while preserving root key access. None of these are individually critical — skip them and the IdP every other service trusts becomes the easiest hole in the network.

How to verify

After install, the listeners on the host should be exactly these:

ss -lntp | grep -E ':(80|443|9000|5432|6379)\b'
# 0.0.0.0:80    nginx
# 0.0.0.0:443   nginx
# 127.0.0.1:9000  authentik-server (via compose)

PostgreSQL on 5432 and Redis on 6379 must not appear on the host — they live inside the compose network. The OIDC discovery document must return valid JSON over HTTPS:

curl -fsS https://sso.example.com/application/o/.well-known/openid-configuration | jq .issuer
# "https://sso.example.com/application/o/"

Certificate freshness on the public listener:

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

If the discovery URL returns HTML or the cert is within 30 days of expiry, you have a problem before the next JWKS cache rotation.

The fix

Save the script below as /root/setup-authentik-ubuntu22.sh, then run it. It runs the installer flow on a fresh Ubuntu 22.04 VM: base update, kernel tuning, file limits, UFW (SSH + HTTP + HTTPS only), SSH hardening, unattended-upgrades, Docker CE + compose plugin, the official Authentik compose stack with PostgreSQL and Redis kept on the internal network, randomly generated secret key and Postgres password written to /opt/authentik/.env with chmod 600, nginx terminating TLS with WebSocket-aware proxy headers, Let’s Encrypt via certbot’s nginx plugin, and a poll loop that waits for the :9000 upstream and the :443 listener before declaring success.

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

### Ubuntu 22.04 Authentik clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures Docker + Authentik + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${AK_DOMAIN:?Set AK_DOMAIN=sso.example.com}"
: "${AK_EMAIL:?Set AK_EMAIL=ops@example.com for Let's Encrypt}"
AK_VERSION="${AK_VERSION:-2024.10.5}"
AK_PG_PASSWORD="${AK_PG_PASSWORD:-$(openssl rand -hex 24)}"
AK_SECRET_KEY="${AK_SECRET_KEY:-$(openssl rand -base64 60 | tr -d '\n')}"

echo
echo "========================================"
echo "Authentik Ubuntu 22.04 Setup"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip \
  iproute2 net-tools openssl jq \
  software-properties-common

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-authentik.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

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

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-authentik.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root SSH key login enabled"
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 ChallengeResponseAuthentication 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 ssh

echo "==> Configuring fail2ban"
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 unattended-upgrades for security"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu jammy stable" \
  > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

systemctl enable --now docker

echo "==> Preparing /opt/authentik"
mkdir -p /opt/authentik/{media,certs,custom-templates}
cd /opt/authentik

cat > /opt/authentik/.env <<ENV
PG_PASS=${AK_PG_PASSWORD}
AUTHENTIK_SECRET_KEY=${AK_SECRET_KEY}
AUTHENTIK_ERROR_REPORTING__ENABLED=false
AUTHENTIK_IMAGE=ghcr.io/goauthentik/server
AUTHENTIK_TAG=${AK_VERSION}
COMPOSE_PROJECT_NAME=authentik
ENV

chmod 600 /opt/authentik/.env

cat > /opt/authentik/docker-compose.yml <<'COMPOSE'
services:
  postgresql:
    image: docker.io/library/postgres:16-alpine
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -d $$POSTGRES_DB -U $$POSTGRES_USER"]
      start_period: 20s
      interval: 30s
      retries: 5
      timeout: 5s
    volumes:
      - database:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${PG_PASS}
      POSTGRES_USER: authentik
      POSTGRES_DB: authentik

  redis:
    image: docker.io/library/redis:alpine
    command: --save 60 1 --loglevel warning
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
      start_period: 20s
      interval: 30s
      retries: 5
      timeout: 3s
    volumes:
      - redis:/data

  server:
    image: ${AUTHENTIK_IMAGE}:${AUTHENTIK_TAG}
    restart: unless-stopped
    command: server
    environment:
      AUTHENTIK_REDIS__HOST: redis
      AUTHENTIK_POSTGRESQL__HOST: postgresql
      AUTHENTIK_POSTGRESQL__USER: authentik
      AUTHENTIK_POSTGRESQL__NAME: authentik
      AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
      AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
      AUTHENTIK_ERROR_REPORTING__ENABLED: ${AUTHENTIK_ERROR_REPORTING__ENABLED}
    volumes:
      - ./media:/media
      - ./custom-templates:/templates
    ports:
      - "127.0.0.1:9000:9000"
    depends_on:
      postgresql:
        condition: service_healthy
      redis:
        condition: service_healthy

  worker:
    image: ${AUTHENTIK_IMAGE}:${AUTHENTIK_TAG}
    restart: unless-stopped
    command: worker
    environment:
      AUTHENTIK_REDIS__HOST: redis
      AUTHENTIK_POSTGRESQL__HOST: postgresql
      AUTHENTIK_POSTGRESQL__USER: authentik
      AUTHENTIK_POSTGRESQL__NAME: authentik
      AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
      AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
      AUTHENTIK_ERROR_REPORTING__ENABLED: ${AUTHENTIK_ERROR_REPORTING__ENABLED}
    user: root
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./media:/media
      - ./certs:/certs
      - ./custom-templates:/templates
    depends_on:
      postgresql:
        condition: service_healthy
      redis:
        condition: service_healthy

volumes:
  database:
    driver: local
  redis:
    driver: local
COMPOSE

echo "==> Starting Authentik stack"
docker compose --env-file /opt/authentik/.env -f /opt/authentik/docker-compose.yml up -d

echo "==> Waiting for Authentik server on 127.0.0.1:9000"
for i in {1..90}; do
  if ss -lntp | grep -q '127.0.0.1:9000'; then
    break
  fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:9000'; then
  echo "Authentik server failed to listen on 127.0.0.1:9000"
  docker compose -f /opt/authentik/docker-compose.yml logs --tail=200 server || true
  exit 1
fi

echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/authentik <<NGINX
upstream authentik_backend {
    server 127.0.0.1:9000;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${AK_DOMAIN};
    return 301 https://\$host\$request_uri;
}

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

    client_max_body_size 50M;
    proxy_read_timeout   300s;
    proxy_send_timeout   300s;
    proxy_connect_timeout 60s;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location /ws/ {
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        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 \$scheme;
        proxy_http_version 1.1;
        proxy_pass http://authentik_backend;
    }

    location / {
        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 \$scheme;
        proxy_http_version 1.1;
        proxy_pass http://authentik_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/authentik /etc/nginx/sites-enabled/authentik
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${AK_EMAIL}" -d "${AK_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then
    break
  fi
  sleep 1
done

echo "==> Final package update"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r

echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|9000)\b' || true

echo
echo "Containers:"
docker compose -f /opt/authentik/docker-compose.yml ps

echo
echo "Services:"
systemctl is-active docker nginx fail2ban chrony || true

echo
echo "OIDC discovery (must return JSON over HTTPS):"
curl -fsS "https://${AK_DOMAIN}/application/o/.well-known/openid-configuration" | jq -r .issuer || true

echo
echo "Secrets written to /opt/authentik/.env (mode 600). Move them to your secrets manager and remove the file from this host before going live."

echo
echo "Web UI:"
echo "https://${AK_DOMAIN}/if/flow/initial-setup/"

echo
echo "Final step:"
echo "Open the URL, create the akadmin account, enable TOTP MFA immediately, then register the first OIDC/SAML provider in the Authentik admin interface."

Make it executable and run it:

chmod 700 /root/setup-authentik-ubuntu22.sh
AK_DOMAIN=sso.example.com AK_EMAIL=ops@example.com /root/setup-authentik-ubuntu22.sh

The first request to https://sso.example.com/if/flow/initial-setup/ creates the akadmin user — finish the wizard, enable TOTP MFA on that account before anything else, then build your first OIDC provider. Move the secrets from /opt/authentik/.env into your secrets manager; the on-disk copy is a bootstrap convenience. Host-level backups are not configured here — docker compose exec postgresql pg_dump plus /opt/authentik/media/ should be covered by your VM snapshot policy.

Run the production IdP on a Stack Harbor-managed environment with patch cadence, monitoring, and Sev-1 escalation built in: Managed Cloud Ops.