Skip to main content
Support Hours: 24/7 (technical team 11 AM to 8 PM PKT)WhatsApp: +92 313 2946143
Hosting Infrastructure
14 min read
Updated Oct 7, 2026 • Published Sep 15, 2026

How to Host Next.js on a VPS with PM2 and Nginx Reverse Proxy

Step-by-step production deployment guide for Next.js on a Linux VPS. Learn how to configure Node.js, PM2 process management, Nginx reverse proxy, and free SSL certificates.

Muhammad Anees Ur Rehman
Founder & Infrastructure Architect
Share Guide:
How to Host Next.js on a VPS with PM2 and Nginx Reverse Proxy

Why Deploy Next.js on a Self-Managed KVM VPS Instead of Serverless?

In short: To host Next.js on a VPS, install Node.js, build the app with npm run build, keep it running with PM2, put Nginx in front as a reverse proxy and add a free SSL certificate. The full commands are below.

While serverless platforms like Vercel offer automated Git deployments, enterprise development teams frequently face significant drawbacks: exorbitant bandwidth egress costs, strict serverless function execution timeouts (10 to 60 seconds), cold-start latency spikes, and vendor lock-in. Hosting your Next.js application on an isolated KVM Virtual Private Server (VPS) delivers predictable, flat-rate pricing, persistent server-side memory caching, unmetered network bandwidth, and complete architectural control over background worker daemons, Redis queues, and local databases.

If you need a server for this setup, our VPS hosting in Pakistan plans run on KVM with NVMe storage and PKR billing.

How To Host Nextjs On VPS With Pm2 And Nginx Reverse Proxy architecture and execution workflow diagram.
Figure 1: Architectural workflow and configuration sequence for how to host nextjs on vps with pm2 and nginx reverse proxy.
  • Zero Cold Starts: Next.js runs as a persistent, compiled Node.js HTTP server daemon, answering incoming requests in milliseconds.
  • Predictable Monthly Invoicing: Say goodbye to unpredictable thousand-dollar hyperscaler serverless bandwidth bills.
  • High Concurrency with PM2 Clustering: Automatically fork Node.js worker threads across all available CPU cores to maximize throughput.
  • SSL Offloading & Static Caching: Nginx handles TLS encryption handshakes and serves static media directly from disk cache, freeing Node.js to execute dynamic logic.
Key Takeaway: A self-hosted Next.js production stack utilizing PM2 cluster mode and Nginx reverse proxy provides enterprise-grade throughput, persistent memory execution, and zero cold-start latency. Connect via command line with our how to connect via SSH guide, explore KVM VPS hosting, or review our PM2 process management guide.

Step 1: Initial VPS Provisioning and Node.js Environment Setup

Provision a clean Ubuntu 22.04 LTS or 24.04 LTS KVM VPS instance. Connect via SSH and install the required development runtime packages:

  • Update Package Repositories: sudo apt update && sudo apt upgrade -y
  • Install Essential Build Tools: sudo apt install -y curl git build-essential nginx
  • Install Node.js via NodeSource: Execute curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - followed by sudo apt install -y nodejs
  • Verify Installation: Run node -v and npm -v to confirm active runtime versions.

Step 2: Deploying the Application and Configuring PM2 Process Manager

Clone your Next.js project into /var/www/my-app and install dependencies. To ensure your application automatically restarts after crashes or server reboots, deploy PM2:

How To Host Nextjs On VPS With Pm2 And Nginx Reverse Proxy performance benchmark and optimization matrix.
Figure 2: Performance benchmark comparison demonstrating latency reductions and throughput gains.

Installing and Launching with PM2

Install PM2 globally and build your production bundle:

  • sudo npm install -g pm2
  • cd /var/www/my-app && npm install && npm run build
  • pm2 start npm --name "nextjs-app" -- start -- -p 3000
  • pm2 save && pm2 startup (Generates systemd service hooks to relaunch after reboots)

Enabling PM2 Cluster Mode

For multi-core VPS servers, launch an ecosystem.config.js file with instances: "max" and exec_mode: "cluster" to utilize 100% of your vCPU cores.

Step 3: Configuring Nginx as a High-Performance Reverse Proxy

While Next.js can listen directly on port 3000, exposing Node.js directly to the public internet is insecure and inefficient. Nginx serves as a hardened reverse proxy on ports 80 and 443.

  • Create Server Block: Create /etc/nginx/sites-available/nextjs.conf with proxy_pass http://127.0.0.1:3000;.
  • Configure HTTP/1.1 and WebSockets: Include proxy_http_version 1.1;, proxy_set_header Upgrade $http_upgrade;, and proxy_set_header Connection 'upgrade';.
  • Preserve Real Client IP: Forward headers using proxy_set_header X-Forwarded-For $remote_addr; and proxy_set_header Host $host;.
  • Test and Reload: Execute sudo nginx -t followed by sudo systemctl reload nginx.

Production Architecture Checklist: Next.js on VPS

Review this technical architecture matrix to verify all components of your production deployment.

ComponentTechnologyStandard Production ConfigurationRole
Runtime EnvironmentNode.js 20.x LTSActive LTS runtime with npm/pnpmExecutes compiled JavaScript
Process ManagerPM2 Process DaemonCluster mode with auto-restart on failureDaemon monitoring and zero downtime reload
Reverse ProxyNginx Web ServerGzip compression, HTTP/2, WebSocket forwardingPublic network gateway & TLS termination
SSL EncryptionLet's Encrypt CertbotAutomated renewal with TLS 1.3 enforcementEnd-to-end HTTPS encryption
Firewall SecurityUFW (Uncomplicated Firewall)Allow ports 22, 80, 443; drop port 3000Perimeter port access control

Step 4: Securing Your Domain with Free Let's Encrypt SSL

Secure your Next.js application with an automated Let's Encrypt SSL certificate using Certbot:

  • Install Certbot Nginx Plugin: sudo apt install -y certbot python3-certbot-nginx
  • Request Certificate: sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
  • Automated Renewal Verification: Certbot automatically provisions a systemd timer; test renewal with sudo certbot renew --dry-run.

Automating Deployments with GitHub Actions CI/CD and SSH Webhooks

Manually connecting via SSH to run git pull and npm run build is acceptable for hobby projects, but production applications require automated Continuous Integration and Continuous Deployment (CI/CD):

  • Create a GitHub Action Workflow (.github/workflows/deploy.yml) that triggers automatically whenever commits merge into your main production branch.
  • Execute Automated Testing: Run linting and unit tests inside the GitHub virtual runner before initiating server deployment.
  • Trigger SSH Deployment: Use an SSH action to connect to your KVM VPS, pull the latest commits, install dependencies, compile the production build, and execute pm2 reload nextjs-app with zero downtime.

Optimizing Next.js Image Optimization on Self-Hosted VPS Hardware

By default, Next.js optimizes images using the sharp high-performance Node.js image processing library. On self-hosted KVM servers, ensure you install sharp explicitly (npm install sharp) inside your project directory. This enables blazing-fast WebP/AVIF conversions with native C++ libvips binaries, reducing CPU compilation overhead by over 75%.

Production Maintenance Checklist: Operating Next.js on Linux VPS

Ensure your self-hosted Next.js production stack maintains 99.9% uptime with this operational maintenance protocol:

  • Monitor Process Status Regularly: Run pm2 status and pm2 monit to verify cluster worker memory and CPU health.
  • Automate Log Pruning: Deploy pm2-logrotate to prevent disk storage exhaustion from uncompressed application logs.
  • Keep Node.js LTS Updated: Regularly apply minor security patch releases within the active Node.js LTS release cycle.
  • Maintain Nginx Configuration Backups: Keep version-controlled backups of your Nginx server block configuration files in Git.
Frequently Asked Questions

Common Questions Answered

How do I deploy code updates with zero downtime?

Pull your latest Git commits, run npm install && npm run build, and then execute pm2 reload nextjs-app. PM2 will sequentially reload cluster worker threads, ensuring visitors experience zero dropped connections.

Should port 3000 be open in my VPS firewall?

NO! Block port 3000 from public internet access using UFW (sudo ufw default deny incoming, sudo ufw allow 22, sudo ufw allow 80, sudo ufw allow 443). Only Nginx should communicate with port 3000 over localhost.

How much RAM does a Next.js production app require?

A standard Next.js application typically consumes between 200 MB to 500 MB of RAM per worker thread during runtime, but the compilation phase (npm run build) can spike up to 1.5 GB. We recommend a VPS with at least 2 GB to 4 GB of RAM.

Can I run a database on the same VPS as Next.js?

Yes! You can run PostgreSQL, MySQL, or MongoDB directly on the same KVM VPS, connecting your Next.js backend via low-latency local sockets.

How do I handle environment variables (.env) securely on a VPS?

Store production secrets inside a .env.production file on your VPS that is explicitly excluded from your Git repository via .gitignore. Reference variables in PM2 using the env_production block in ecosystem.config.js.

Can I run multiple Next.js applications on a single KVM VPS?

Yes! You can run multiple Next.js apps listening on different local ports (e.g. 3000, 3001, 3002) and configure Nginx server blocks to proxy distinct domain names to their respective ports.

Muhammad Anees Ur Rehman
Written & Audited By

Muhammad Anees Ur Rehman

Founder & Infrastructure Architect • 3+ Years Experience

Muhammad Anees Ur Rehman is the Founder and Chief Infrastructure Architect at Alif Host. With 3+ years of hands-on work in Linux web hosting, LiteSpeed server optimization, and cloud virtualization, Anees builds and runs the hosting infrastructure behind Alif Host for Pakistani businesses, e-commerce stores, and digital agencies. A staunch advocate for transparent hosting policies and local payment integration (JazzCash, Easypaisa, Raast), he regularly publishes deep-dive technical benchmarks on server response times, WordPress performance, and cyber resiliency.

LiteSpeed Web Server TuningKVM Cloud VirtualizationcPanel & WebHost Manager (WHM)
View Full Author Profile & Articles
Featured Hosting & Infrastructure

Related Hosting & Infrastructure Solutions

Dedicated KVM ResourcesStarting at PKR 2,600/month

VPS Hosting in Pakistan with Dedicated NVMe Storage

Reliable virtual private servers with dedicated compute resources, NVMe storage, 1Gbps unmetered uplink, and local payment gateways in Pakistan.

VPS Hosting in Pakistan with Dedicated NVMe Storage
Remote DesktopStarting at PKR 3,200/month

Windows RDP Server in Pakistan: Plans and Price in PKR

Dedicated Windows Remote Desktop access with guaranteed RAM and NVMe storage for forex trading, accounting software, and continuous remote workstations.

Windows RDP Server in Pakistan: Plans and Price in PKR

Related Educational Articles

Back to Blog