How to Deploy Next.js on Ubuntu 24.04 with PM2 and Nginx

Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer
IntermediateUpdated Nov 17, 202618 min read~45 minutes total
Next.jsDeploymentNode.jsPM2NginxUbuntu 24.04Self-Hosting
Last reviewed:
Tutorial
How to Deploy Next.js on Ubuntu 24.04 with PM2 and Nginx
rafftechnologies.com/learn
On this page

Prerequisites

  • Ubuntu 24.04 Linux VM, SSH sudo access, a Next.js repository with a lockfile, a domain pointed to the VM, and a recovery path before firewall changes.

Serve your Next.js app from your own Ubuntu 24.04 server.

Tested on 1 vCPU and 2 GB RAM: $8.99 a month

  1. 1Pick a Linux imageUbuntu, Debian and more, with your SSH key added.
  2. 2Choose a sizeFrom $4.99 a month. Resize when your app grows.
  3. 3Connect over SSHYour server is up in about 55 seconds.

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

To deploy a Next.js app on Ubuntu 24.04, build the application with a supported Node.js LTS release, run the production server as a supervised process, bind it to localhost, and place Nginx in front for public HTTP/HTTPS traffic. This tutorial uses Node.js 24 LTS, PM2, Nginx, and Certbot to build that single-server production baseline.

Raff Technologies is used as the Ubuntu VM platform in the saved test workflow. The Next.js application itself listens only on 127.0.0.1:3000; Nginx is the public edge. This matches current Next.js self-hosting guidance, which recommends a reverse proxy rather than exposing the Next.js server directly to the internet.

As of October 27, 2026, the patched Node.js 24 LTS release is 24.22.1 and the current stable Next.js documentation version is 16.3.4. Next.js 16.x is Active LTS, while 15.x is Maintenance LTS. Your production deployment should still use the Next.js version pinned by the application's lockfile rather than turning a server migration into an unplanned framework upgrade.

The original workflow was tested on a Raff Ubuntu 24.04 VM with 1 vCPU and 2 GB RAM. Node.js 24.22.1 LTS, Next.js 16.3.4 self-hosting behavior, and PM2 startup guidance were documentation-reviewed for this refresh; no new full machine retest is claimed.

Prerequisites:

  • A Raff Linux VM running Ubuntu 24.04
  • SSH access with a non-root sudo user
  • A Next.js application in a Git repository
  • A lockfile such as package-lock.json if you plan to use npm ci
  • A domain pointed to the VM for production HTTPS
  • Ports 80/tcp and 443/tcp available for Nginx
  • A recovery path before enabling or changing firewall rules

Step 1 — Prepare Ubuntu, DNS, and UFW safely

Update Ubuntu and install the base packages:

Bash
sudo apt update sudo apt upgrade -y sudo apt install -y git curl ca-certificates nginx ufw dnsutils

Check whether the upgrade requires a reboot:

Bash
test -f /var/run/reboot-required && cat /var/run/reboot-required

If a reboot is required, perform it during a safe maintenance window before continuing.

Point your domain's A record to the VM's public IPv4 address. Add an AAAA record only when IPv6 is configured and reachable on this VM.

Verify DNS:

Bash
dig +short A your-domain.com

Inspect UFW before changing it:

Bash
sudo ufw status verbose

Confirm the actual SSH port:

Bash
sudo sshd -T | awk '/^port / {print $2}'

If UFW is already active, keep the existing SSH rule and allow Nginx:

Bash
sudo ufw allow 'Nginx Full' sudo ufw status numbered

If UFW is inactive, allow the actual SSH path first. For standard SSH with the OpenSSH profile:

Bash
sudo ufw allow OpenSSH

For a custom SSH port, allow that port instead, for example:

Bash
sudo ufw allow 2222/tcp

Then allow Nginx:

Bash
sudo ufw allow 'Nginx Full'

Keep the current SSH session open and successfully open a second SSH session before enabling an inactive firewall:

Bash
sudo ufw enable sudo ufw status numbered

Do not use ufw --force enable as a shortcut around SSH-path verification.

Verify: DNS should resolve to the intended VM, Nginx should be active, the actual SSH path should remain reachable, and UFW should allow only the public services you intend to expose.

Step 2 — Install Node.js 24 LTS with NVM

As of October 27, 2026, Node.js provides 24.22.1 on the patched v24 LTS line. Install NVM with the current installer shown by Node.js:

Bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.7/install.sh | bash

Load NVM into the current shell:

Bash
export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

Install Node.js 24 and make it the default for this user:

Bash
nvm install 24 nvm alias default 24 nvm use 24

Check the installed versions:

Bash
node --version npm --version nvm current

The exact patch can increase later. As of October 27, 2026, use v24.22.1 or a later patched v24 LTS release.

Verify: node --version and nvm current should report the same Node.js 24 branch.

Step 3 — Clone the Next.js application and install locked dependencies

Create the application directory:

Bash
sudo mkdir -p /var/www/nextjs sudo chown "$USER":"$USER" /var/www/nextjs cd /var/www/nextjs

Clone your repository:

Bash
git clone https://github.com/your-username/your-nextjs-repo.git .

If the repository uses npm and contains package-lock.json, install the locked dependency graph:

Bash
npm ci

Inspect the installed Next.js version:

Bash
npm ls next

Next.js 16.x is the current Active LTS major. The official documentation is on 16.3.4 as of this refresh, but do not replace the application's tested lockfile version merely because a newer release exists.

Verify: package.json and the expected lockfile should exist, npm ci should complete successfully, and npm ls next should resolve the project's installed Next.js version.

Step 4 — Configure production environment variables

Next.js supports both build-time and runtime environment variables. Variables prefixed with NEXT_PUBLIC_ are exposed to the browser and are inlined into client JavaScript during next build, so never store secrets in a public variable.

Create a production-local environment file if your application requires one:

Bash
cd /var/www/nextjs nano .env.production.local

Example:

Dotenv
DATABASE_URL=your_server_side_database_url APP_SECRET=your_server_side_secret NEXT_PUBLIC_APP_URL=https://your-domain.com

Protect it:

Bash
chmod 600 .env.production.local

Check that local environment files are ignored by Git:

Bash
grep -E '^\.env|\.env\*' .gitignore || true git status --short

Add an appropriate ignore rule if your repository does not already exclude the file.

Verify: if .env.production.local exists, it should have mode 600, secrets should not use the NEXT_PUBLIC_ prefix, and the file should not be staged for commit.

Step 5 — Build the Next.js production application

Build the application with its required environment already in place:

Bash
cd /var/www/nextjs npm run build

A successful build creates the .next directory.

When troubleshooting, inspect the framework and environment instead of assuming every failed build is a VM-size problem:

Bash
npx next info

Check the build output without running the build a second time:

Bash
test -d .next && echo ".next build directory exists" test -f package.json && echo "package.json found"

Verify: npm run build should finish without a fatal error and .next should exist afterward.

Step 6 — Test the Next.js production server on localhost only

For this architecture, the application server should not be the public endpoint. Start it on loopback:

Bash
cd /var/www/nextjs npm run start -- --hostname 127.0.0.1 --port 3000

In a second SSH session, inspect the listener:

Bash
sudo ss -lntp | grep ':3000'

The expected bind is:

Text
127.0.0.1:3000

Test the local application:

Bash
curl -I http://127.0.0.1:3000

Stop the manual process with Ctrl+C after the test.

Verify: the local HTTP request should succeed and port 3000 should not listen on 0.0.0.0.

Step 7 — Run Next.js with PM2

Install PM2 under the same Node.js/NVM user that owns the application process:

Bash
npm install -g pm2

Create /var/www/nextjs/ecosystem.config.cjs:

Bash
nano /var/www/nextjs/ecosystem.config.cjs

Use one process as the baseline:

Javascript
module.exports = { apps: [ { name: 'nextjs-app', cwd: '/var/www/nextjs', script: 'npm', args: [ 'start', '--', '--hostname', '127.0.0.1', '--port', '3000' ], instances: 1, exec_mode: 'fork', watch: false, env: { NODE_ENV: 'production' } } ] }

Start the process:

Bash
cd /var/www/nextjs pm2 start ecosystem.config.cjs

Inspect status and recent logs:

Bash
pm2 status pm2 logs nextjs-app --lines 50 --nostream

A single instance is intentional. Current Next.js self-hosting guidance says caches are local to each instance by default, and multi-instance App Router deployments require additional coordination for cache tags, shared cache state, deployment versions, and related behavior.

For PM2-specific operations, see How to Install PM2 and Deploy Node.js on Ubuntu 24.04.

Verify: nextjs-app should be online, curl -I http://127.0.0.1:3000 should succeed, and port 3000 should remain loopback-only.

Step 8 — Configure PM2 reboot persistence

Generate PM2's startup integration as the application user:

Bash
pm2 startup

PM2 prints a customized sudo env PATH=... pm2 startup systemd ... command. Run the exact command it prints rather than copying a hard-coded path from another server.

Save the process list:

Bash
pm2 save

Find the generated systemd service:

Bash
systemctl list-unit-files | grep '^pm2-'

PM2 documents that after changing the Node.js version, you should regenerate the startup integration so its PATH points to the current Node.js binary.

Verify: the PM2 systemd service for your user should be enabled and pm2 save should complete successfully.

Step 9 — Configure Nginx as the public reverse proxy

Create the site configuration:

Bash
sudo nano /etc/nginx/sites-available/nextjs

Add:

Nginx
server { listen 80; listen [::]:80; server_name your-domain.com www.your-domain.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_buffering off; proxy_read_timeout 60s; proxy_connect_timeout 10s; } }

Next.js recommends a reverse proxy for self-hosting. App Router streaming also requires the proxy path not to buffer the response. proxy_buffering off provides that behavior at this Nginx layer.

Do not invent a separate one-year cache rule for /_next/static/. Next.js already sets immutable caching headers for truly immutable hashed assets.

Enable the site:

Bash
sudo ln -sf /etc/nginx/sites-available/nextjs \ /etc/nginx/sites-enabled/nextjs sudo rm -f /etc/nginx/sites-enabled/default

Validate before reloading:

Bash
sudo nginx -t sudo systemctl reload nginx

Test the proxy locally with the production Host header:

Bash
curl -I http://127.0.0.1 -H 'Host: your-domain.com'

Verify: nginx -t should succeed and the Host-header request should return the Next.js application through Nginx.

Step 10 — Enable HTTPS with Certbot

Install Certbot and its Nginx plugin:

Bash
sudo apt install -y certbot python3-certbot-nginx

Request a certificate after public DNS points to the VM and port 80 is reachable:

Bash
sudo certbot --nginx --redirect \ -d your-domain.com \ -d www.your-domain.com

If you do not use www, omit it from DNS, Nginx, and Certbot.

Inspect the certificate and test renewal:

Bash
sudo certbot certificates sudo certbot renew --dry-run

For certificate troubleshooting, continue with Secure Nginx with Let's Encrypt on Ubuntu 24.04.

Verify: HTTP should redirect to HTTPS, the HTTPS request should succeed, and the renewal dry run should pass.

Step 11 — Verify reboot persistence

Save the final PM2 process list:

Bash
pm2 save

Reboot during a maintenance window:

Bash
sudo reboot

After reconnecting, verify PM2, the local app, and the public endpoint:

Bash
pm2 status curl -I http://127.0.0.1:3000 curl -I https://your-domain.com

If the process did not return, inspect the PM2 service:

Bash
systemctl list-units --type=service | grep pm2 systemctl --failed

Verify: nextjs-app should return as online after reboot, port 3000 should respond locally, and the public HTTPS endpoint should work without a manual pm2 start.

Step 12 — Verify the Next.js deployment end to end

Run the final checks:

Bash
printf 'Node.js:\n' node --version printf '\nNext.js:\n' cd /var/www/nextjs npm ls next printf '\nPM2:\n' pm2 status printf '\nLocal Next.js:\n' curl -I http://127.0.0.1:3000 printf '\nListening socket:\n' sudo ss -lntp | grep ':3000' printf '\nNginx config:\n' sudo nginx -t printf '\nHTTP redirect:\n' curl -I http://your-domain.com printf '\nHTTPS response:\n' curl -I https://your-domain.com printf '\nFirewall:\n' sudo ufw status numbered

In the application and browser, confirm that:

  • the intended production build is being served;
  • PM2 reports nextjs-app as online;
  • Next.js listens only on 127.0.0.1:3000;
  • Nginx passes its configuration test;
  • HTTP redirects to HTTPS;
  • HTTPS serves the application successfully;
  • port 3000 has no public UFW allow rule;
  • the application returns after reboot; and
  • streaming routes, if your app uses them, are not unintentionally buffered by Nginx.

End-to-end verification is complete when the complete request path — browser → HTTPS/Nginx → loopback Next.js → PM2-managed process — works after a reboot without exposing the application port publicly.

Update the Next.js application safely

For the single-process baseline in this tutorial:

Bash
cd /var/www/nextjs git pull --ff-only npm ci npm run build pm2 restart nextjs-app pm2 save

This sequence does not claim zero downtime. PM2 cluster reloads and multi-instance Next.js deployments require deliberate cache, version-skew, revalidation, and graceful-shutdown design.

Before changing the Next.js major or minor version, inspect what the application actually uses:

Bash
npm ls next npm outdated next || true

Test framework upgrades in staging before production.

Roll back or remove the deployment

For an application rollback, prefer a known-good Git revision and rebuild it using your normal release process:

Bash
cd /var/www/nextjs git log --oneline -n 10 npm ci npm run build pm2 restart nextjs-app

To remove only this PM2 application:

Bash
pm2 delete nextjs-app pm2 save

Remove the Nginx site:

Bash
sudo rm -f /etc/nginx/sites-enabled/nextjs sudo rm -f /etc/nginx/sites-available/nextjs sudo nginx -t sudo systemctl reload nginx

Review certificates before deleting TLS material:

Bash
sudo certbot certificates

Delete /var/www/nextjs only when source files, generated files, uploads, and environment configuration are no longer required.

Troubleshooting

npm run build fails

Inspect the actual runtime and framework first:

Bash
node --version npm --version npm ls next npx next info

Use the application's reported compiler, dependency, TypeScript, environment, or memory error rather than assuming every failure is caused by VM size.

PM2 starts but Next.js immediately exits

Inspect the logs:

Bash
pm2 logs nextjs-app --lines 100 --nostream

Check that a production build exists and port 3000 is free:

Bash
test -d /var/www/nextjs/.next && echo build-present sudo ss -lntp | grep ':3000' || true

Port 3000 listens on 0.0.0.0

Inspect the PM2 process:

Bash
pm2 describe nextjs-app

Restart from the ecosystem file:

Bash
cd /var/www/nextjs pm2 delete nextjs-app pm2 start ecosystem.config.cjs pm2 save

Verify 127.0.0.1:3000 is the intended listener.

Nginx returns 502 Bad Gateway

Verify the application first:

Bash
pm2 status curl -I http://127.0.0.1:3000 pm2 logs nextjs-app --lines 50 --nostream

Then inspect Nginx:

Bash
sudo nginx -t sudo tail -n 50 /var/log/nginx/error.log

A 502 usually means Nginx cannot reach the application or the upstream process is failing.

Streaming responses are delayed

Confirm Nginx buffering is disabled for the application location:

Bash
sudo nginx -T 2>/dev/null | grep -n 'proxy_buffering'

The current Next.js self-hosting guidance requires buffering to be disabled somewhere in the proxy path for streaming responses to work as intended.

The application does not return after reboot

Inspect the generated PM2 integration:

Bash
systemctl list-unit-files | grep '^pm2-' systemctl --failed

If Node.js was upgraded through NVM after PM2 startup integration was generated, recreate it:

Bash
pm2 unstartup pm2 startup pm2 save

Run the exact sudo commands printed by PM2 when prompted.

Multiple PM2 instances serve inconsistent cached data

Return to one process while designing a shared cache and tag-invalidation strategy. Current Next.js self-hosting guidance notes that cache state is local per instance by default and revalidateTag() on one instance does not automatically invalidate every other instance.

Set the ecosystem file back to:

Javascript
instances: 1, exec_mode: 'fork'

Then restart the process.

Conclusion

You deployed a Next.js application on Ubuntu 24.04 using Node.js 24 LTS, PM2, Nginx, HTTPS, and a loopback-only application port. The deployment also verifies reboot recovery and keeps firewall activation separate from unsafe copy-paste shortcuts.

The main production boundary is simple: Nginx owns the public edge, while next start stays private. When the architecture grows beyond one Next.js process, treat shared caching, cache-tag invalidation, deployment versioning, streaming, and graceful shutdown as explicit design requirements rather than assuming PM2 cluster mode solves them automatically.

For a standalone Nginx installation, see Install Nginx on Ubuntu 24.04. The PM2 and HTTPS instructions are linked alongside the corresponding steps above.

Deploy a Raff Ubuntu VM for a self-managed Next.js app with PM2, Nginx, and HTTPS. Choose server resources for your build process and production traffic.

Tested on 1 vCPU and 2 GB RAM: $8.99 a month · 14-day money-back guarantee

Deploy Your Server

Sources

  • Next.js Docs — Self-Hosting, support policy, and current 16.3.4 documentation
  • Node.js — v24.22.1 LTS download and release schedule
  • PM2 — startup scripts and saved process restoration
  • Guidance re-verified: 2026-09-07
Was this article helpful?
Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer

Aybars is a Platform Engineer & Technical Writer at Raff Technologies. He works on Linux VM templates, self-hosted application workflows, and security-focused deployment validation, turning tested infrastructure procedures into clear, practical tutorials for developers and teams.

Serve your Next.js app from your own Ubuntu 24.04 server.

Tested on 1 vCPU and 2 GB RAM: $8.99 a month

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

14-day money-back guarantee

Frequently asked questions

How do I deploy a Next.js app on Ubuntu 24.04?
Build the application with a supported Node.js LTS release, run `next start` behind PM2 on localhost, place Nginx in front as the public reverse proxy, enable HTTPS, and verify reboot recovery and the complete request path.
Which Next.js version is current in this tutorial?
Next.js 16.3.4 is the current stable documentation version verified on September 7, 2026. Next.js 16.x is Active LTS. Keep the version pinned by your application lockfile and apply framework upgrades separately from server deployment.
Which Node.js version should I use for Next.js in 2026?
This guide uses Node.js 24 LTS. As of October 27, 2026, use 24.22.1 or a newer patched version from the supported Node 24 line, and confirm compatibility with the Next.js version in your application lockfile.
Should Next.js port 3000 be public?
No for this deployment pattern. Bind `next start` to `127.0.0.1:3000` and expose Nginx on ports 80 and 443. Next.js recommends using a reverse proxy in front of self-hosted applications.
Can I run Next.js with PM2?
Yes. PM2 can supervise the Next.js production process and restore a saved process list after reboot. Start with one instance unless your Next.js cache and revalidation architecture is designed for multiple instances.
Should I use PM2 cluster mode with Next.js?
Not by default. Multiple Next.js instances require coordination for cache state, cache-tag invalidation, deployment versions, and related self-hosting concerns. A single PM2 process is the safer baseline.
Why use Nginx in front of Next.js?
Next.js recommends a reverse proxy such as Nginx to handle edge concerns including malformed requests, slow connections, payload limits, TLS, and rate limiting before traffic reaches the application server.
Do I need custom Nginx caching rules for Next.js static assets?
Usually not. Next.js already sets immutable caching headers for truly immutable hashed assets. Avoid overriding framework caching unless you have a deliberate CDN or reverse-proxy cache design.