VPS Tutorials
Deploy Next.js on a VPS: standalone Docker, HTTPS and rollback
Deploy an App Router project with standalone Docker, Compose and Caddy. Include static assets, handle build and runtime variables, test health and preserve rollback images.

This deployment is for an existing App Router project with package-lock.json. It builds a standalone Node.js image, runs it with Compose and puts Caddy in front for HTTPS. It is a single-server design with a possible interruption during replacement; rolling deployments need coordinated instances, versions and shared caches.
| Requirement | Suitable approach | Reason |
|---|---|---|
| Static pages without server features | Static export and web server | No Node.js service to maintain |
| SSR, Route Handlers, Server Actions, ISR | Standalone Node.js container | Needs the Next.js server |
| Multiple servers/rolling updates | Load balancer and coordinated cache/releases | Compose alone cannot synchronize instances |
For ordinary Express applications, see Node.js deployment. Here we focus on Next.js artifacts and runtime behavior.
Use Ubuntu 24.04, supported Docker/Compose and working DNS for app.example.com. An initial 2 vCPU/4 GB/40 GB SSD budget is a planning example, not an official minimum. Large next build workloads may need 8 GB or a CI builder. Reserve room for images, logs and rollback tags. Open 80/443, restrict SSH and keep application 3000 private.
Verify npm ci and npm run build locally. This example uses npm; adapt every installation command consistently for pnpm/Yarn and its lockfile.
Merge standalone output into next.config.ts without deleting existing settings:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
output: 'standalone',
}
export default nextConfig
Create app/api/health/route.ts:
export async function GET() {
return Response.json({ status: 'ok' })
}
This checks whether the web process answers, not database/queue/API availability. Monitor dependencies separately and ensure authentication/locale middleware does not unexpectedly redirect the probe. A healthcheck marks a container unhealthy; Docker's restart policy does not automatically restart it solely for that status.
Create Dockerfile:
FROM node:24-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
FROM node:24-bookworm-slim AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN mkdir -p public && npm run build
FROM node:24-bookworm-slim AS runner
WORKDIR /app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
RUN mkdir -p .next && chown node:node .next
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Standalone output does not automatically include public or .next/static. Missing copies can leave the homepage working while assets return 404. The example uses Node 24; check your Next.js version and native dependencies against that runtime. Monorepos may need outputFileTracingRoot and adjusted nested artifact paths. Keep uploads in persistent volumes/object storage rather than the image; the non-root user needs write access only where required.
Create .dockerignore:
node_modules
.next
.git
.env*
app.env
*.log
Create compose.yaml:
services:
app:
image: nextjs-app:${APP_VERSION}
build: .
init: true
restart: unless-stopped
env_file:
- ./app.env
environment:
NODE_ENV: production
HOSTNAME: 0.0.0.0
PORT: '3000'
healthcheck:
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:3000/api/health', r => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
mem_limit: 1g
cpus: '1.5'
pids_limit: 256
security_opt:
- no-new-privileges:true
caddy:
image: caddy:2
restart: unless-stopped
depends_on:
app:
condition: service_healthy
environment:
DOMAIN: ${DOMAIN}
ports:
- '80:80'
- '443:443'
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
volumes:
caddy_data:
caddy_config:
The runtime memory/CPU limits are examples to measure and adjust; they do not limit the image build. Keep Caddy's state volumes persistent. Compose's dependency health condition governs startup, not continuous application recovery.
Create Caddyfile:
{$DOMAIN} {
encode zstd gzip
reverse_proxy app:3000
}
.env supplies Compose interpolation; app.env supplies server runtime variables:
# .env
DOMAIN=app.example.com
APP_VERSION=2026-09-25-a1b2c3d
# app.env:仅示例;替换为你的真实服务端变量
API_BASE_URL=https://api.example.com
Add .env and app.env to .gitignore, and protect them with chmod 600 .env app.env. The second file's comment is an example; replace the value with your actual server setting.
Never put secrets in NEXT_PUBLIC_: client values are embedded at next build. Changing NEXT_PUBLIC_ needs a rebuild. Since .env files are excluded from the build context and env_file is runtime-only, explicitly provide public build values through matching Docker build arguments/environment before the build command. Use build-secret mechanisms for private build-time credentials, not public variables or persistent image layers. Server settings used during prerendering may also be evaluated at build time.
docker compose config --quiet
docker compose build app
docker compose up -d
docker compose ps
docker compose logs --tail=100 app caddy
curl -I https://app.example.com/
docker compose config --quiet checks syntax only. Verify image build, endpoint, assets and certificate separately. Caddy needs correct reachable A/AAAA and public 80/443 for the usual challenge method. If Nginx, a hosting panel or another gateway already owns those ports, integrate with the chosen existing gateway instead of starting a competitor.
Use a commit/release identifier for APP_VERSION; do not overwrite latest each release:
docker compose build app
docker compose up -d --no-deps app
docker compose ps
curl -fsS https://app.example.com/api/health
Replacing the app may briefly interrupt requests. Verify health and real pages after deployment. To roll back, set .env's APP_VERSION to the retained old image and run docker compose up -d --no-deps app. Verify the image exists and use --no-build when preventing an accidental rebuild of new source under an old tag. Do not prune rollback images beforehand. A code rollback does not reverse database migration; plan compatible schema changes or tested data recovery.
Back up Git, protected .env/app.env, real databases/uploads/object storage and relevant gateway state. .next cache is not the sole source of durable user data. Keep offsite copies and test isolated recovery. For limits/logging, see production Compose. Multi-instance deployments additionally need consistent build identifiers, server-action keys and supported cache coordination.
| Symptom | Check first | Likely action |
|---|---|---|
| 502 | docker compose ps, docker compose logs app | Inspect build, readiness and Caddy upstream |
/_next/static/* returns 404 | /app/.next/static in image | Fix static COPY and rebuild |
public image 404 | /app/public | Check COPY and Linux filename case |
| New variable ignored | NEXT_PUBLIC_ prefix | Rebuild client values; inspect prerender/runtime use |
| Builder killed | free -h, dmesg, docker system df | Inspect OOM, increase builder capacity or use CI; preserve old images/data |
| No certificate | DNS, 80/443, firewall, Caddy logs | Correct records/listeners and inspect issuance |
References: Next.js self-hosting, standalone Docker example, production Compose, Caddy HTTPS. Test build, health, static assets and rollback on the actual hostname before treating the deployment as ready.