Guides/Server Setup
Server Setup10 min read

How to Deploy a Next.js App to Ubuntu (EC2 or VPS) with PM2 and Nginx

Deploy your Next.js application to a production Ubuntu server — build it, run it with PM2, serve it through Nginx with SSL, and set up automatic deployments.

Install Node.js and Clone Your Repo

Install nvm and Node.js 18+ (see our PM2 guide for nvm setup). Clone your repo: git clone your_repo_url /home/ubuntu/myapp. Navigate to it: cd /home/ubuntu/myapp. Copy your environment file: scp .env.local ubuntu@server:/home/ubuntu/myapp/ — never commit .env.local to git. Install dependencies: npm install.

Build and Start with PM2

Build the app: npm run build. Create a PM2 config (ecosystem.config.js): module.exports = { apps: [{ name: "myapp", script: "npm", args: "start", env: { NODE_ENV: "production", PORT: 3000 } }] }. Start: pm2 start ecosystem.config.js. Enable startup: pm2 startup && pm2 save. Verify it is running: pm2 logs myapp.

Set Up Nginx as Reverse Proxy

Install Nginx and create a site config for your domain (see our Nginx reverse proxy guide). The proxy_pass should point to http://localhost:3000. Add these headers for Next.js: proxy_set_header X-Forwarded-Proto $scheme. Next.js uses this to correctly set HTTPS URLs in SSR responses. Test config: sudo nginx -t — reload: sudo systemctl reload nginx.

Add SSL with Certbot

Run: sudo certbot --nginx -d yourdomain.com. Certbot modifies your Nginx config automatically to add HTTPS and redirect HTTP to HTTPS. Test auto-renewal: sudo certbot renew --dry-run. Your certificate expires every 90 days but renews automatically via systemd timer. Check the timer: systemctl status certbot.timer.

Set Up Zero-Downtime Deployments

For updates, SSH in and run: cd /home/ubuntu/myapp && git pull && npm install && npm run build && pm2 reload myapp. The pm2 reload command performs a rolling restart — new requests go to new workers before old ones are killed, resulting in zero downtime. Automate this with a simple deploy.sh script or a GitHub Actions workflow that SSHes in and runs the commands.

Need Help?

Want this done for you?

Our engineering team handles implementations like this every week. Get a free scoping call — we will tell you exactly what it takes and what it costs.

Book a free call

© 2026 NexWorldTech — Built for Global Dominance.