nginx reverse proxy node js pm2 Setup (2026): Secure & Fast
Set up nginx reverse proxy for Node JS apps managed by PM2. Learn best practices on security, optimization, and troubleshooting for nginx reverse proxy node js pm2.
Putting nginx in front of your Node.js app (running with PM2) yields many advantages: SSL offloading, request buffering, improved security, and a streamlined deployment process. You'll configure nginx as a reverse proxy, forwarding all incoming web requests to your Node.js service, which is managed for resilience and zero-downtime by PM2. This detailed guide explains how to create the nginx reverse proxy node js pm2 setup: configure nginx, set up PM2, connect and secure both, solve typical errors, and ship production-ready Node.js APIs or web apps using real configurations deployed at scale.
Why use nginx reverse proxy for Node.js with PM2?
nginx is better optimized than Node.js for dealing with direct internet clients, HTTPS, slow connections, and managing large numbers of incoming requests. Its low memory footprint and asynchronous event-based processing make it ideal as a front-line reverse proxy. PM2, meanwhile, simplifies process management—restarting apps if they crash, allowing zero-downtime deployments, and supporting robust logging and process clustering for multi-core CPUs. Combining nginx reverse proxy node js pm2 means you gain efficiency, reliability, and security without reinventing the wheel.
- SSL/TLS termination at nginx, so Node.js stays simple and fast.
- Rate limiting and basic DoS/DDoS protection natively in nginx.
- Simple scaling: host multiple Node.js apps, route traffic by hostname or path.
- Graceful restarts and rolling deploys—nginx queues new requests while apps restart behind PM2.
- Automatic restart and monitoring of Node apps via PM2—essential for resilient production systems.
- Centralized logging: forward all logs to one place, tagging by app/process using PM2's features.
- Request buffering and static file serving done by nginx, reducing load on Node.js.
nginx reverse proxy node js pm2: quick setup & config
To create an nginx reverse proxy node js pm2 stack, follow these basic steps:
1. Start your Node.js app under PM2 on a local-only port (for example, 3000). 2. Configure nginx to listen on external ports (80 for HTTP, 443 for HTTPS) and proxy incoming requests to your local Node.js port. 3. Add essential nginx proxy settings—headers, timeouts, buffering—that production traffic requires.
Example code and configuration for a simple deployment:
Install and start your Node.js app:
npm install -g pm2
# Alternatively, you can use yarn (less common):
# yarn global add pm2
pm2 start server.js --name my-app
# Example nginx server block for HTTP (expand for HTTPS below):
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 60s;
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
# Gzip responses for performance
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
}
# For HTTPS, also include SSL settings and a redirect from HTTP to HTTPS.
# After saving your config:
sudo nginx -t # Check for syntax errors
sudo nginx -s reload
Prerequisites: what you’ll need
Before configuring nginx reverse proxy node js pm2, make sure you've prepared the following: - An existing Node.js app (tested with Node.js v20 and up for long-term security support). - PM2 installed globally (recommend PM2 version 5+ for active support and features). - Properly installed nginx (works with both mainline and stable version—Ubuntu/Debian shown here). - SSH root or sudo access. For safety, consider creating a dedicated deploy user. - A DNS domain or subdomain pointing to your server's public IP.
If nginx or PM2 are missing, install them with: sudo apt update && sudo apt install nginx npm install -g pm2 # (Yarn install alternative: yarn global add pm2, though npm is the current best practice)
Check installed versions: nginx -v pm2 -v node -v
How to configure nginx as reverse proxy for Node.js with PM2
Connect your nginx reverse proxy node js pm2 setup with these detailed steps: - Bind your Node.js app only to 127.0.0.1 to prevent outsiders from bypassing nginx (e.g. app.listen(3000, '127.0.0.1')). - Create an nginx site config in /etc/nginx/sites-available/my-app, then symlink it into sites-enabled. - Add all recommended proxy headers (including X-Forwarded-Host/Proto) and ensure timeouts suit your API/service load. - Use PM2’s cluster mode (pm2 start server.js -i max) to spread load across all available CPU cores—this is critical for high-traffic production systems. - Test end-to-end: local curl http://localhost:3000 should respond; then curl http://example.com from outside should show the same app output.
Expanded checklist for implementation:
- Set Node app to bind ONLY to 127.0.0.1 or ::1 for security.
- Check UFW/firewall: only open ports 80, 443 (and 22 for SSH). Block 3000 and other app ports.
- Validate nginx config: sudo nginx -t before every reload.
- Symlink config: sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/
- Reload nginx safely: sudo nginx -s reload, or sudo systemctl reload nginx.
- Run Node.js in PM2 cluster mode: pm2 start server.js -i max for maximal CPU utilization.
- For config reloads & code changes: pm2 reload all or pm2 reload <app-name> for zero-downtime restarts.
- Automate environment variables and per-app settings with PM2’s ecosystem.config.js.
- Ensure logs are accessible and not world-readable; set up logrotate for both nginx and PM2 logs.
Best practices: nginx, PM2 & Node.js in production
To keep your nginx reverse proxy node js pm2 stack robust and secure in production, implement the following practices: - Always terminate SSL in nginx—not in Node.js—for performance and centralized management. Use automated tools like Certbot (for Let's Encrypt) or AWS ACM for obtaining and renewing certificates. - Set reasonable proxy_read_timeout and related values—enough for your biggest upstream request (e.g. large file upload), but not so high as to invite abuse. - Use all the proxy_set_header directives so your Node.js apps get the real client IP, host, and protocol, which are vital for logging and analytics. - Run PM2 as a regular, non-root user for security. For production reliability, employ PM2's ecosystem.config.js—don't rely on ad-hoc process management. - Enable and test PM2 startup scripts ('pm2 startup') so your apps restart on server reboot. Always run pm2 save as the deploy user after any process config change. - Set up log rotation for PM2 and nginx logs using 'logrotate' or systemd timers to avoid disk-full errors. - Monitor runtimes: use pm2 monit for app health. For team-managed infrastructure, integrate pm2-gui, keymetrics, or dashboards with alerting. - Regularly update Node.js, nginx, and PM2 for current security fixes and performance improvements.
- Automate SSL certificate renewal using Certbot, ACM, or cron jobs.
- Export NODE_ENV=production in your app and process configs.
- Cluster mode scales horizontally: pm2 start server.js -i max uses all available CPU cores.
- Don’t expose Node.js ports (like 3000/4000) in firewall or nginx config.
- Enable log rotation for /var/log/nginx/*.log and PM2 logs (see /home/<user>/.pm2/logs/).
- Enforce strong Content-Security-Policy and other security headers using nginx's add_header and Node.js middleware like helmet.
- Implement rate limiting with nginx 'limit_req_zone' and 'limit_req' to slow abuse.
- Send security-related alerts on Nginx config reload failure or PM2 process exit.
Zero downtime deploys: PM2 reload and nginx reverse proxy
A top feature of nginx reverse proxy node js pm2 deployments is true zero-downtime deployments. PM2's ability to reload or gracefully restart processes means you never need to drop requests during code updates.
The zero-downtime deployment workflow:
- Pull the latest code changes into your project directory using git (or rsync, or deployment scripts). - Build or transpile your app assets as needed. - Run pm2 reload my-app or pm2 reload ecosystem.config.js. PM2 will spawn new worker processes, gracefully closing old ones only after new ones are ready. - nginx continues to proxy requests without interruption, holding new connections until at least one healthy backend worker is ready. - Always tail (watch) both PM2 logs and nginx logs during deployment to catch unexpected errors.
Extra troubleshooting: - A 502 Bad Gateway typically means the upstream Node.js app is down, still booting up, or on the wrong port. PM2 process crashes (see pm2 logs <app-name>) are the first thing to check. - If reloads take too long, tune 'proxy_connect_timeout' and use health checks to avoid failing deployments. - For blue-green or canary deploys, use two PM2 process groups and switch backend with nginx config/test before a full cutover.
How to run multiple Node.js apps behind nginx and PM2
A core benefit of the nginx reverse proxy node js pm2 approach is hosting multiple apps (or microservices) securely and efficiently on one server.
Use nginx server blocks (virtual hosts) for each domain/subdomain, and run each Node.js app as a distinct PM2 process—on its own local port. PM2 manages all the processes and keeps them alive.
Expanded example multi-app nginx config:
server { listen 80; server_name api.example.com; location / { proxy_pass http://127.0.0.1:4000; 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_read_timeout 60s; } }
server { listen 80; server_name app.example.com; location / { proxy_pass http://127.0.0.1:5000; 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_read_timeout 60s; } }
Now, in PM2: pm2 start api.js --name api-app --watch pm2 start web.js --name web-app --watch
'the --watch flag enables auto-restart on local changes (dev only! remove in production).'
This configuration allows nginx to route by domain or path, while PM2 keeps each Node instance running, collecting distinct logs and statistics per service.
For more complex cases, use nginx location blocks for different API endpoints, sticky session settings, or path-based routing. Make sure each app listens on a unique localhost port, and be explicit with PM2 process configs.
- Set distinct PM2 process names and ports per app.
- Configure separate log files in PM2 ecosystem config for clarity.
- If using HTTPS, copy the server_name/certificate blocks for each app domain.
Common errors: nginx reverse proxy node js pm2 setup
Troubleshooting common nginx reverse proxy node js pm2 problems:
- 502 Bad Gateway: The backend Node.js app is down, misconfigured, or on a different port than nginx proxy_pass expects. Always verify with pm2 list and check which port each process listens on. Use sudo netstat -plnt or ss -plnt to see open ports.
- Real client IP missing: If your Node.js logs only show 127.0.0.1, double-check proxy_set_header X-Forwarded-For and review your app’s logic for extracting real IP from request headers (don't trust client-supplied X-Forwarded-For without validation).
- SSL/TLS issues: nginx must have valid ssl_certificate and ssl_certificate_key directives. Use Let's Encrypt and Certbot to obtain and auto-renew certs. Example: sudo certbot --nginx -d example.com
- PM2 apps do not restart on reboot: Complete the setup by running pm2 startup as the deploy user, then pm2 save. Run pm2 resurrect at boot if needed, or enable systemd integration.
- nginx reload/config errors: Always test configs first: sudo nginx -t. If you get errors, check syntax, missing semicolons, and file permissions.
- Log file bloat: PM2 and nginx can both generate large logs. If you ignore log rotation, you risk running out of disk space. Configure logrotate for each.
Security tips: hardening your nginx + Node + PM2 stack
Multi-layer security in an nginx reverse proxy node js pm2 deployment is vital: - nginx: Limit allowed HTTP methods, use add_header directives for HSTS (Strict-Transport-Security), X-Content-Type-Options, X-Frame-Options, and Content-Security-Policy. Implement rate limiting with limit_req_zone (e.g. block IPs sending more than 20 requests/sec). Set up fail2ban for repeated offending IPs. - Node.js: Set NODE_ENV=production for optimized error reporting (no stack traces to users), enforce HTTP headers with npm packages like helmet, and don’t serve static or sensitive files directly from your app folder—serve only intended assets. - PM2: Always run as a least-privilege OS user (not root). Use ecosystem.config.js to securely manage environments and secrets. Never log secrets, passwords, or tokens. - OS/system: Keep all packages—Node.js, nginx, PM2, your app, and the OS—up-to-date with security patches. Disable unused network interfaces. Use UFW, firewalld, or cloud security groups to lock down all ports except those truly needed (usually 80/443/22).
- Disable server_tokens in nginx to hide nginx version info.
- Set up Web Application Firewall (WAF) for high-risk apps.
- Review all open ports (sudo ss -tulwn) after each config.
- Monitor file and resource usage (CPU, RAM, disk space) for unexpected spikes—could signal attacks.
- Automate security audits with tools like Lynis or OpenVAS.
Conclusion: nginx reverse proxy node js pm2 for modern DevOps
The nginx reverse proxy node js pm2 stack is a benchmark combination for high-availability production APIs and web apps. You get robust security, hardened entry points, fast static file serving (offloaded entirely to nginx), seamless HTTPS, and easy, minimal-downtime deployments—trusted everywhere from SaaS startups to enterprises.
Think of the nginx reverse proxy node js pm2 architecture as your platform’s backbone: resilient, easy to automate, and straightforward to monitor and update. Put configs and deployment scripts under version control, use infrastructure-as-code where possible (Ansible, Terraform, etc.), and always roll out changes to test/staging before production. A process-focused, security-first approach using nginx, Node.js, and PM2 will save you countless headaches and maximize uptime.
Frequently asked questions
How do I restart my Node.js app with PM2 and nginx?
Use pm2 reload <app-name> to gracefully restart or reload your Node.js app. With nginx reverse proxy in place, there is zero downtime—nginx continues accepting connections and forwards them as soon as the app process is healthy.
Why do I get a 502 Bad Gateway with nginx and PM2?
This typically means the Node.js app managed by PM2 is down, crashing, or not listening on the port your nginx config specifies. Confirm using 'pm2 list' and check logs for crashes with 'pm2 logs <app-name>'.
How do I add SSL/HTTPS to Node.js with nginx reverse proxy?
Terminate SSL in nginx. Use Certbot or provide certificates to nginx, then proxy requests to your backend Node.js app over HTTP (not HTTPS). You only need SSL from end user to nginx—not between nginx and Node.js on localhost.
How do I run multiple Node.js apps behind nginx and PM2?
Configure a separate nginx server block for each app (by domain or path), each forwarding to a different local port. Launch apps on unique ports and with unique PM2 process names for separate management, logging, and scaling.
Should I expose my Node.js app to the public or only via nginx?
Never expose your Node.js server directly to the public internet. Always bind your app to 127.0.0.1, then route external requests through nginx. nginx handles public HTTP/S, providing security, buffering, and central control.