Vercel is the easiest place to run Next.js, but not always the right one. Maybe you already pay for a server, need to sit next to a database on a private network, or want a fixed monthly bill. This site, the one you're reading, runs on a single EC2 instance, and every push to main deploys it in about two minutes.
This guide walks through that setup end to end: preparing the server, a GitHub Actions workflow that builds and ships the app, PM2 to keep it running, Nginx in front, HTTPS, and rollbacks. It works the same on any VPS: EC2, DigitalOcean, Hetzner, Lightsail.
The shape of the pipeline
- You push to
main. - GitHub Actions installs dependencies and runs
next buildon GitHub's machine, not your server. - It packs the build into a tarball and copies it to the server over SSH.
- The server unpacks it into a new release folder and switches a
currentlink to it. - PM2 reloads the app. Nginx keeps serving traffic on ports 80 and 443 the whole time.
Building in CI matters: next build is memory-hungry, and running it on a small server can stall or crash the site it's serving.
Prepare the server
Start from a hardened server: SSH keys only, a firewall with 22, 80 and 443 open, and a non-root user. Then install Node.js for that user with nvm, plus PM2 and Nginx:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
source ~/.bashrc
nvm install 22
npm install -g pm2
sudo apt install -y nginx
mkdir -p ~/apps/site/releases ~/apps/site/sharedUse the same major Node.js version here as in your workflow, so native modules built in CI run on the server.
Create a key pair just for deployments, and give GitHub the private half:
ssh-keygen -t ed25519 -f deploy_key -C "github-actions-deploy" -N ""
ssh-copy-id -i deploy_key.pub deploy@your-serverIn the repository, open Settings › Secrets and variables › Actions and add SSH_HOST, SSH_USER and SSH_KEY (the contents of deploy_key). Then delete the local copy of the private key.
The release layout
Instead of overwriting the app in place, each deploy gets its own folder, and a symlink points at the live one:
releases/
20261120093012/
20261124151530/
20261125101544/ ← newest
current -> releases/20261125101544
shared/
.env.production
data/ ← anything that must survive deploysThis gives you two things for free. Switching versions is a single, atomic symlink change, so there's never a half-copied app. And rolling back is pointing the link at the previous folder.
Anything the app writes at run time, such as uploads, a SQLite database or a cache, belongs in shared/, outside the release folders. Otherwise the next deploy leaves it behind in an old release.
Keep the app running with PM2
PM2 restarts the app if it crashes, starts it at boot, and can reload it without dropping requests. Describe the app once in an ecosystem file and commit it:
module.exports = {
apps: [
{
name: "site",
cwd: "/home/deploy/apps/site/current",
script: "node_modules/next/dist/bin/next",
args: "start -p 3000",
exec_mode: "cluster",
instances: 2,
env: { NODE_ENV: "production" },
},
],
};Cluster mode with two instances is what makes pm2 reload zero-downtime: PM2 restarts the instances one at a time, so one is always answering. On a one-CPU server, two instances is still fine; they mostly wait on I/O.
Start it once by hand, then make PM2 survive reboots:
pm2 start ~/apps/site/current/ecosystem.config.cjs
pm2 startup # prints a sudo command; run it once
pm2 saveThe GitHub Actions workflow
name: Deploy
on:
push:
branches: [main]
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run build
- name: Package the release
run: tar -czf release.tar.gz .next public package.json package-lock.json next.config.ts ecosystem.config.cjs
- name: Upload
uses: appleboy/[email protected]
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
source: release.tar.gz
target: /home/deploy/apps/site
- name: Activate
uses: appleboy/[email protected]
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
set -e
export NVM_DIR="$HOME/.nvm"; . "$NVM_DIR/nvm.sh"
cd ~/apps/site
RELEASE=releases/$(date +%Y%m%d%H%M%S)
mkdir -p "$RELEASE"
tar -xzf release.tar.gz -C "$RELEASE" && rm release.tar.gz
ln -s ~/apps/site/shared/.env.production "$RELEASE/.env.production"
cd "$RELEASE" && npm ci --omit=dev && cd ~/apps/site
ln -sfn "$RELEASE" current
pm2 reload site --update-env
ls -1dt releases/* | tail -n +4 | xargs -r rm -rfWhat each piece is for:
concurrencystops two quick pushes from deploying on top of each other.npm ciinstalls exactly what's in the lockfile, so CI and production get the same versions.set -eaborts the script at the first failure, beforecurrentis switched. A broken release never goes live.npm ci --omit=devon the server installs runtime dependencies only. It also builds native modules (such asbetter-sqlite3orsharp) for the server's own system.- The last line keeps the three newest releases and deletes the rest.
Pin actions to a major version (or, stricter, to a commit SHA) and update them when GitHub announces runner changes. Old action versions eventually stop running when their Node.js runtime is retired.
Nginx in front
Next.js can serve traffic directly, but Nginx in front handles TLS, compression, connection limits and slow clients far more efficiently, and lets you host several apps on one server.
server {
listen 80;
server_name example.com www.example.com;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
# Hashed build assets never change: cache them for a year
location /_next/static/ {
proxy_pass http://127.0.0.1:3000;
add_header Cache-Control "public, max-age=31536000, immutable";
}
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 ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxAlways run nginx -t before reloading. It catches typos before they take the site down. The Upgrade and Connection headers let WebSockets through, in case the app ever needs them.
Keep the app itself listening on 127.0.0.1:3000 only, behind the firewall, so the only public way in is through Nginx.
HTTPS
With DNS pointing at the server, Certbot gets a free Let's Encrypt certificate and edits the Nginx config for you:
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-runCertbot installs a timer that renews certificates automatically; the dry run confirms renewal will work.
If you put Cloudflare in front instead, set its SSL mode to Full (strict) and install a Cloudflare origin certificate on Nginx. "Flexible" mode leaves the hop between Cloudflare and your server unencrypted.
Environment variables
Next.js reads .env.production at build time and at run time, with an important split:
- Variables starting with
NEXT_PUBLIC_are baked into the JavaScript at build time. They must exist in CI, as repository secrets or variables, and changing them needs a rebuild. - All other variables are read by the server at run time. Keep them in
shared/.env.productionon the server, which the workflow links into each release.
Never commit real secrets to the repository, and remember that anything NEXT_PUBLIC_ is visible to every visitor.
Rolling back
Because the old releases are still on disk, a rollback takes seconds:
cd ~/apps/site
ls -1dt releases/* # newest first
ln -sfn releases/20261124151530 current
pm2 reload site --update-envThen fix forward with a normal commit; the next deploy replaces the rolled-back release as usual.
Common problems
- 502 Bad Gateway: Nginx can't reach the app. Check
pm2 statusandpm2 logs site, and that the port in Nginx matches the one the app listens on. - The server runs out of memory during deploys: don't build on the server. If even
npm ciis too heavy, switch to standalone output. - Old pages after a deploy: a CDN or browser cached HTML. Static assets are hashed and safe to cache forever; HTML shouldn't be cached for long.
- Native module errors (
was compiled against a different Node.js version): the server's Node.js major version differs from CI's, ornode_moduleswas copied from CI instead of installed on the server. - Data disappeared after deploying: it was written inside a release folder. Move it to
shared/.
FAQ
Can I host Next.js without Vercel?
Yes. next build and next start run on any server with Node.js. Features like server rendering, API routes, image optimization and incremental static regeneration all work on a self-hosted Node.js server.
Do I need Nginx in front of Next.js?
It's not required, but it's strongly recommended: it handles HTTPS, compression and slow clients efficiently, lets you run several apps on one server, and keeps the Node.js port off the internet.
How do I deploy Next.js with zero downtime?
Run it under PM2 in cluster mode with at least two instances and use pm2 reload, which restarts instances one at a time. Combine that with release folders and a current symlink so the switch is atomic.
Should I build Next.js on the server or in CI?
In CI. Building needs a lot of memory and CPU, and on a small server it can slow down or crash the live site. Ship the finished build instead.
Where should a self-hosted Next.js app store files and databases?
Outside the release folders, in a shared directory that every release links to. Otherwise each deploy starts with an empty copy and the old data stays behind in a previous release.