Common Nginx Error Log Pattern (Node.js / Express)
When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Node.js / Express, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:
2026/11/22 17:12:03 [error] 4112#4112: *773 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.19, server: api.nodeapp.dev, request: "POST /api/auth/login HTTP/2.0", upstream: "http://127.0.0.1:4000/api/auth/login", host: "api.nodeapp.dev"
Reverse Proxy Architecture & Header Forwarding for Node.js / Express
Running a Node.js Express API managed by PM2 on port 4000 behind Nginx is one of the most reliable, battle-tested production topologies on Linux servers. Nginx handles TLS termination, HTTP/2, static asset delivery, and slow-loris protection so Node.js's single-threaded event loop remains dedicated to business logic and database queries.
However, putting Nginx in front of Express changes how Express perceives every incoming HTTP request. Without explicit trust proxy configuration in Express and matching X-Forwarded-For / X-Forwarded-Proto headers in Nginx, req.ip always resolves to 127.0.0.1, req.secure returns false, and express-rate-limit ends up rate-limiting every visitor on Earth inside a single shared 127.0.0.1 bucket.
Likewise, Express session cookies with cookie: { secure: true } silently fail to set if Express believes the connection is insecure HTTP. Pairing app.set("trust proxy", 1) in Express with Nginx's proxy_set_header X-Forwarded-Proto $scheme and proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ensures accurate client IP attribution, valid secure cookies, and zero-downtime PM2 cluster reloads.
Finally, pay close attention to trailing slashes in proxy_pass when mounting Express under /api/. Leaving Strip Prefix OFF preserves /api/auth/login for Express routers mounted at app.use("/api", apiRouter), whereas turning Strip Prefix ON rewrites /api/auth/login to /auth/login before Express ever sees the request.
To harden an Express and PM2 production node behind Nginx, combine Nginx limit_req_zone rate limiting at the edge (stopping abusive floods before they touch Node.js) with Express trust proxy hop validation inside your application routes. Ensure systemd or pm2 startup persists your PM2 process list across kernel reboots, verify that Nginx passes X-Real-IP and X-Forwarded-For cleanly without stripping existing proxy headers inconsistently, and inspect /var/log/nginx/error.log after every deployment to confirm zero upstream connection refusals.
Step-by-Step Nginx & Node.js / Express Deployment Guide
Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.
1Enable trust proxy in Express for Accurate Client IPs and Secure Cookies
src/server.tsSet app.set("trust proxy", 1) when exactly one Nginx proxy sits in front of Express (use 2 if Cloudflare CDN also proxies traffic to Nginx). Avoid trust proxy: true blindly, which lets express-rate-limit warn about spoofable X-Forwarded-For chains.
src/server.tstypescriptimport express from 'express'; import rateLimit from 'express-rate-limit'; const app = express(); // Trust the single local Nginx reverse proxy hop app.set('trust proxy', 1); app.use( '/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100, standardHeaders: true, legacyHeaders: false, }) ); app.get('/api/whoami', (req, res) => { res.json({ clientIp: req.ip, protocol: req.protocol, secure: req.secure, }); }); app.listen(4000, '127.0.0.1');2Run Express in PM2 Cluster Mode for Zero-Downtime Reloads
ecosystem.config.cjsPM2 cluster mode spins up one Node.js worker per CPU core and shares port 4000 cleanly so pm2 reload reloads your API without Nginx returning 502 Bad Gateway during deploys.
ecosystem.config.cjsjavascriptmodule.exports = { apps: [ { name: 'express-api', script: 'dist/server.js', instances: 'max', exec_mode: 'cluster', env_production: { NODE_ENV: 'production', PORT: 4000, }, }, ], };3Synchronize Express Body Parsers With Nginx client_max_body_size
src/middleware/bodyLimits.tsExpress defaults to 100 KB for express.json() while Nginx defaults to 1 MB. Match both limits (e.g., 10 MB for JSON/uploads) so large payloads fail predictably rather than abruptly dropping connections.
src/middleware/bodyLimits.tstypescriptimport express from 'express'; export function registerBodyParsers(app: express.Express) { app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ extended: true, limit: '10mb' })); }4Validate Nginx Syntax, Reload, and Test Forwarded Headers
terminalReload Nginx after copying the generated config and call /api/whoami over HTTPS to confirm req.ip reflects your real public IP and req.secure equals true.
terminalbashsudo nginx -t && sudo systemctl reload nginx curl -s https://api.nodeapp.dev/api/whoami
Common Node.js / Express Nginx Reverse Proxy Pitfalls
Review these three production failure modes before reloading Nginx on staging or live servers.
Using app.set("trust proxy", true) Breaking express-rate-limit v7+
Modern express-rate-limit raises ERR_ERL_PERMISSIVE_TRUST_PROXY if you pass boolean true to trust proxy because attackers could forge arbitrary X-Forwarded-For headers. Always specify the exact proxy hop count like app.set("trust proxy", 1) or "loopback".
502 Bad Gateway Caused by Binding Express to IPv6 Only While Nginx Proxies IPv4
Calling app.listen(4000) without a host argument can bind :: on some Linux kernels while Nginx proxies to 127.0.0.1:4000 (or vice versa when using localhost). Explicitly pass app.listen(4000, "127.0.0.1") and match 127.0.0.1:4000 in Nginx.
Enabling Express compression() Middleware Alongside Nginx gzip on
Compressing responses inside Node.js wastes event-loop CPU cycles and interferes with Nginx gzip heuristics. Let Nginx handle gzip compression and remove the Express compression middleware.
Complete Your Deployment With Matching Docker Compose & CORS Tools
Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:
Generate a Docker Compose config for Node.js APIs, BullMQ background workers, Redis 7, and PostgreSQL 16 with native healthchecks and noeviction Redis safety.
Fix CORS preflight and cookie credential errors between Node.js Express APIs and Next.js App Router. Configure cors() middleware, app.options, and Helmet.
Frequently Asked Questions
- Why does Nginx log "connect() failed (111: Connection refused)" for my Express API?
- Error 111 means nothing is actively listening on 127.0.0.1:4000. Verify your PM2 process is online (pm2 status), check pm2 logs for startup crashes, and confirm Express is bound to port 4000 on 127.0.0.1.
- Should I use Strip Prefix ON or OFF when proxying /api/ to Express?
- Keep Strip Prefix OFF if your Express routes already include the prefix (app.use("/api", router)). Turn Strip Prefix ON if your Express app registers routes at the root (app.get("/users")) while Nginx exposes them publicly at /api/users.
- How do I prevent 502 errors while deploying a new Express build with PM2?
- Run Express in PM2 cluster mode with at least 2 instances and use pm2 reload express-api instead of pm2 restart. PM2 spins up new workers and waits for them to listen before gracefully draining old connections.
- How many proxies should I trust if Cloudflare sits in front of Nginx and Express?
- If traffic travels Client -> Cloudflare -> Nginx -> Express, set app.set("trust proxy", 2) in Express (or configure Nginx ngx_http_realip_module with Cloudflare IP ranges and keep trust proxy at 1).
Related Nginx Reverse Proxy Guides
Browse all 10 Nginx guides →Nginx Reverse Proxy Config for Next.js SSR (App Router, SSL & Streaming)
Generate a production Nginx reverse proxy for Next.js App Router on port 3000 with Certbot SSL, _next/static caching, streaming responses, and WebSockets.
Nginx Reverse Proxy Config for Socket.IO & WebSockets (Upgrade & 3600s)
Fix WebSocket 400 errors and 60-second disconnects in Nginx for Socket.IO and ws servers. Generate Upgrade, Connection map, and 3600s proxy_read_timeout blocks.
Nginx Config for React (Vite) SPA + Same-Origin /api/ Proxy (Zero CORS)
Serve a built React Vite dist/ SPA at / with try_files history fallback while proxying /api/ to your backend on the same Nginx domain to eliminate CORS.
Nginx Multi-Service Subpath Routing Config (/api/, /auth/ & /ws/)
Route /api/, /auth/, and /ws/ microservices to separate backend ports under one Nginx HTTPS domain. Master trailing-slash prefix stripping and prevent 404s.