Guides 15 min read ·
How to Deploy a Next.js App on a VPS (Ubuntu, Nginx, PM2 and Free SSL)
Deploy Next.js 16 on an Ubuntu VPS: standalone build, PM2, Nginx reverse proxy, free SSL, env vars, zero-downtime redeploys, GitHub Actions and Docker.
To deploy a Next.js app on a VPS, install Node.js, build the app with output: 'standalone', run the generated server.js with PM2 as a non-root user, and put nginx in front as a reverse proxy with a free Let's Encrypt certificate from certbot. The Next.js deployment docs list a Node.js server as an option that supports every feature, including ISR and image optimisation. The step that needs the most memory is next build, so size the server for the build.
As of November 2026, this guide uses Next.js 16.4.6 (the latest stable release, 9 November 2026), Node.js 24 LTS, Ubuntu 24.04, nginx, PM2 7.1 and certbot.
What are the VPS requirements for Next.js?
Next.js 16 needs Node.js 20.9 or newer, according to its installation docs. Ubuntu 24.04's own nodejs package is version 18.19, too old, and Node 20 reached end of life on 30 April 2026, so install a current LTS line as in step 1.
Next.js doesn't publish RAM or CPU requirements, and building differs from running:
- Building is the heavy part.
next buildcompiles, type-checks and prerenders the whole app at once. On a 1 GB server it can stop with "JavaScript heap out of memory", or the kernel kills it. For comparison, Vercel builds free Hobby projects on 2 vCPUs and 8 GB of memory. - Running grows with the app. The memory-usage guide notes that the server preloads each page's JavaScript into memory at start. A database on the same server needs its own share.
- CPU. More vCPUs make builds faster. One Node.js process runs your JavaScript on one core; PM2's cluster mode can run several.
Our rule of thumb: 2 GB of RAM plus swap is the floor for building on the server, and 4 GB or more is comfortable.
Add swap on a small server
Swap is disk used as overflow memory: slow, but it turns a crashed build into a slower one. The swapon manual calls dd the most portable way to create the file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
free -h
How to deploy a Next.js app on an Ubuntu VPS, step by step
These steps assume a fresh Ubuntu 24.04 server already secured with SSH keys, updates and the ufw firewall; see how to set up a VPS. Replace example.com and nextapp with your own names.
1. Install Node.js 24 LTS, nginx and PM2
sudo apt update
sudo apt install -y curl git nginx
curl -fsSL https://deb.nodesource.com/setup_24.x -o nodesource_setup.sh
sudo -E bash nodesource_setup.sh
sudo apt install -y nodejs
node -v
sudo npm install -g pm2
sudo ufw allow 'Nginx Full'
This uses NodeSource's setup script. Node 24, used by the official Next.js Dockerfile, is in maintenance LTS until 30 April 2028. Node 26, the active LTS line since 28 October 2026, is the other choice.
2. Create a deploy user and the app folders
sudo useradd --create-home --shell /bin/bash deploy
sudo mkdir -p /var/www/nextapp/releases /var/www/nextapp/shared
sudo chown -R deploy:deploy /var/www/nextapp
sudo -iu deploy
The app runs as this unprivileged user and lives under /var/www because Ubuntu home directories have been private since 21.04 and nginx must read the static files. Still as deploy, create a key and clone your repository:
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 -C "nextapp-server"
cat ~/.ssh/id_ed25519.pub
git clone git@github.com:your-name/nextapp.git /var/www/nextapp/repo
Add the printed public key under the repository's Settings, Deploy keys first. GitHub deploy keys cover one repository and are read-only by default.
3. Turn on standalone output
In your project, set this in next.config.ts and commit it:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
output: 'standalone',
}
export default nextConfig
According to the output docs, next build then writes a self-contained .next/standalone folder with only the node_modules files the app needs and a minimal server.js that replaces next start. It does not copy public or .next/static; copy them into standalone/public and standalone/.next/static, or pages load without their CSS, JavaScript and images. The deploy script in step 6 does this.
4. Put your environment variables in one place
nano /var/www/nextapp/shared/.env.production
chmod 600 /var/www/nextapp/shared/.env.production
# example contents
DATABASE_URL=postgres://nextapp:password@127.0.0.1:5432/nextapp
NEXT_PUBLIC_SITE_URL=https://example.com
Three rules from the environment variables guide and output docs:
NEXT_PUBLIC_variables are baked in at build time as fixed values in the browser JavaScript, so changing one means rebuilding.- Other variables stay on the server. Code that renders per request reads them at run time; a page prerendered during the build keeps the value it saw then.
- Standalone output copies
.envand.env.productioninto.next/standalone, andserver.jsreads them as defaults;.env.localisn't copied. The docs advise keeping secrets out of files that ship elsewhere; here the build never leaves the server.
5. Tell PM2 how to run the app
Save this as /var/www/nextapp/ecosystem.config.js:
module.exports = {
apps: [
{
name: 'nextapp',
cwd: '/var/www/nextapp/current',
script: 'server.js',
exec_mode: 'fork', // or 'cluster' with instances: 2, see the redeploy section
instances: 1,
kill_timeout: 10000, // ms to finish in-flight requests before a hard kill
env: {
NODE_ENV: 'production',
PORT: 3000,
HOSTNAME: '127.0.0.1', // localhost only; nginx is the public face
},
},
],
}
server.js reads PORT and HOSTNAME; binding to 127.0.0.1 keeps port 3000 closed to the outside. The self-hosting guide says Next.js finishes in-flight requests and pending after() callbacks on SIGINT or SIGTERM and recommends allowing 10 to 30 seconds, hence the longer kill_timeout.
6. Write and run the deploy script
Save this as /var/www/nextapp/deploy.sh. It builds in the repository folder while the live site keeps running, copies the result into a new release folder, then switches over:
#!/usr/bin/env bash
set -euo pipefail
APP=/var/www/nextapp
RELEASE="$APP/releases/$(date +%Y%m%d-%H%M%S)"
cd "$APP/repo"
git pull --ff-only
cp "$APP/shared/.env.production" .env.production
npm ci
npm run build
mkdir -p "$RELEASE"
cp -r .next/standalone/. "$RELEASE/"
cp -r .next/static "$RELEASE/.next/static"
if [ -d public ]; then cp -r public "$RELEASE/public"; fi
ln -sfn "$RELEASE" "$APP/current"
pm2 startOrReload "$APP/ecosystem.config.js"
pm2 save
# keep the five newest releases
ls -1dt "$APP"/releases/* | tail -n +6 | xargs -r rm -rf
chmod +x /var/www/nextapp/deploy.sh
/var/www/nextapp/deploy.sh
curl -I http://127.0.0.1:3000
Because of set -e, a failed build stops the script before the switch and the old release keeps serving.
7. Start the app at boot
Type exit to get back to your admin (sudo) user, then run the startup command in the form the PM2 docs give:
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u deploy --hp /home/deploy
sudo -iu deploy pm2 save
This creates a systemd service that starts PM2 as deploy at boot and restores the saved apps. Watch it with pm2 status, pm2 logs nextapp and pm2 monit. A plain systemd unit running /usr/bin/node server.js in /var/www/nextapp/current also works (our Telegram bot guide shows one), but deploy then needs a sudoers rule to restart it.
How do you set up Nginx, DNS and free SSL for Next.js?
8. Point your domain at the server
Create A records for example.com (@) and www pointing to the server's IPv4 address; see connecting a domain and DNS records explained. Check with nslookup example.com before step 10, because Let's Encrypt must reach the server by name.
9. Configure nginx as a reverse proxy
The self-hosting guide recommends a reverse proxy to handle malformed requests, slow-connection attacks, payload limits and rate limiting. Save this as /etc/nginx/sites-available/nextapp:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
client_max_body_size 10m;
# hashed build files: serve straight from disk, cache for a year
location /_next/static/ {
alias /var/www/nextapp/current/.next/static/;
add_header Cache-Control "public, max-age=31536000, immutable";
access_log off;
}
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 $connection_upgrade;
}
}
sudo ln -s /etc/nginx/sites-available/nextapp /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
- Proxy headers pass on the real domain, protocol and visitor IP. Server Actions compare the browser's Origin with
x-forwarded-hostorhostand reject a mismatch. - Static caching. Files under
/_next/statichave hashed names, and Next.js sends them aspublic, max-age=31536000, immutable. nginx serves them from disk with the same header, keeping that work off Node. - WebSockets. Next.js doesn't need them in production; the
Upgradelines, from the nginx docs, pass yours through. nginx closes a proxied connection that's silent for 60 seconds, so raiseproxy_read_timeoutfor long-lived sockets.proxy_http_version 1.1is required before nginx 1.29.7; Ubuntu 24.04 ships 1.24. - Streaming. For
loading.jsor Suspense streaming, the self-hosting guide says to disable nginx buffering, for example with anX-Accel-Buffering: noheader set innext.config.
10. Get a free SSL certificate with certbot
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/local/bin/certbot
sudo certbot --nginx --redirect -d example.com -d www.example.com
sudo certbot renew --dry-run
These follow certbot's instructions (run sudo apt install snapd first if your image lacks snap). Certbot adds the certificate to your server block, --redirect sends HTTP visitors to HTTPS, and a timer renews certificates automatically (systemctl list-timers shows it). Leave renewal to it: Let's Encrypt is shortening certificate lifetimes from 90 days to 64 on 10 February 2027 and 45 on 16 February 2028. On Debian, sudo apt install certbot python3-certbot-nginx avoids snap.
Do image optimisation and ISR work when you self-host?
Yes. On a single server with a persistent disk, both work without extra set-up.
- Images. The self-hosting guide says
next/imageworks with zero configuration undernext start. Since Next.js 15, Next.js usessharpautomatically withnext startor standalone output, so you don't install it yourself. Build on the same OS and CPU type as the server so npm fetches the matching sharp binary. Optimised images are cached in.next/cache/images. - Image memory. sharp's install notes suggest jemalloc instead of glibc's default allocator (used on Ubuntu) for long-running processes. If memory creeps up, run
sudo apt install libjemalloc2and addLD_PRELOAD: '/usr/lib/x86_64-linux-gnu/libjemalloc.so.2'to the PM2env. - ISR. Cached and revalidated pages share one server cache, kept on each instance's local disk plus a 50 MB in-memory layer. The guide says this works automatically for one
next startinstance with persistent disk. The server writes into.next, so the release folder must belong to the app's user, as here. - Several instances. With PM2 cluster mode or more servers,
revalidateTag()on one instance only clears that instance's cache by default; the guide covers sharing it through a custom cache handler such as Redis.
How do you redeploy a Next.js app with zero downtime?
Don't run npm run build inside the live folder: the build rewrites .next under the running server and the site breaks until the restart. The script above builds elsewhere and switches a symlink only after a successful build.
That leaves the restart. The PM2 FAQ says restart causes a short downtime while reload is zero-downtime for cluster-mode apps, stopping old workers only once new ones accept connections. In fork mode, PM2 turns a reload into a restart, so expect a short gap. To close it, set exec_mode: 'cluster' and instances: 2 (mind the multi-instance caveat above) and run pm2 delete nextapp once, since a reload keeps the old mode.
Setting a deploymentId, for example NEXT_DEPLOYMENT_ID=$(git rev-parse --short HEAD) at build time, makes a browser tab still on the old build do a full page load instead of a client-side navigation that may fail. To roll back, point the symlink at the previous release and reload:
ln -sfn /var/www/nextapp/releases/20261120-183000 /var/www/nextapp/current
pm2 reload nextapp
How to deploy Next.js from GitHub Actions over SSH
On your computer, create a separate key with ssh-keygen -t ed25519 -f gh-deploy -N "". Add the public half to /home/deploy/.ssh/authorized_keys with a forced command, so it can run the deploy script and nothing else (see restrict in the sshd manual):
restrict,command="/var/www/nextapp/deploy.sh" ssh-ed25519 AAAA...rest-of-key... github-actions
In the repository's Actions secrets, store the private key as DEPLOY_SSH_KEY, the server address as DEPLOY_HOST, and the output of ssh-keyscan -t ed25519 your.server.ip, after checking its fingerprint, as DEPLOY_KNOWN_HOSTS. Then add .github/workflows/deploy.yml:
name: Deploy
on:
push:
branches: [main]
concurrency: production
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Run the deploy script on the VPS
env:
SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
HOST: ${{ secrets.DEPLOY_HOST }}
run: |
mkdir -p ~/.ssh
printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key deploy@"$HOST"
Secrets go in through env, as GitHub's docs show, and concurrency stops deploys overlapping. This builds on the VPS. On a small server, build in the workflow instead (ubuntu-latest matches a Linux x64 server for sharp) and copy the release over with rsync, using a key without the forced command.
Can you self-host Next.js with Docker instead?
Yes, with full feature support. The official with-docker example is a multi-stage Dockerfile that builds standalone output on node:24.13.0-slim, copies public and .next/static for you, and runs as the unprivileged node user. Copy its Dockerfile and .dockerignore into your project, install Docker Engine, then:
docker build -t nextapp .
docker run -d --name nextapp --restart unless-stopped \
-p 127.0.0.1:3000:3000 --env-file /var/www/nextapp/shared/.env.production nextapp
- Bind to 127.0.0.1. Docker's docs say published ports are open to the outside world by default and that Docker and ufw are incompatible.
NEXT_PUBLIC_values must exist at build time. The example's.dockerignoreexcludes.envbut not.env.production, which ends up inside the image, so keep only public values there or pass them as build arguments (ARGplusENVin the builder stage). Give secrets at run time with--env-file.- nginx: keep the server block but drop the
/_next/static/location, since those files are inside the container.
For a dashboard that deploys on git push and handles SSL and logs, see Coolify vs Dokploy.
How to fix common Next.js VPS errors
502 Bad Gateway
nginx couldn't reach the app. Check pm2 status and pm2 logs nextapp, then curl -I http://127.0.0.1:3000. "Connection refused" in /var/log/nginx/error.log means nothing listens on that address and port. Use 127.0.0.1 in proxy_pass, not localhost, which can resolve to IPv6 ::1 while the app listens on IPv4 only.
Port 3000 already in use
The error reads EADDRINUSE: address already in use. Find the culprit with sudo ss -ltnp | grep :3000: usually a forgotten npm start in another SSH session or a second app on the same port. Stop it, or give each app its own PORT.
Out of memory during next build
Look for "JavaScript heap out of memory" or a bare "Killed" (sudo journalctl -k | grep -i oom confirms). Add swap, or raise Node's heap limit as Vercel's guide suggests, for example NODE_OPTIONS=--max-old-space-size=2048 npm run build, keeping it below RAM plus swap. The lasting fix is building in GitHub Actions or on a bigger server.
413 Request Entity Too Large
nginx rejects request bodies over client_max_body_size, which defaults to 1 MB. Raise it (10 MB above) and reload nginx. Server Actions have their own 1 MB default, set with experimental.serverActions.bodySizeLimit.
When is Vercel simpler than a VPS?
Vercel maintains Next.js, and its platform gives you a preview URL for every pull request, a global CDN, automatic scaling and no server to patch. The Hobby plan is free, but Vercel's terms limit Hobby to "personal or non-commercial use", and Pro costs US$20 a month per developer seat, billed in dollars, plus usage beyond the included credit. A VPS suits a commercial app that wants a fixed monthly bill, a database or background jobs on the same machine, data in India or rupee billing. Our Vercel alternatives for India guide compares costs, and Node.js hosting in India covers Express, NestJS and other Node apps.
Running Next.js on a HostEthical Cloud VPS
Our Cloud VPS plans are unmanaged KVM servers with full root access, a dedicated IPv4 address and Ubuntu 24.04 among the OS choices, ready about 5 to 15 minutes after payment. VPS Starter's 4 vCPU and 8 GB of RAM is plenty to build and run most single Next.js apps with a database alongside, usually without swap. Go bigger for several apps, a large monorepo or a heavy database.
| Plan | vCPU | RAM | Storage | Paid monthly | Paid up front, per month | At renewal |
|---|---|---|---|---|---|---|
| VPS Starter | 4 cores | 8 GB | 100 GB SSD | ₹860 | ₹774.17 (yearly) | Same price |
| VPS Pro | 6 cores | 12 GB | 200 GB SSD | ₹1,170 | ₹1,053.33 (yearly) | Same price |
| VPS Max | 8 cores | 24 GB | 300 GB SSD | ₹2,190 | ₹1,971.67 (yearly) | Same price |
Choose Mumbai if most visitors are in India: the server is closer to them and your data stays in the country, for ₹380 a month more. Germany has no location fee and suits a European or worldwide audience; see our Mumbai VPS guide. You can register your domain with us, keep it on our nameservers and add step 8's A records in our DNS editor. Plans start at ₹860 a month, or about ₹774.17 a month when billed yearly, paid in rupees by UPI, same price at renewal. You manage the OS and app, we manage hardware and network (managed vs unmanaged VPS).
Frequently asked questions
What Node.js version does Next.js need on a VPS?
Next.js 16, the current major version (16.4.6 is the latest stable release as of November 2026), needs Node.js 20.9 or newer. Node 20 reached end of life on 30 April 2026, so install a current LTS line such as Node 24 or Node 26 from NodeSource. Ubuntu 24.04's own nodejs package is version 18.19, which is too old.
How much RAM do I need to host a Next.js app on a VPS?
Next.js publishes no official figure, and the build needs far more memory than the running site. A 1 GB server can run out of memory during next build, so add swap, build in GitHub Actions, or choose a larger server. As a rule of thumb, 2 GB plus swap is the floor for building on the server and 4 GB or more is comfortable, especially with a database on the same machine.
Do I need output: 'standalone' to self-host Next.js?
No. next start supports every feature on a VPS. Standalone output is optional but produces a smaller, self-contained folder with a minimal server.js and only the dependencies the app needs. If you use it, copy the public folder and .next/static into the standalone folder yourself, because next build does not copy them.
Can I use PM2 instead of systemd for Next.js?
Yes. PM2 restarts the app if it crashes, and pm2 startup plus pm2 save bring it back after a reboot through a systemd service it creates. PM2 cluster mode also allows zero-downtime reloads with pm2 reload. A plain systemd unit works just as well if you only need one process and can accept a brief gap on each restart.
Why does my Next.js site show 502 Bad Gateway behind Nginx?
Nginx cannot reach the Next.js server, usually because the app crashed, is not running, or listens on a different port or address. Check pm2 status and pm2 logs, test with curl -I http://127.0.0.1:3000, and read /var/log/nginx/error.log. Use 127.0.0.1 rather than localhost in proxy_pass so Nginx does not try IPv6 while the app listens on IPv4.