Skip to content

Deploying Directus on Ubuntu 22.04 (production-ready)

Stand up a hardened Directus headless CMS on Ubuntu 22.04 — Docker Compose with PostgreSQL + Redis, nginx + Let's Encrypt, S3-compatible asset storage.

You spun up Directus from the docker run one-liner on a VM, pointed a frontend at it, and called it done. Six months later, PostgreSQL is on 0.0.0.0:5432 because the compose file you copied off a forum left the port published, every uploaded asset lives on the application node’s local disk so the VM has crept past 200 GB and snapshots take an hour, the admin role has been shared across three contractors because nobody set up an SSO bridge, and Redis is missing entirely — every flow run rehydrates the schema from cold because the cache is in-process and the container restarted last week.

What’s happening

A Directus deployment that is actually production-ready needs more than the compose quickstart. PostgreSQL has to live on the Docker network only (no published 5432), with a strong password in the env file and chmod 600 on it. Redis has to be wired in as the cache and rate-limit store so schema reads and the websocket layer survive a restart. Assets belong on S3-compatible object storage — the application node should be stateless so you can rebuild it in fifteen minutes — and Directus’s storage driver supports that natively through STORAGE_S3_*. nginx terminates TLS on the public side with a real Let’s Encrypt cert. The first admin user gets created via directus bootstrap, not by clicking through the UI as anonymous. None of these are individually critical — skip them and the CMS becomes the data-loss-prone VM in the fleet.

How to verify

After install, the published listeners on the host should be limited:

ss -lntp | grep -E ':(80|443|8055|5432|6379)\b'
# 0.0.0.0:80     nginx
# 0.0.0.0:443    nginx
# (nothing on 8055, 5432, 6379 — they live on the docker network only)

PostgreSQL must answer inside the container, never from the host:

docker compose -f /opt/directus/docker-compose.yml exec -T database \
  pg_isready -U directus
# /var/run/postgresql:5432 - accepting connections

The admin URL should answer:

curl -I https://your-directus-domain/admin/
# HTTP/2 200

Container health:

docker compose -f /opt/directus/docker-compose.yml ps
# directus    Up (healthy)
# database    Up (healthy)
# cache       Up (healthy)

If 5432 or 6379 shows on 0.0.0.0 on the host, the compose file is still publishing them — fix it before you put data in.

The fix

Save the script below as /root/setup-directus-ubuntu22.sh, then run it. It performs the full installer flow on a fresh Ubuntu 22.04 VM: base update, kernel/network tuning, file limits, UFW (SSH + HTTP + HTTPS only), SSH hardening, unattended-upgrades for security patches, Docker Engine + Compose v2 from Docker’s apt repo, a /opt/directus working tree with a 600-perm env file, a compose stack with PostgreSQL 16 + Redis 7 + Directus (latest) on a private bridge with no ports published, S3-compatible asset storage wired through STORAGE_S3_* variables, nginx with TLS terminated by Let’s Encrypt, directus bootstrap to seed the schema and the first admin user, and a poll loop that waits for the application healthcheck before declaring success.

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

### Ubuntu 22.04 Directus clean VM installer
### Docker Compose stack: PostgreSQL 16 + Redis 7 + Directus
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### S3-compatible asset storage; assets do not live on the app node
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${DIRECTUS_DOMAIN:?Set DIRECTUS_DOMAIN=cms.example.com}"
: "${DIRECTUS_EMAIL:?Set DIRECTUS_EMAIL=ops@example.com for Let's Encrypt}"
: "${ADMIN_EMAIL:?Set ADMIN_EMAIL=admin@example.com}"
: "${S3_ENDPOINT:?Set S3_ENDPOINT, e.g. https://s3.example.com}"
: "${S3_BUCKET:?Set S3_BUCKET, e.g. directus-prod-assets}"
: "${S3_REGION:?Set S3_REGION, e.g. us-east-1}"
: "${S3_KEY:?Set S3_KEY (access key id)}"
: "${S3_SECRET:?Set S3_SECRET (secret access key)}"

ADMIN_PASSWORD="${ADMIN_PASSWORD:-$(openssl rand -hex 16)}"
DB_PASSWORD="${DB_PASSWORD:-$(openssl rand -hex 24)}"
KEY="${KEY:-$(uuidgen 2>/dev/null || openssl rand -hex 16)}"
SECRET="${SECRET:-$(openssl rand -hex 32)}"

echo
echo "========================================"
echo "Directus Ubuntu 22.04 Setup"
echo "Domain: ${DIRECTUS_DOMAIN}"
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 uuid-runtime \
  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-directus.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

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-directus.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 Engine + Compose v2"
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 $(. /etc/os-release && echo "$VERSION_CODENAME") 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/directus"
mkdir -p /opt/directus/extensions /opt/directus/uploads /opt/directus/templates
chmod 750 /opt/directus

echo "==> Writing /opt/directus/.env"
cat > /opt/directus/.env <<ENV
# Directus core
KEY=${KEY}
SECRET=${SECRET}
PUBLIC_URL=https://${DIRECTUS_DOMAIN}
LOG_LEVEL=info
NODE_ENV=production

# Admin bootstrap
ADMIN_EMAIL=${ADMIN_EMAIL}
ADMIN_PASSWORD=${ADMIN_PASSWORD}

# Database (compose service "database")
DB_CLIENT=pg
DB_HOST=database
DB_PORT=5432
DB_DATABASE=directus
DB_USER=directus
DB_PASSWORD=${DB_PASSWORD}

# Cache + rate limit (compose service "cache")
CACHE_ENABLED=true
CACHE_STORE=redis
CACHE_AUTO_PURGE=true
REDIS=redis://cache:6379
RATE_LIMITER_ENABLED=true
RATE_LIMITER_STORE=redis
RATE_LIMITER_POINTS=50
RATE_LIMITER_DURATION=1

# S3-compatible asset storage
STORAGE_LOCATIONS=s3
STORAGE_S3_DRIVER=s3
STORAGE_S3_KEY=${S3_KEY}
STORAGE_S3_SECRET=${S3_SECRET}
STORAGE_S3_BUCKET=${S3_BUCKET}
STORAGE_S3_REGION=${S3_REGION}
STORAGE_S3_ENDPOINT=${S3_ENDPOINT}
STORAGE_S3_FORCE_PATH_STYLE=true

# CORS
CORS_ENABLED=true
CORS_ORIGIN=https://${DIRECTUS_DOMAIN}

# Cookies
SESSION_COOKIE_SECURE=true
SESSION_COOKIE_SAME_SITE=lax
ENV

chmod 600 /opt/directus/.env
chown root:root /opt/directus/.env

echo "==> Writing /opt/directus/docker-compose.yml"
cat > /opt/directus/docker-compose.yml <<'COMPOSE'
services:
  database:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: directus
      POSTGRES_USER: directus
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks: [internal]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U directus"]
      interval: 10s
      timeout: 5s
      retries: 10

  cache:
    image: redis:7-alpine
    restart: unless-stopped
    command: ["redis-server", "--save", "", "--appendonly", "no"]
    networks: [internal]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 10

  directus:
    image: directus/directus:latest
    restart: unless-stopped
    depends_on:
      database:
        condition: service_healthy
      cache:
        condition: service_healthy
    env_file: .env
    volumes:
      - ./extensions:/directus/extensions
      - ./uploads:/directus/uploads
      - ./templates:/directus/templates
    ports:
      - "127.0.0.1:8055:8055"
    networks: [internal]
    healthcheck:
      test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8055/server/health || exit 1"]
      interval: 15s
      timeout: 5s
      retries: 20

volumes:
  pgdata:

networks:
  internal:
    driver: bridge
COMPOSE

echo "==> Starting the stack"
cd /opt/directus
docker compose pull
docker compose up -d

echo "==> Waiting for Directus health"
for i in {1..60}; do
  state="$(docker compose ps --format json directus | python3 -c 'import sys,json;[print(j.get("Health","")) for j in (json.loads(l) for l in sys.stdin if l.strip())]' 2>/dev/null | head -n1)"
  if [[ "${state}" == "healthy" ]]; then
    break
  fi
  sleep 3
done

if ! docker compose ps --format json directus \
  | grep -q '"Health":"healthy"'; then
  echo "Directus container not healthy"
  docker compose logs --tail=200 directus || true
  exit 1
fi

echo "==> Bootstrapping admin user"
docker compose exec -T directus npx directus bootstrap || true

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

cat > /etc/nginx/sites-available/directus <<NGINX
upstream directus_backend {
    server 127.0.0.1:8055;
    keepalive 32;
}

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

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

    client_max_body_size 100M;
    proxy_read_timeout   300s;

    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 /websocket {
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        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://directus_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://directus_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/directus /etc/nginx/sites-enabled/directus
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 "${DIRECTUS_EMAIL}" -d "${DIRECTUS_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 "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Public listeners (only nginx should appear):"
ss -lntp | grep -E ':(80|443|8055|5432|6379)\b' || true

echo
echo "Stack:"
docker compose -f /opt/directus/docker-compose.yml ps

echo
echo "Admin URL:"
echo "https://${DIRECTUS_DOMAIN}/admin"
echo
echo "Admin credentials:"
echo "Email:    ${ADMIN_EMAIL}"
echo "Password: ${ADMIN_PASSWORD}"

echo
echo "Final step:"
echo "Open the admin URL, sign in, rotate the bootstrap password, then create the first collection."

Make it executable and run it:

chmod 700 /root/setup-directus-ubuntu22.sh
DIRECTUS_DOMAIN=cms.example.com \
DIRECTUS_EMAIL=ops@example.com \
ADMIN_EMAIL=admin@example.com \
S3_ENDPOINT=https://s3.us-east-1.amazonaws.com \
S3_BUCKET=directus-prod-assets \
S3_REGION=us-east-1 \
S3_KEY=AKIA... \
S3_SECRET='REPLACE' \
/root/setup-directus-ubuntu22.sh

Most installs finish in 5 to 8 minutes on a 2 vCPU / 4 GB VM. After the script prints the admin URL, sign in with the printed credentials, rotate the bootstrap password under User Settings, and create your first collection. The script does not configure host-level backups; PostgreSQL is on a named volume covered by your VM snapshot policy, and assets are off-node by design on S3 — verify both restore paths quarterly.

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