Almost every production website you use sits behind NGINX. It is the front door: the first thing a request hits, and the last thing a response passes through. It terminates TLS, decides which backend server handles the request, caches responses, blocks bad traffic, and keeps the whole thing running when a server dies.
That is a lot of responsibility for one piece of software — and most NGINX outages are not NGINX failing, but NGINX configured like a development server. This post covers how production teams actually run it: reverse proxying, load balancing, health checks, SSL termination, and the tuning that keeps it fast under real traffic.
What a Reverse Proxy Actually Is
A reverse proxy sits between clients and backend servers. The client never talks to your app servers directly — it talks to NGINX, and NGINX talks to the backends.
The request lifecycle is simple:
- Client sends a request to your domain — DNS points at NGINX, not at any app server.
- NGINX receives it, applies routing rules, rate limits, and security checks.
-
NGINX forwards it to a chosen backend server via
proxy_pass. - The backend responds to NGINX, which returns the response to the client — optionally caching it for the next identical request.
Why bother with the middleman? Four reasons:
- Backends stay hidden. App servers are never exposed to the internet. Attackers see NGINX; your internal network stays internal.
- One place for TLS. Certificates live on NGINX, not on every app server. Renewal, strong ciphers, and HTTP/2 are configured once.
- Caching and compression. NGINX serves repeated responses from cache and gzips text, so backends do less work.
- A single control point. Routing, rate limiting, authentication, and logging all happen in one place, instead of being reimplemented in every service.
NGINX is good at this because of its architecture: an event-driven, non-blocking model where a small number of worker processes handle thousands of concurrent connections without a thread per connection. That is why it survives traffic spikes that would drown a thread-per-request server.
The Core Config: proxy_pass and Headers
A minimal production reverse proxy looks like this:
upstream backend {
least_conn;
server backend1.local weight=3;
server backend2.local;
server backend3.local;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name app.example.com;
ssl_certificate /etc/ssl/certs/app.example.com.crt;
ssl_certificate_key /etc/ssl/private/app.example.com.key;
location / {
proxy_pass http://backend;
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_connect_timeout 5s;
proxy_read_timeout 60s;
}
}
The headers matter more than most people realise. Without proxy_set_header Host $host, the backend sees "backend" as the host and virtual-host routing breaks. Without X-Real-IP and X-Forwarded-For, every request in your app logs appears to come from NGINX itself — your real client IPs, rate limiting, and geo logic all go blind. And X-Forwarded-Proto is what tells the backend the original request was HTTPS, so it stops redirecting users into an infinite HTTP-to-HTTPS loop.
Load Balancing Algorithms: Picking the Right One
| Algorithm | How it picks a backend | Best for |
|---|---|---|
| Round robin (default) | Sends requests in turn to each backend | Backends of equal strength, stateless apps |
least_conn |
Sends to the server with the fewest active connections | Long-lived requests, uneven request costs |
ip_hash |
Sticks a client to one backend by IP hash | Sessions stored in server memory |
| Weighted round robin | Stronger servers get more traffic (weight=3) |
Mixed hardware, gradual migration |
least_time (NGINX Plus) |
Sends to the server with the lowest latency and fewest connections | Latency-sensitive services |
Round robin is the default and the right choice for most stateless apps — it is simple, fair, and predictable. Switch to least_conn when requests vary wildly in cost: a 10-second report request and a 10-millisecond API call should not count the same. Use ip_hash only when you must — session stickiness is a workaround for state that should live in Redis or a database, and it breaks the moment that one server goes down. Weighted servers are the graceful way to drain an old server: lower its weight, wait for connections to drain, then remove it with zero downtime.
Health Checks and Reliability
A load balancer that sends traffic to a dead server is worse than no load balancer. NGINX's passive health checks handle this with two directives on each upstream server:
server backend1.local max_fails=3 fail_timeout=30s;
After 3 failed attempts within 30 seconds, NGINX marks the server unavailable and stops sending it traffic for 30 seconds, then retries it. The failed server recovers automatically — no pager, no manual intervention. (NGINX Plus adds active health checks that probe backends on a schedule; the open-source build relies on these passive checks, which is enough for most teams.)
Three reliability habits to go with it:
- Always run at least two NGINX instances behind a floating IP (keepalived/VRRP) or a cloud load balancer. One NGINX is a single point of failure for everything behind it.
-
Test before you reload.
nginx -tvalidates the config;nginx -s reloadapplies it without dropping connections. Never edit a live config and restart blind — a typo in oneserverblock takes down every site on the box. -
Watch the error log.
error_log /var/log/nginx/error.log warn;is where upstream failures, SSL errors, and timeout causes actually show up.
SSL Termination: One Place for TLS
SSL termination means NGINX decrypts HTTPS and talks plain HTTP to the backends on a trusted internal network. Certificates live in one place, renewal is one job (usually Certbot), and backends stay simple.
The production minimum:
- TLS 1.2 and 1.3 only — disable TLS 1.0/1.1 and weak ciphers.
- A strong
ssl_cipherslist andssl_prefer_server_ciphers on. - HSTS (
add_header Strict-Transport-Security "max-age=63072000" always;) once you are sure HTTPS works everywhere. - OCSP stapling (
ssl_stapling on;) so clients do not block on revocation checks. - Certificate renewal automated and monitored — an expired cert is the most embarrassing outage in the industry, and it is entirely preventable.
Caching, Compression, and Rate Limiting
Caching is the cheapest performance win NGINX offers. Static responses cached at the proxy never reach your backends at all:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g inactive=60m;
proxy_cache app_cache;
proxy_cache_valid 200 10m;
Compression is one line — gzip on; with gzip_types covering text, CSS, and JSON — and it cuts bandwidth for text responses by 70% or more. Never gzip already-compressed formats like images or video; it wastes CPU for nothing.
Rate limiting protects backends from floods, scrapers, and one buggy client:
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req zone=api_limit burst=20 nodelay;
Ten requests per second per IP, with a burst of twenty. Tune the numbers to your API — the point is that the limit exists before the incident, not after it.
Performance Tuning: The Settings That Matter
NGINX is fast out of the box, but four settings decide how fast it stays under load:
-
worker_processes auto;— one worker per CPU core. More workers than cores just adds context switching. -
worker_connections 1024;(or higher) — connections per worker. Total capacity is workers × connections; raise it deliberately, and raise the system's open-file limits (worker_rlimit_nofile) to match, or the higher number is fiction. -
keepalive 32;inside the upstream block — reuses connections to backends instead of opening a new one per request. Without it, every proxied request pays a full TCP (and TLS, if used) handshake to the backend. -
sendfile on;andtcp_nopush on;— let the kernel serve static files efficiently instead of copying data through userspace.
Measure before tuning: stub_status (or the NGINX Plus dashboard) shows active connections, accepts, and handled requests. If worker_connections is the ceiling, you will see it there — and nowhere else will tell you.
The Mistakes That Take NGINX Down in Production
- Forgetting
proxy_set_header Host— backends see the wrong host, virtual hosting breaks. - No
X-Real-IP/X-Forwarded-For— every client looks like NGINX in the logs, and IP-based rate limiting limits NGINX itself. - A single NGINX instance with no failover — the front door becomes the single point of failure.
- Editing config and restarting without
nginx -t— one typo, all sites down. - No rate limiting until the first scraper or flood.
-
ip_hashused as a substitute for shared sessions — one dead server logs out its users. - Expired certificates with no renewal monitoring.
- Upstream timeouts left at defaults — a hung backend holds worker connections until the whole proxy stalls.
Troubleshooting: 502 Bad Gateway
The error every NGINX operator meets first. A 502 means NGINX is fine, but the backend is not answering. Check in order:
-
Is the backend up?
curlit directly from the NGINX host, bypassing the proxy. - Is it listening where NGINX expects? Wrong port or socket path is the most common cause.
-
Did it time out?
proxy_read_timeouttoo short for a slow endpoint shows up as 502s under load, not at idle. - Is the backend crashing? Check its logs, not NGINX's — NGINX only reports that the connection failed.
-
Is NGINX out of connections?
worker_connectionsexhausted looks like backends failing, but the cause is the proxy itself.
The Production Checklist
- Reverse proxy with
proxy_pass, correctHostandX-Forwarded-*headers. - Load balancing algorithm chosen deliberately, not left at default by accident.
- Health checks:
max_failsandfail_timeoutset on every upstream server. - At least two NGINX instances with failover — no single front door.
- TLS 1.2+ only, strong ciphers, HSTS, automated renewal with monitoring.
- Caching for repeatable responses, gzip for text.
- Rate limiting per client before the first incident.
-
nginx -tbefore every reload; config in version control, changes via review. -
worker_processes auto,worker_connectionsraised with matching file limits, upstreamkeepaliveenabled. - Error log monitored, 502 runbook written down before the first 502.
What Hiring Managers Actually Ask
If you are targeting remote DevOps, SRE, or platform roles, NGINX is interview material because it sits in front of everything:
- "Users get intermittent 502s under load — walk me through it." (Answer: check whether the backend is up and listening, whether
proxy_read_timeoutis too short for slow endpoints, whether the backend is crashing, and whether NGINX itself is out ofworker_connections.) - "How do you do zero-downtime deploys behind NGINX?" (Answer: weighted servers — lower the old server's weight, drain its connections, remove it from the upstream, deploy, add it back, repeat for the next one. Or blue-green with two upstreams and a config reload.)
- "Why does every request in the app log come from the same IP?" (Answer: the proxy headers are missing —
X-Real-IPandX-Forwarded-Forwere never set, so the backend only ever sees NGINX.) - "How do you scale NGINX itself?" (Answer: more workers per core up to a point, then more instances behind a floating IP or cloud load balancer, with config in version control and
nginx -tbefore every reload.)
The answer they want is never "I can write a server block." It is the system around it: headers, health checks, failover, TLS discipline, and a reload habit that never takes the front door down.
Key Takeaway
NGINX is the front door of your infrastructure — hide the backends, terminate TLS once, balance deliberately, check health automatically, and never reload an untested config. A proxy that never goes down is not luck; it is headers, health checks, and a second instance.
Your turn: How do you run NGINX in production — reverse proxy, load balancer, or both? And which load balancing algorithm do you use, and why? Tell me in the comments.

Top comments (0)