You have a hardened VPS (Article #1). Now you need a production-ready Docker Compose stack that you can drop in and run. This template gives you:
- PostgreSQL with proper persistence, healthchecks, and backup
- Redis for caching/sessions with persistence
- Nginx reverse proxy with SSL termination (auto via Let’s Encrypt)
- Automated backup to local + optional S3 (Restic + Rclone)
- Healthchecks on every service
- Resource limits to prevent OOM kills
- Log rotation so disk doesn’t fill up
Prerequisites
- VPS from Article #1 (Ubuntu 24.04, Docker + Compose, UFW, Fail2ban)
- Domain pointed to VPS IP (for SSL)
- SSH access as
deployuser (non-root, indockergroup)
Project Structure
/opt/app/
├── docker-compose.yml
├── .env # Generated from .env.example
├── .env.example
├── nginx/
│ ├── nginx.conf
│ ├── conf.d/
│ │ └── default.conf
│ └── certs/ # Let's Encrypt certs (auto-managed)
├── postgres/
│ ├── init/
│ │ └── 01-init.sql
│ └── backup/
│ └── backup.sh
├── redis/
│ └── redis.conf
├── scripts/
│ ├── deploy.sh
│ ├── backup.sh
│ └── restore.sh
└── monitoring/ # Optional: Prometheus exporters
└── docker-compose.monitoring.yml
Step 1: Create Project Directory
sudo mkdir -p /opt/app/{nginx/{conf.d,certs},postgres/{init,backup},redis,scripts,monitoring}
sudo chown -R deploy:deploy /opt/app
cd /opt/app
Step 2: Environment Template (.env.example)
cat > .env.example <<'EOF'
# ──────────────────────────────────────────────
# GENERAL
# ──────────────────────────────────────────────
COMPOSE_PROJECT_NAME=app
TZ=Asia/Makassar
# ──────────────────────────────────────────────
# POSTGRESQL
# ──────────────────────────────────────────────
POSTGRES_DB=appdb
POSTGRES_USER=appuser
POSTGRES_PASSWORD=CHANGE_ME_STRONG_PASSWORD
POSTGRES_PORT=5432
# ──────────────────────────────────────────────
# REDIS
# ──────────────────────────────────────────────
REDIS_PASSWORD=CHANGE_ME_REDIS_PASSWORD
REDIS_PORT=6379
# ──────────────────────────────────────────────
# NGINX / SSL
# ──────────────────────────────────────────────
DOMAIN=yourdomain.com
EMAIL=admin@yourdomain.com
NGINX_HTTP_PORT=80
NGINX_HTTPS_PORT=443
# ──────────────────────────────────────────────
# BACKUP (Restic + Rclone)
# ──────────────────────────────────────────────
BACKUP_RETENTION_DAYS=30
BACKUP_SCHEDULE="0 2 * * *" # Daily 02:00
# Restic repo (local or S3 via rclone)
RESTIC_REPOSITORY=/opt/backups/app
# RESTIC_REPOSITORY=rclone:remote:bucket/app
RESTIC_PASSWORD=CHANGE_ME_RESTIC_PASSWORD
RCLONE_CONFIG=/opt/app/rclone.conf # Optional, for S3
EOF
Copy and edit:
cp .env.example .env
nano .env # Fill in ALL CHANGE_ME values
Step 3: Nginx Configuration
nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
# Performance
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 50M;
# Gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
# Upstreams
upstream app_backend {
server app:3000; # Your app container
keepalive 32;
}
# Include site configs
include /etc/nginx/conf.d/*.conf;
}
nginx/conf.d/default.conf
# HTTP → HTTPS redirect
server {
listen 80;
listen [::]:80;
server_name ${DOMAIN} www.${DOMAIN};
# ACME challenge for Let's Encrypt
location /.well-known/acme-challenge/ {
root /var/www/certbot;
try_files $uri =404;
}
location / {
return 301 https://$host$request_uri;
}
}
# HTTPS server
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${DOMAIN} www.${DOMAIN};
# SSL (managed by certbot)
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' https:;" always;
# Proxy to app
location / {
proxy_pass http://app_backend;
proxy_http_version 1.1;
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_cache_bypass $http_upgrade;
proxy_read_timeout 90s;
proxy_send_timeout 90s;
}
# API rate limiting
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://app_backend;
proxy_http_version 1.1;
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;
}
# Auth endpoints stricter
location /api/auth/login {
limit_req zone=login burst=5 nodelay;
proxy_pass http://app_backend;
proxy_http_version 1.1;
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;
}
# Static assets caching
location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
proxy_pass http://app_backend;
}
# Health check endpoint (no auth, no rate limit)
location /health {
access_log off;
proxy_pass http://app_backend/health;
}
}
Step 4: PostgreSQL Config
postgres/init/01-init.sql
-- Create extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements";
-- Create additional databases if needed
-- CREATE DATABASE appdb_test;
-- Performance settings (applied at runtime via postgresql.conf)
-- shared_buffers = 256MB
-- effective_cache_size = 1GB
-- maintenance_work_mem = 64MB
-- checkpoint_completion_target = 0.9
-- wal_buffers = 16MB
-- default_statistics_target = 100
-- random_page_cost = 1.1
-- effective_io_concurrency = 200
-- work_mem = 4MB
-- min_wal_size = 1GB
-- max_wal_size = 4GB
postgres/backup/backup.sh
#!/bin/bash
set -euo pipefail
BACKUP_DIR="https://dev.to/backups/postgres"
DATE=$(date +%Y%m%d_%H%M%S)
FILE="${BACKUP_DIR}/postgres_${POSTGRES_DB}_${DATE}.sql.gz"
mkdir -p "${BACKUP_DIR}"
echo "[$(date)] Starting PostgreSQL backup..."
pg_dump -h localhost -U "${POSTGRES_USER}" -d "${POSTGRES_DB}"
--no-owner --no-acl --clean --if-exists | gzip > "${FILE}"
echo "[$(date)] Backup saved: ${FILE}"
# Cleanup old backups (keep 30 days)
find "${BACKUP_DIR}" -name "postgres_${POSTGRES_DB}_*.sql.gz" -mtime +30 -delete
echo "[$(date)] PostgreSQL backup complete"
Step 5: Redis Config
redis/redis.conf
# Network
bind 0.0.0.0
port 6379
timeout 300
tcp-keepalive 60
# Security
requirepass ${REDIS_PASSWORD}
protected-mode yes
# Persistence
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /data
# AOF (Append Only File) - more durable
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
# Memory
maxmemory 512mb
maxmemory-policy allkeys-lru
# Logging
loglevel notice
logfile ""
# Clients
maxclients 10000
Step 6: Main Docker Compose (docker-compose.yml)
version: '3.8'
services:
# ──────────────────────────────────────────────
# POSTGRESQL
# ──────────────────────────────────────────────
postgres:
image: postgres:16-alpine
container_name: ${COMPOSE_PROJECT_NAME}-postgres
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
TZ: ${TZ}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./postgres/init:/docker-entrypoint-initdb.d:ro
- ./postgres/backup:/backup:ro
ports:
- "127.0.0.1:${POSTGRES_PORT}:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
deploy:
resources:
limits:
cpus: '1.0'
memory: 1G
reservations:
cpus: '0.25'
memory: 256M
networks:
- internal
# ──────────────────────────────────────────────
# REDIS
# ──────────────────────────────────────────────
redis:
image: redis:7-alpine
container_name: ${COMPOSE_PROJECT_NAME}-redis
restart: unless-stopped
command: redis-server /usr/local/etc/redis/redis.conf
environment:
- REDIS_PASSWORD=${REDIS_PASSWORD}
- TZ=${TZ}
volumes:
- redis_data:/data
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf:ro
ports:
- "127.0.0.1:${REDIS_PORT}:6379"
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
interval: 10s
timeout: 3s
retries: 5
start_period: 10s
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.1'
memory: 128M
networks:
- internal
# ──────────────────────────────────────────────
# NGINX (Reverse Proxy + SSL)
# ──────────────────────────────────────────────
nginx:
image: nginx:alpine
container_name: ${COMPOSE_PROJECT_NAME}-nginx
restart: unless-stopped
ports:
- "${NGINX_HTTP_PORT}:80"
- "${NGINX_HTTPS_PORT}:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./nginx/certs:/etc/letsencrypt:ro
- certbot_www:/var/www/certbot
depends_on:
- app
healthcheck:
test: ["CMD", "nginx", "-t"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
deploy:
resources:
limits:
cpus: '0.5'
memory: 128M
reservations:
cpus: '0.1'
memory: 32M
networks:
- internal
- external
# ──────────────────────────────────────────────
# CERTBOT (Auto SSL)
# ──────────────────────────────────────────────
certbot:
image: certbot/certbot:latest
container_name: ${COMPOSE_PROJECT_NAME}-certbot
restart: unless-stopped
entrypoint: "https://dev.to/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done'"
volumes:
- ./nginx/certs:/etc/letsencrypt
- certbot_www:/var/www/certbot
environment:
- DOMAIN=${DOMAIN}
- EMAIL=${EMAIL}
networks:
- external
# ──────────────────────────────────────────────
# YOUR APPLICATION (Replace with your service)
# ──────────────────────────────────────────────
app:
image: your-registry/your-app:latest
container_name: ${COMPOSE_PROJECT_NAME}-app
restart: unless-stopped
environment:
- DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
- REDIS_URL=redis://:${REDIS_PASSWORD}@redis:6379
- NODE_ENV=production
- TZ=${TZ}
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
deploy:
resources:
limits:
cpus: '1.0'
memory: 1G
reservations:
cpus: '0.25'
memory: 256M
networks:
- internal
# ──────────────────────────────────────────────
# BACKUP (Restic)
# ──────────────────────────────────────────────
backup:
image: restic/restic:latest
container_name: ${COMPOSE_PROJECT_NAME}-backup
restart: unless-stopped
environment:
- RESTIC_REPOSITORY=${RESTIC_REPOSITORY}
- RESTIC_PASSWORD=${RESTIC_PASSWORD}
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-}
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-}
volumes:
- postgres_data:/data/postgres:ro
- redis_data:/data/redis:ro
- ./scripts:/scripts:ro
- ./rclone.conf:/config/rclone/rclone.conf:ro
entrypoint: |
/bin/sh -c "
apk add --no-cache bash postgresql-client redis dcron &&
echo '${BACKUP_SCHEDULE} /scripts/backup.sh >> /var/log/backup.log 2>&1' > /etc/crontabs/root &&
crond -f -l 8
"
depends_on:
- postgres
- redis
networks:
- internal
# ──────────────────────────────────────────────
# VOLUMES
# ──────────────────────────────────────────────
volumes:
postgres_data:
driver: local
redis_data:
driver: local
certbot_www:
driver: local
# ──────────────────────────────────────────────
# NETWORKS
# ──────────────────────────────────────────────
networks:
internal:
driver: bridge
internal: true # No internet access for internal services
external:
driver: bridge
Step 7: Backup Script (scripts/backup.sh)
#!/bin/bash
set -euo pipefail
echo "[$(date)] Starting backup..."
# 1. PostgreSQL dump
echo "[$(date)] Dumping PostgreSQL..."
pg_dump -h postgres -U "${POSTGRES_USER}" -d "${POSTGRES_DB}"
--no-owner --no-acl --clean --if-exists | gzip > /tmp/postgres_$(date +%Y%m%d_%H%M%S).sql.gz
# 2. Redis dump (RDB + AOF)
echo "[$(date)] Copying Redis data..."
cp /data/redis/dump.rdb /tmp/redis_dump_$(date +%Y%m%d_%H%M%S).rdb 2>/dev/null || true
cp /data/redis/appendonly.aof /tmp/redis_aof_$(date +%Y%m%d_%H%M%S).aof 2>/dev/null || true
# 3. Restic backup
echo "[$(date)] Running restic backup..."
restic backup /tmp/postgres_*.sql.gz /tmp/redis_*.rdb /tmp/redis_*.aof
--tag "scheduled,$(date +%Y-%m-%d)"
--host "${COMPOSE_PROJECT_NAME}"
# 4. Cleanup local temp
rm -f /tmp/postgres_*.sql.gz /tmp/redis_*.rdb /tmp/redis_*.aof
# 5. Prune old snapshots
echo "[$(date)] Pruning old snapshots..."
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
echo "[$(date)] Backup complete"
chmod +x scripts/backup.sh
Step 8: Deploy Script (scripts/deploy.sh)
#!/bin/bash
set -euo pipefail
cd /opt/app
echo "[$(date)] Pulling latest images..."
docker compose pull
echo "[$(date)] Building app image (if local)..."
# docker compose build app # Uncomment if building locally
echo "[$(date)] Starting services..."
docker compose up -d --remove-orphans
echo "[$(date)] Waiting for healthchecks..."
sleep 10
# Verify all services healthy
for service in postgres redis nginx app; do
status=$(docker compose ps --format json | jq -r ".[] | select(.Service=="$service") | .Health")
if [[ "$status" != "healthy" ]]; then
echo "❌ $service is not healthy: $status"
docker compose logs "$service" --tail 50
exit 1
fi
echo "✅ $service healthy"
done
echo "[$(date)] Deploy complete"
chmod +x scripts/deploy.sh
Step 9: Initial SSL Certificate
# 1. Start nginx + certbot only
docker compose up -d nginx certbot
# 2. Get initial certificate (run once)
docker compose run --rm certbot certonly
--webroot -w /var/www/certbot
-d ${DOMAIN} -d www.${DOMAIN}
--email ${EMAIL}
--agree-tos --non-interactive
# 3. Reload nginx
docker compose exec nginx nginx -s reload
# 4. Start all services
docker compose up -d
Step 10: Verification Checklist
# 1. All containers running
docker compose ps
# 2. Healthchecks passing
docker compose ps --format "table {{.Service}}t{{.Status}}t{{.Health}}"
# 3. PostgreSQL accessible
docker compose exec postgres pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}
# 4. Redis accessible
docker compose exec redis redis-cli -a ${REDIS_PASSWORD} ping
# 5. Nginx config valid
docker compose exec nginx nginx -t
# 6. SSL certificate valid
curl -I https://${DOMAIN}
# 7. App responding
curl -f https://${DOMAIN}/health
# 8. Backup runs manually
docker compose run --rm backup /scripts/backup.sh
# 9. Check logs
docker compose logs -f --tail 100
Resource Requirements (Minimum VPS)
| Service | CPU | RAM | Disk |
|---|---|---|---|
| PostgreSQL | 1.0 | 1 GB | 10+ GB |
| Redis | 0.5 | 512 MB | 1+ GB |
| Nginx | 0.5 | 128 MB | 100 MB |
| App (example) | 1.0 | 1 GB | 2+ GB |
| Backup | 0.25 | 256 MB | 5+ GB |
| Total | 3.25 | ~3 GB | ~20 GB |
Recommended: 2 vCPU, 4 GB RAM, 40 GB SSD (Hetzner CX42 ~€16/mo or DO $24/mo)
What’s Next
This stack is your production foundation. Next articles:
- Monitoring: Prometheus + Grafana + Loki (Article #3)
- Alerts: Grafana Alerting → Telegram/Slack (Article #4)
- Logs: Loki + Promtail for containers + systemd (Article #5)
- Dashboards: Ready-to-import JSON (Article #6 — Gumroad $10)
- Hardening: SSH + Kernel + Auditd (Article #7)
- Backup: Restic + Rclone → S3/B2 (Article #8)
Part of the “Production Infrastructure for Developers” series. Previous: VPS Setup in 15 Minutes
Appendix: Quick Commands Reference
# Deploy
cd /opt/app && ./scripts/deploy.sh
# Backup manually
docker compose run --rm backup /scripts/backup.sh
# View logs
docker compose logs -f postgres
docker compose logs -f nginx
# Restart single service
docker compose restart app
# Update images
docker compose pull && docker compose up -d --remove-orphans
# Scale app (if stateless)
docker compose up -d --scale app=3
# Shell into container
docker compose exec postgres psql -U ${POSTGRES_USER} -d ${POSTGRES_DB}
docker compose exec redis redis-cli -a ${REDIS_PASSWORD}
# Backup status
restic snapshots --repo ${RESTIC_REPOSITORY}