Troubleshooting 502 Bad Gateway Errors in Nginx
Systematic causes of Nginx 502 errors—upstream crashes, ports, timeouts—and how to fix them quickly.
What 502 means in an Nginx deployment
HTTP 502 Bad Gateway indicates Nginx acted as a gateway or proxy and received an invalid response from an upstream server. The problem is usually not Nginx itself but the application, socket, or timeout sitting behind it. Users see a generic error page while logs contain the clues operators need.
Vcom Web Tech debugs 502 errors weekly across Next.js, PHP-FPM, and upstream API gateways. A consistent method reduces mean time to recovery: confirm scope, read logs, verify upstream health, then adjust configuration.
Distinguish 502 from 504 Gateway Timeout. Timeouts often need proxy_read_timeout increases or application optimization, while immediate 502 responses may mean the upstream refused connections entirely.
Check whether the upstream process is running
SSH to the server and inspect PM2, systemd, or Docker status for the application service. If the process exited, Nginx logs show connect() failed while connecting to upstream. Restart the app and watch memory during boot.
Verify the port in proxy_pass matches the listening port from ss -tlnp or netstat. After deployments, teams sometimes change PORT in environment variables without updating Nginx site files.
Unix socket upstreams fail when socket paths change across releases or permissions block the nginx worker user. Align socket ownership with distribution defaults or documented hardening guides.
Read Nginx error logs first
Tail error.log while reproducing the issue. Messages about upstream prematurely closed connection point to application crashes mid-request. upstream timed out suggests slow queries or blocking I/O.
Increase error_log severity temporarily if info-level hints are missing, but revert after diagnosis to avoid log noise.
Correlate timestamps with application logs. A stack trace at the same second as a 502 confirms the handler died rather than a network blip.
Timeouts, buffers, and body size
Default proxy timeouts may be too low for report generation, webhooks, or large uploads. Adjust proxy_connect_timeout, proxy_send_timeout, and proxy_read_timeout together so no stage becomes the obvious bottleneck.
Small proxy_buffer settings occasionally trigger 502 on large response headers from verbose frameworks. Increase proxy_buffer_size and proxy_buffers when headers include large cookies or JWT.
client_max_body_size must exceed your largest acceptable upload. Requests rejected before reaching the app can still surface as 502 depending on intermediary behavior.
PHP-FPM and other non-Node upstreams
PHP-FPM pools exhaust max_children under traffic spikes, causing 502 until workers free. Monitor slow logs and raise pool limits or scale horizontally.
FastCGI pass directives must reference the correct socket or TCP port. Package upgrades sometimes move default socket paths.
Health checks at the load balancer should hit a lightweight endpoint so cold starts do not mark entire nodes bad during deploys.
Preventing repeat incidents
Add synthetic monitoring that requests critical URLs every minute from outside the server. Alert on 502 rates before customers flood support.
Use graceful reload patterns: pm2 reload, rolling Docker updates, or upstream draining in larger clusters. Hard kills mid-request produce 502 bursts that look like mysterious outages.
Document upstream map, timeout values, and owner contact in the runbook. Future troubleshooting should start from known good baselines instead of guessing which layer failed.
Additional operational notes
Operational excellence on Linux hosting requires documenting every change to Nginx, systemd, PM2, Docker, and DNS in a runbook your team shares. Vcom Web Tech clients benefit when staging environments mirror production firewall rules, TLS versions, and mail authentication so surprises appear before customers notice. Schedule quarterly reviews of backups, certificate expiry, DMARC reports, and monitoring alerts even when traffic feels stable.
When incidents occur, capture timelines and root causes in blameless postmortems. Patterns from past 502 errors, failed renewals, or bounce spikes inform checklists for the next deployment. Training new team members on SSH access, log locations, and escalation paths reduces dependency on single maintainers.
Security patches, dependency upgrades, and framework migrations should ride the same CI pipelines that deploy application code. Automate smoke tests that hit health endpoints and send test mail through staging SMTP relays. Small consistent investments beat heroic firefighting during launch weekends.
Capacity planning matters on VPS hosts where vertical scaling has limits. Watch disk inode usage, connection counts, and database connection pools as traffic grows. Proactive upgrades cost less than emergency migrations during peak sales or campaign sends.
Finally, communicate with stakeholders using plain language about risk, downtime windows, and deliverability metrics. Technical depth supports trust when email authentication or deployment strategy changes affect revenue-facing systems.
Additional operational notes
Operational excellence on Linux hosting requires documenting every change to Nginx, systemd, PM2, Docker, and DNS in a runbook your team shares. Vcom Web Tech clients benefit when staging environments mirror production firewall rules, TLS versions, and mail authentication so surprises appear before customers notice. Schedule quarterly reviews of backups, certificate expiry, DMARC reports, and monitoring alerts even when traffic feels stable.
When incidents occur, capture timelines and root causes in blameless postmortems. Patterns from past 502 errors, failed renewals, or bounce spikes inform checklists for the next deployment. Training new team members on SSH access, log locations, and escalation paths reduces dependency on single maintainers.
Security patches, dependency upgrades, and framework migrations should ride the same CI pipelines that deploy application code. Automate smoke tests that hit health endpoints and send test mail through staging SMTP relays. Small consistent investments beat heroic firefighting during launch weekends.
Capacity planning matters on VPS hosts where vertical scaling has limits. Watch disk inode usage, connection counts, and database connection pools as traffic grows. Proactive upgrades cost less than emergency migrations during peak sales or campaign sends.
Finally, communicate with stakeholders using plain language about risk, downtime windows, and deliverability metrics. Technical depth supports trust when email authentication or deployment strategy changes affect revenue-facing systems.