DEV3 Technologies home

DEV3 Developer Forum

How do I deploy a Next.js app on a VPS with PM2 and Nginx?

Next.js helpSolved0 views
dev3 ·

I have an Ubuntu VPS. I want to run next start permanently, restart it after crashes and reboots, and serve it over HTTPS on my domain. What is the setup?

#nextjs#deployment#nginx#pm2

0

1 reply

dev3 · Accepted answer

1. Build and run

git pull && npm ci && npm run build
npm i -g pm2
pm2 start npm --name myapp -- start -- -p 3000
pm2 save
pm2 startup   # prints a command to run, so PM2 restarts on reboot

With output: "standalone" you can start node .next/standalone/server.js instead (remember to copy public and .next/static).

2. Nginx reverse proxy

server {
  listen 80;
  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";
  }
}
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d example.com -d www.example.com

3. Environment

Put variables in .env.production in the project root (read by next start) or in a PM2 ecosystem file. Remember NEXT_PUBLIC_* values are baked at build time, so build on the server (or in CI) with them set.

4. Zero-downtime-ish deploys

pm2 reload myapp restarts gracefully in cluster mode. Build into a new directory and swap a symlink if you need atomic releases.

Pitfalls

  • Building on a 1 GB VPS can run out of memory; add swap or build in CI.
  • Without X-Forwarded-Proto auth libraries may generate http callback URLs. With Auth.js set AUTH_TRUST_HOST=true.
  • Image optimisation caches to .next/cache; keep it between deploys for speed.

The Nginx config generator helps produce the server block.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.