Reverse Proxy and Load Balancing
Nginx's most powerful use case is as a reverse proxy. It sits in front of your application servers — Node.js, Python, Go, PHP-FPM — buffers requests, handles SSL termination, and distributes load.
The Proxy Mental Model
Client → Nginx (public-facing)
├── SSL termination
├── Compression
├── Rate limiting
├── Static files served directly
└── proxy_pass → Upstream app (internal port)
├── Node.js :3000
├── Python/Gunicorn :8000
├── Go app :8080
└── Another Nginx instance
What You Will Learn
- How
proxy_passworks and what headers must be forwarded - How to define
upstreamblocks for multiple backend servers - Load balancing strategies: round-robin, least connections, IP hash, weighted
- How to pass the real client IP through to the backend
- Health checks and failure handling
- WebSocket proxying
- Buffering and timeout settings
Topics in This Module
- proxy_pass Basics —
proxy_pass, required headers, location patterns - Upstream Blocks — Defining multiple backends, server weights, backup servers
- Load Balancing Strategies —
round_robin,least_conn,ip_hash,random - Proxy Headers —
X-Real-IP,X-Forwarded-For,Host,X-Forwarded-Proto - Health Checks — Passive failure detection,
max_fails,fail_timeout - WebSocket Proxying —
UpgradeandConnectionheaders, timeout settings - Proxy Buffers and Timeouts —
proxy_buffering,proxy_read_timeout, buffer sizes
Best Practices
- Always set
proxy_set_header X-Real-IP $remote_addr;— backends need the real client IP - Set
proxy_set_header Host $host;to pass the correct hostname to the backend - Use
proxy_connect_timeoutandproxy_read_timeoutto avoid hanging workers - For WebSockets, add
proxy_http_version 1.1and theUpgrade/Connectionheaders - Use
least_connfor long-lived connections (WebSockets, uploads);round_robinfor short API calls
Success Checkpoint
By the end of this module you should be able to proxy traffic to any HTTP backend, configure upstream load balancing, forward the correct headers, and handle upstream failures gracefully.