Skip to content

Deploying Strapi v5 on Ubuntu 22.04 (production-ready)

Stand up a hardened Strapi v5 headless CMS on Ubuntu 22.04 — PostgreSQL on localhost, PM2 process manager, nginx + Let's Encrypt, S3 upload provider.

You ran npx create-strapi-app@latest, pointed it at PostgreSQL, ran npm run start in a tmux session, opened the firewall on :1337, and the frontend team started building. Six months later, the tmux died because the box rebooted for kernel patching and nobody noticed for two days, every uploaded image lives in public/uploads/ on the application node so the disk has grown past 80 GB and the snapshot job times out, the admin URL is on :1337 over HTTP because nobody put nginx and Let’s Encrypt in front of it, the four JWT secrets in .env are all the same default-looking string from a copy-paste, and the editor lost half a day’s work yesterday when the process crashed and there was no restart-on-failure policy.

What’s happening

A Strapi v5 deployment that is actually production-ready needs more than npm start. The Node process has to be supervised — PM2 with pm2 startup systemd is the canonical pattern; tmux is not a process manager. PostgreSQL must be bound to 127.0.0.1 only and reachable only by Strapi on the same host. Strapi’s four cryptographic secrets — APP_KEYS, API_TOKEN_SALT, ADMIN_JWT_SECRET, JWT_SECRET, plus TRANSFER_TOKEN_SALT and the new v5 ENCRYPTION_KEY — must each be regenerated to high-entropy random strings, never the example values in the docs. nginx terminates TLS in front of Strapi’s internal :1337 listener with a real Let’s Encrypt cert. The upload provider has to be switched to @strapi/provider-upload-aws-s3 so assets are stateless — the application node should be rebuildable in fifteen minutes. None of these are individually critical — skip them and the CMS becomes the VM that nobody can rebuild.

How to verify

After install, the listeners should look like this:

ss -lntp | grep -E ':(80|443|1337|5432)\b'
# 127.0.0.1:5432   postgres
# 127.0.0.1:1337   node (strapi)
# 0.0.0.0:80       nginx
# 0.0.0.0:443      nginx

PostgreSQL on 5432 must be 127.0.0.1, never 0.0.0.0. The admin URL should answer:

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

PM2 should report the process online:

sudo -i -u strapi pm2 list
# strapi    online    0    fork

PostgreSQL responding:

sudo -u postgres pg_isready -h 127.0.0.1
# 127.0.0.1:5432 - accepting connections

If PM2 shows errored or stopped, the process is in restart-loop and the journal will tell you why. If the admin URL returns 502, the Node process died after the last deploy and nobody noticed.

The fix

Save the script below as /root/setup-strapi-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, PostgreSQL 14 with listen_addresses = 'localhost' and a dedicated strapi role, Node.js 20 LTS via NodeSource, a dedicated strapi system user (the Node process must not run as root), the project scaffolded via npx create-strapi@latest with the --quickstart skipped in favour of an interactive-free Postgres flow, .env written with regenerated secrets and an S3 upload provider block, the project built (npm run build), PM2 installed globally and configured to start under systemd with LimitNOFILE=64000, nginx + Let’s Encrypt, and a poll loop that waits for :1337 before declaring success.

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

### Ubuntu 22.04 Strapi v5 clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs PostgreSQL 14 + Node.js 20 LTS + Strapi v5 under PM2
### S3-compatible upload provider; 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

: "${STRAPI_DOMAIN:?Set STRAPI_DOMAIN=cms.example.com}"
: "${STRAPI_EMAIL:?Set STRAPI_EMAIL=ops@example.com for Let's Encrypt}"
: "${S3_ENDPOINT:?Set S3_ENDPOINT, e.g. https://s3.us-east-1.amazonaws.com}"
: "${S3_BUCKET:?Set S3_BUCKET}"
: "${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)}"

PROJECT_NAME="${PROJECT_NAME:-strapi-prod}"
DB_PASSWORD="${DB_PASSWORD:-$(openssl rand -hex 24)}"
APP_KEYS="${APP_KEYS:-$(openssl rand -hex 32),$(openssl rand -hex 32),$(openssl rand -hex 32),$(openssl rand -hex 32)}"
API_TOKEN_SALT="${API_TOKEN_SALT:-$(openssl rand -hex 32)}"
ADMIN_JWT_SECRET="${ADMIN_JWT_SECRET:-$(openssl rand -hex 32)}"
JWT_SECRET="${JWT_SECRET:-$(openssl rand -hex 32)}"
TRANSFER_TOKEN_SALT="${TRANSFER_TOKEN_SALT:-$(openssl rand -hex 32)}"
ENCRYPTION_KEY="${ENCRYPTION_KEY:-$(openssl rand -hex 32)}"
NODE_MAJOR=20

echo
echo "========================================"
echo "Strapi Ubuntu 22.04 Setup"
echo "Domain: ${STRAPI_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 git \
  software-properties-common build-essential

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-strapi.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-strapi.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 PostgreSQL 14"
apt-get -y install postgresql postgresql-contrib

echo "==> Locking PostgreSQL to localhost"
PG_CONF="/etc/postgresql/14/main/postgresql.conf"
sed -i "s|^#*listen_addresses.*|listen_addresses = 'localhost'|" "$PG_CONF"
systemctl restart postgresql

echo "==> Creating Strapi database and role"
sudo -u postgres psql <<SQL
DO \$\$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'strapi') THEN
    CREATE ROLE strapi LOGIN PASSWORD '${DB_PASSWORD}';
  ELSE
    ALTER ROLE strapi WITH PASSWORD '${DB_PASSWORD}';
  END IF;
END
\$\$;
SQL

sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='strapi'" | grep -q 1 \
  || sudo -u postgres createdb -O strapi strapi

echo "==> Installing Node.js ${NODE_MAJOR} LTS"
curl -fsSL https://deb.nodesource.com/setup_${NODE_MAJOR}.x | bash -
apt-get -y install nodejs

echo "==> Creating strapi system user"
if ! id -u strapi >/dev/null 2>&1; then
  useradd --create-home --shell /bin/bash --user-group strapi
fi

echo "==> Scaffolding Strapi project at /home/strapi/${PROJECT_NAME}"
sudo -i -u strapi bash <<INSTALL
set -euo pipefail
cd /home/strapi
if [[ ! -d ${PROJECT_NAME} ]]; then
  npx --yes create-strapi@latest ${PROJECT_NAME} \
    --no-run \
    --skip-cloud \
    --skip-db \
    --use-npm \
    --typescript
fi
cd ${PROJECT_NAME}
npm install @strapi/provider-upload-aws-s3
INSTALL

echo "==> Writing /home/strapi/${PROJECT_NAME}/.env"
cat > /home/strapi/${PROJECT_NAME}/.env <<ENV
HOST=127.0.0.1
PORT=1337
URL=https://${STRAPI_DOMAIN}

APP_KEYS=${APP_KEYS}
API_TOKEN_SALT=${API_TOKEN_SALT}
ADMIN_JWT_SECRET=${ADMIN_JWT_SECRET}
JWT_SECRET=${JWT_SECRET}
TRANSFER_TOKEN_SALT=${TRANSFER_TOKEN_SALT}
ENCRYPTION_KEY=${ENCRYPTION_KEY}

NODE_ENV=production

DATABASE_CLIENT=postgres
DATABASE_HOST=127.0.0.1
DATABASE_PORT=5432
DATABASE_NAME=strapi
DATABASE_USERNAME=strapi
DATABASE_PASSWORD=${DB_PASSWORD}
DATABASE_SSL=false

# S3-compatible upload provider
AWS_ACCESS_KEY_ID=${S3_KEY}
AWS_ACCESS_SECRET=${S3_SECRET}
AWS_REGION=${S3_REGION}
AWS_BUCKET=${S3_BUCKET}
AWS_ENDPOINT=${S3_ENDPOINT}
ENV

chmod 600 /home/strapi/${PROJECT_NAME}/.env
chown strapi:strapi /home/strapi/${PROJECT_NAME}/.env

echo "==> Wiring S3 upload provider into config/plugins.ts"
cat > /home/strapi/${PROJECT_NAME}/config/plugins.ts <<'PLUGINS'
export default ({ env }) => ({
  upload: {
    config: {
      provider: 'aws-s3',
      providerOptions: {
        s3Options: {
          credentials: {
            accessKeyId: env('AWS_ACCESS_KEY_ID'),
            secretAccessKey: env('AWS_ACCESS_SECRET'),
          },
          region: env('AWS_REGION'),
          endpoint: env('AWS_ENDPOINT'),
          forcePathStyle: true,
          params: {
            Bucket: env('AWS_BUCKET'),
          },
        },
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
});
PLUGINS

chown strapi:strapi /home/strapi/${PROJECT_NAME}/config/plugins.ts

echo "==> Building Strapi"
sudo -i -u strapi bash <<BUILD
set -euo pipefail
cd /home/strapi/${PROJECT_NAME}
NODE_ENV=production npm run build
BUILD

echo "==> Installing PM2 globally"
npm install -g pm2

echo "==> Writing PM2 ecosystem file"
cat > /home/strapi/${PROJECT_NAME}/ecosystem.config.js <<ECO
module.exports = {
  apps: [
    {
      name: 'strapi',
      cwd: '/home/strapi/${PROJECT_NAME}',
      script: 'npm',
      args: 'run start',
      env: {
        NODE_ENV: 'production',
      },
      max_memory_restart: '1G',
      autorestart: true,
      watch: false,
      time: true,
    },
  ],
};
ECO

chown strapi:strapi /home/strapi/${PROJECT_NAME}/ecosystem.config.js

echo "==> Starting Strapi under PM2 as the strapi user"
sudo -i -u strapi bash -lc "cd /home/strapi/${PROJECT_NAME} && pm2 start ecosystem.config.js && pm2 save"

echo "==> Generating PM2 startup unit for the strapi user"
env PATH="$PATH:/usr/bin" pm2 startup systemd -u strapi --hp /home/strapi
systemctl daemon-reload

echo "==> Raising LimitNOFILE on the PM2 unit"
mkdir -p /etc/systemd/system/pm2-strapi.service.d
cat > /etc/systemd/system/pm2-strapi.service.d/override.conf <<'PM2_LIMITS'
[Service]
LimitNOFILE=64000
PM2_LIMITS
systemctl daemon-reload
systemctl enable --now pm2-strapi
systemctl restart pm2-strapi

echo "==> Waiting for Strapi to listen on 127.0.0.1:1337"
for i in {1..120}; do
  if ss -lntp | grep -q '127.0.0.1:1337'; then
    break
  fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:1337'; then
  echo "Strapi failed to listen on 127.0.0.1:1337"
  sudo -i -u strapi bash -lc "pm2 logs strapi --lines 200 --nostream" || true
  exit 1
fi

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

cat > /etc/nginx/sites-available/strapi <<NGINX
upstream strapi_backend {
    server 127.0.0.1:1337;
    keepalive 32;
}

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

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${STRAPI_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 / {
        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://strapi_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/strapi /etc/nginx/sites-enabled/strapi
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 "${STRAPI_EMAIL}" -d "${STRAPI_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 "Listeners:"
ss -lntp | grep -E ':(80|443|1337|5432)\b' || true

echo
echo "Services:"
systemctl is-active postgresql nginx fail2ban chrony pm2-strapi || true

echo
echo "PM2 process:"
sudo -i -u strapi pm2 list || true

echo
echo "Database password (record this somewhere safe):"
echo "${DB_PASSWORD}"

echo
echo "Admin URL:"
echo "https://${STRAPI_DOMAIN}/admin"

echo
echo "Final step:"
echo "Open the admin URL above, create the first super-admin account (this is the Owner), then create your first content type."

Make it executable and run it:

chmod 700 /root/setup-strapi-ubuntu22.sh
STRAPI_DOMAIN=cms.example.com \
STRAPI_EMAIL=ops@example.com \
S3_ENDPOINT=https://s3.us-east-1.amazonaws.com \
S3_BUCKET=strapi-prod-uploads \
S3_REGION=us-east-1 \
S3_KEY=AKIA... \
S3_SECRET='REPLACE' \
/root/setup-strapi-ubuntu22.sh

Most installs finish in 8 to 15 minutes on a 2 vCPU / 4 GB VM — the bulk of the time is npx create-strapi pulling the scaffold and npm run build. The first account created on the admin URL becomes the super admin. Create your first content type immediately, publish a test entry with an image upload, and verify the uploaded file ends up in the S3 bucket — never in public/uploads/ on the box. The script does not configure host-level backups; pg_dump strapi should be in your VM snapshot policy, and uploads are off-node by design on S3.

Run the production Strapi tier on a Stack Harbor-managed environment with patch cadence, monitoring and Sev-1 escalation built in: see Cloud PaaS → and Contact us about a managed PaaS environment →.