Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
The production box for my post scheduler (Instagram, Threads and more) has Docker, compose and env files, and no source code. GitHub Actions pushes images to GHCR. The box pulls them and restarts what changed. It's a pnpm monorepo: a NestJS API, a worker for the publishing queue (pg-boss on Postgres via Prisma) and a few Next.js apps, with S3 and RDS. Builds run in CI because next build wants 1 to 2 GB of RAM per app and a small instance gets OOM-killed.
EC2, RDS and S3
The instance is a t3.small (2 GB) with a 30 GB gp3 disk, and disk is what fills up: each image is about 1 GB and every deploy leaves one behind. Attach an Elastic IP before touching DNS, because a plain public IP changes on stop and start.
The security group allows 22 for SSH and 80 and 443 for everyone (Let's Encrypt needs 80 from outside). Compose publishes the app ports (3000, 3002, 4001…) on 127.0.0.1 only, so nginx can reach them and the internet can't.
# deploy/docker-compose.yml (trimmed)
services:
api:
image: ${IMAGE_PREFIX:-app}/api:${IMAGE_TAG:-prod}
restart: unless-stopped
env_file: [../apps/api/.env]
environment:
PORT: '4001'
ENABLE_INLINE_WORKER: 'false'
ports:
- '127.0.0.1:4001:4001' # loopback only: nginx can reach it, the internet can't
healthcheck:
test: ['CMD', 'node', '-e', "fetch('http://127.0.0.1:4001/api/v1/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 10s
timeout: 5s
retries: 12
start_period: 40s
worker:
image: ${IMAGE_PREFIX:-app}/api:${IMAGE_TAG:-prod} # same image, different command
restart: unless-stopped
command: ['sh', '-c', 'pnpm start:worker']
env_file: [../apps/api/.env]
environment:
ENABLE_QUEUE: 'true'
The worker reuses the API image. The healthcheck uses node -e fetch(...) because the slim image has no curl. The frontends are still on Vercel.
RDS sits in the same VPC, not public, and its 5432 rule takes the EC2 security group as source instead of an IP. The app's role and database get created with psql from the EC2 box.
S3 gets an IAM user without console access and a policy scoped to one bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject",
"s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"],
"Resource": "arn:aws:s3:::example-bucket/*"
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": "arn:aws:s3:::example-bucket"
}
]
}
Object actions go on bucket/* and listing on the bucket itself. ListBucket is a bucket-level action, so granting it on bucket/* alone makes it fail. Objects are public-read on purpose, because Instagram and Threads fetch media by URL and a 403 gets the post rejected.
Config comes in three layers
deploy/.env holds only IMAGE_PREFIX and IMAGE_TAG, written by CI only when missing. apps/api/.env is the runtime env (database URL, JWT secret, S3 keys, CORS origins), hand-written with chmod 600, never touched by CI. NEXT_PUBLIC_* values are inlined during next build, so they're GitHub repository Variables (a browser bundle is public anyway) passed as build args.
Anything other than NEXT_PUBLIC_* only needs a new container:
cd /srv/app
nano apps/api/.env
# Not enough: restart keeps the same container, and its old environment
# docker restart app-api-1
docker compose -f deploy/docker-compose.yml --env-file deploy/.env \
up -d --force-recreate --no-deps api worker
The Dockerfile refuses to build web or admin when NEXT_PUBLIC_API_URL is empty. That bundle would build fine and break in the browser.
The GitHub Actions jobs
gates is the reusable CI workflow every PR runs (typecheck, build, unit tests, audits). Every later job needs it, so a red commit never gets deployed.
plan diffs before..sha against a services.json. A change under apps/api/ selects api along with the worker, AI and MCP containers that run from its image, while a change in packages/, the lockfile or the Dockerfile selects everything. A frontend with an empty NEXT_PUBLIC_API_URL is dropped with a warning, so one red web build doesn't block the API.
build runs docker/build-push-action per app, tagging :prod and :sha-<7 chars>, and pushes to GHCR with GITHUB_TOKEN. Images are 1 GB because pnpm's symlinks break when packages are copied one by one, and the Dockerfile copies the whole workspace instead. Next's output: 'standalone' would shrink that. I haven't done it yet.
prepare SSHes in, installs Docker if needed and copies the compose file with scp (which needs actions/checkout), so a fresh box only needs apps/api/.env. It checks the key with ssh-keygen -y first, because a bad EC2_SSH_KEY only says error in libcrypto.
deploy goes one service at a time so pulls don't fight over disk. The script, trimmed:
# $service, $also, $port, $prefix, $tag are passed in by the job
export IMAGE_PREFIX="$prefix" IMAGE_TAG="$tag" # a shell var beats deploy/.env
run_compose() { docker compose -f deploy/docker-compose.yml --env-file deploy/.env "$@"; }
run_compose pull "$service" $also
run_compose up -d --no-build "$service" $also
for attempt in $(seq 1 36); do
id=$(run_compose ps -q "$service")
state=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$id")
case "$state" in healthy|running) break ;; esac
[ "$attempt" = 36 ] && { run_compose logs --tail 80 "$service"; exit 1; }
sleep 5
done
# nginx lives on the host, so the app has to answer on loopback
curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${port}/" \
|| { echo "nothing listening on 127.0.0.1:${port}"; exit 1; }
docker image prune -a -f --filter "until=168h" # keep a week to roll back to
Exporting IMAGE_TAG pins the run to the image it just built. The loopback probe is there because nginx lives outside compose: drop the ports: line and containers look healthy while nginx serves 502s.
Migrations are a manual step
The API's build script runs prisma migrate deploy only when DATABASE_URL is set. Render (dev) has it; GitHub Actions doesn't, so the image reaching EC2 has never touched RDS. The Render and Neon database once fell 9 tables behind while every check was green (separate post).
cd /srv/app
C="docker compose -f deploy/docker-compose.yml --env-file deploy/.env"
# exits 1 while migrations are pending: that's the answer, not a crash
$C run --rm --no-deps api pnpm --filter @app/api exec prisma migrate status
$C run --rm --no-deps api pnpm --filter @app/api db:deploy
migrate status exits 1 when something's pending, which pnpm wraps as ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL. The pending list is just above it. The healthcheck won't catch it: /api/v1/health returns 200 even with the database degraded. It's a runbook checklist line for now, and I want it in the deploy job.
Nginx, certbot and rolling back
nginx is installed on the host, outside the workflow. The repo's reference config keeps ports in line with compose:
server {
listen 80;
server_name app.example.com;
# no trailing slash: /homepage has to reach the app unchanged
location /homepage {
proxy_pass http://127.0.0.1:3002;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
server_name api.example.com;
client_max_body_size 500m; # same as the API's upload limit
location / {
proxy_pass http://127.0.0.1:4001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 300s;
}
}
The /homepage proxy_pass (the marketing site's basePath) has no trailing slash, or nginx strips the prefix and assets 404. The API block allows 500 MB bodies to match the upload limit instead of answering 413. Behind the proxy, Express has to trust exactly one hop or the rate limiter sees nginx for every client (that setting in an Express API).
After dig +short api.example.com confirms DNS, sudo certbot --nginx -d app.example.com -d api.example.com adds the 443 blocks, so edit the file on the server from then on.
To roll back, put IMAGE_TAG=sha-1a2b3c4 in front of the compose pull and up -d --no-build api worker. The box keeps a week of images. The next deploy pins a new tag, so a lasting rollback is a revert on the branch. up -d swaps containers, so expect a few seconds of downtime.
When I'd skip AWS
Unless a client's stack is already on AWS or needs IAM roles and private networking, DigitalOcean (Droplet, Managed Postgres, Spaces via AWS_ENDPOINT_URL_S3) runs this setup with fewer knobs.
The dev branch runs free on Vercel, Render and Neon. Render's free plan sleeps after 15 minutes and doesn't allow background workers. The worker shares the API process, and scheduled posts wait for a request to wake it. Neon needs the direct connection string, not -pooler, since pg-boss needs a real session. Fine for dev, not for a post due at nine sharp.
More posts
- 01
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 02
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.
- 03
PageSpeed gave my site 25 on mobile. My own Lighthouse said 90+
My own Lighthouse gave vennee.dev 90+. PageSpeed mobile said 25. A loader hid the LCP, Lighthouse simulated a slow network, and WebGL ran on the CPU.