How We Deploy Next.js + Strapi on a Small VPS (Production Setup)

2026-12-02来源 dev.toEnglish

At our agency, most client websites run on the same stack: Next.js for the frontend, Strapi as the headless CMS, and PostgreSQL for data — all on a single VPS.

No Kubernetes, no managed platform bills that grow with traffic. Just one server that costs around $10–20/month and is easy for a small team to maintain.

This post is the exact setup we use, including the mistakes that cost us time early on.

The architecture

 ┌──────────── VPS (Ubuntu 24.04) ────────────┐ example.com ───▶ │ Nginx ──▶ Next.js (127.0.0.1:3000) [PM2] │ cms.example.com ▶│ Nginx ──▶ Strapi (127.0.0.1:1337) [PM2] │ │ PostgreSQL (127.0.0.1:5432) │ └────────────────────────────────────────────┘ 
  • Nginx terminates SSL and proxies to the two Node apps.
  • PM2 keeps both apps alive and restarts them on reboot.
  • Next.js talks to Strapi over 127.0.0.1, not through the public domain. Faster, and no extra SSL hop.

Recommended size: 2 vCPU / 4 GB RAM. You can run on 2 GB, but read the swap section first.

Step 1 — Prepare the server

Create a non-root user, enable the firewall:

adduser deploy usermod -aG sudo deploy ufw allow OpenSSH ufw allow 'Nginx Full' ufw enable 

Add swap (do not skip this)

The Strapi admin panel build is memory-hungry. On a 2 GB server, npm run build can get killed by the OOM killer with no helpful error message. Swap fixes it:

sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab 

Step 2 — Install Node.js, PM2, Nginx, PostgreSQL

curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - sudo apt install -y nodejs nginx postgresql sudo npm install -g pm2 

Use an LTS Node version supported by your Strapi version (Strapi 5 supports Node 20 and 22).

Step 3 — Create the database

sudo -u postgres psql 
CREATE USER strapi WITH PASSWORD 'use-a-long-random-password'; CREATE DATABASE strapi OWNER strapi; \q 

PostgreSQL listens only on localhost by default — keep it that way.

Step 4 — Deploy Strapi

Clone your Strapi project to /var/www/cms, then create .env:

HOST=127.0.0.1 PORT=1337 PUBLIC_URL=https://cms.example.com DATABASE_CLIENT=postgres DATABASE_HOST=127.0.0.1 DATABASE_PORT=5432 DATABASE_NAME=strapi DATABASE_USERNAME=strapi DATABASE_PASSWORD=use-a-long-random-password # Generate each with: openssl rand -base64 32 APP_KEYS=key1,key2 API_TOKEN_SALT=... ADMIN_JWT_SECRET=... TRANSFER_TOKEN_SALT=... JWT_SECRET=... ENCRYPTION_KEY=... 

Tell Strapi it runs behind a proxy, otherwise the admin panel and media URLs break. In config/server.ts:

export default ({ env }) => ({ host: env('HOST', '0.0.0.0'), port: env.int('PORT', 1337), url: env('PUBLIC_URL'), proxy: true, app: { keys: env.array('APP_KEYS'), }, }); 

Build and start:

cd /var/www/cms npm ci NODE_ENV=production npm run build NODE_ENV=production pm2 start npm --name cms -- run start 

⚠️ Build with NODE_ENV=production. Building in development mode and running in production is a classic source of "admin panel is blank" bugs.

Step 5 — Deploy Next.js

Clone the frontend to /var/www/web and create .env.production:

STRAPI_URL=http://127.0.0.1:1337 STRAPI_TOKEN=your-read-only-api-token REVALIDATE_SECRET=another-long-random-string 

Create a read-only API token in Strapi (Settings → API Tokens). Never ship a full-access token to the frontend server.

A small fetch helper with cache tags

// lib/strapi.ts export async function strapi<T>(path: string, tag: string): Promise<T> { const res = await fetch(`${process.env.STRAPI_URL}/api/${path}`, { headers: { Authorization: `Bearer ${process.env.STRAPI_TOKEN}` }, next: { revalidate: 3600, tags: [tag] }, }); if (!res.ok) throw new Error(`Strapi ${res.status}: ${path}`); return res.json(); } 

Usage:

const { data } = await strapi<{ data: Article[] }>( 'articles?sort=publishedAt:desc', 'article' ); 

Pages are served from cache, so the site stays fast and Strapi barely gets hit.

On-demand revalidation (content updates in seconds, not hours)

Caching for an hour is great until an editor publishes a post and asks why it isn't live. The fix: let Strapi tell Next.js when content changes.

// app/api/revalidate/route.ts import { revalidateTag } from 'next/cache'; import { NextRequest, NextResponse } from 'next/server'; export async function POST(req: NextRequest) { if (req.headers.get('x-revalidate-secret') !== process.env.REVALIDATE_SECRET) { return NextResponse.json({ ok: false }, { status: 401 }); } const body = await req.json(); const model = body?.model; // e.g. "article" if (model) revalidateTag(model); return NextResponse.json({ revalidated: true, model }); } 

Then in Strapi: Settings → Webhooks → Create

  • URL: https://example.com/api/revalidate
  • Header: x-revalidate-secret = your secret
  • Events: Entry create / update / delete / publish / unpublish

Because the cache tag matches Strapi's model name, publishing an article refreshes only article pages.

Note: this is written for Next.js 15 (App Router). In Next.js 16, revalidateTag takes a second argument — check the docs for your version.

Allow Strapi images

Strapi returns media URLs like /uploads/photo.jpg. Prefix them with your CMS domain and allow it in next.config.ts:

const nextConfig = { images: { remotePatterns: [{ protocol: 'https', hostname: 'cms.example.com' }], }, }; export default nextConfig; 

Build and start:

cd /var/www/web npm ci npm run build pm2 start npm --name web -- start 

Step 6 — Nginx + SSL

/etc/nginx/sites-available/example.com:

server { server_name example.com www.example.com; location / { proxy_pass http://127.0.0.1:3000; 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; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; } } 

/etc/nginx/sites-available/cms.example.com:

server { server_name cms.example.com; # Default is 1 MB — editors WILL upload bigger images  client_max_body_size 50M; location / { proxy_pass http://127.0.0.1:1337; 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; } } 

Enable and issue certificates:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo ln -s /etc/nginx/sites-available/cms.example.com /etc/nginx/sites-enabled/ sudo nginx -t && sudo systemctl reload nginx sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com -d cms.example.com 

Step 7 — Survive reboots

pm2 startup systemd # run the command it prints pm2 save 

Reboot once to test it. Seriously — find out now, not at 2 a.m.

Step 8 — Backups (the step everyone skips)

Two things to back up: the database and /var/www/cms/public/uploads.

Put the DB password in ~/.pgpass (127.0.0.1:5432:strapi:strapi:PASSWORD, then chmod 600 ~/.pgpass), and add a cron job (crontab -e):

0 3 * * * pg_dump -h 127.0.0.1 -U strapi strapi | gzip > /home/deploy/backups/db-$(date +\%F).sql.gz 15 3 * * * tar -czf /home/deploy/backups/uploads-$(date +\%F).tar.gz -C /var/www/cms/public uploads 30 3 * * * find /home/deploy/backups -type f -mtime +14 -delete 

Then copy backups off the server (object storage, another VPS). A backup on the same disk isn't a backup.

Step 9 — A one-command deploy

#!/usr/bin/env bash # deploy-web.sh set -euo pipefail cd /var/www/web git pull --ff-only npm ci npm run build pm2 reload web 

Good enough for most client sites. If you need true zero-downtime deploys, build into a separate directory (or use output: 'standalone') and switch over after the build succeeds.

Gotchas we hit (so you don't have to)

Symptom Cause Fix
Strapi build dies silently Out of memory Add swap / 4 GB RAM
Admin panel loads but API calls fail Missing url / proxy in server.ts Set PUBLIC_URL + proxy: true
Image upload fails with 413 Nginx 1 MB default client_max_body_size 50M
Published post not showing Cached fetch, no revalidation Strapi webhook → revalidateTag
next/image error on Strapi images Host not allowed Add remotePatterns
Site down after server reboot PM2 not registered pm2 startup + pm2 save

When this setup is not enough

One VPS is a great fit for marketing sites, blogs, and small e-commerce. Consider splitting services or moving to managed infrastructure when you need high availability, heavy traffic spikes, or a team deploying many times a day.

What's next in this series: Technical SEO for Next.js + Strapi — sitemaps, metadata from the CMS, and schema markup.

How do you deploy your headless CMS? Drop your setup in the comments — always curious how other teams do it. 👇

I run Tấn Phát Digital, a web design & SEO agency in Ho Chi Minh City, Vietnam. We build most of our client sites on Next.js + Strapi.

原文:https://www.a8q9.cn/en/article/how-we-deploy-next-js-strapi-on-a-small-vps-production-setup-932e7a.html

相关文章