What is Upstream Block in Nginx: Explanation and Example
upstream block in Nginx defines a group of backend servers that Nginx can proxy requests to. It is mainly used to load balance traffic across multiple servers or services, improving reliability and performance.How It Works
The upstream block acts like a traffic controller for Nginx. Imagine you have several identical restaurants (servers) and many customers (requests) arriving. Instead of sending all customers to one restaurant, the traffic controller directs each customer to a different restaurant to avoid crowding.
In Nginx, the upstream block lists backend servers by their addresses. When a user makes a request, Nginx picks one server from this list based on a load balancing method (like round-robin). This helps spread the work evenly and keeps the service fast and available.
Example
This example shows an upstream block named backend_servers with two servers. The server block uses this group to proxy requests.
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend_servers;
}
}When to Use
Use the upstream block when you want to distribute incoming traffic across multiple backend servers. This is helpful to:
- Improve performance by balancing load
- Increase reliability by having backups if one server fails
- Scale your application horizontally by adding more servers
Common real-world cases include web applications, APIs, or microservices where multiple instances run behind a single Nginx proxy.
Key Points
- The
upstreamblock groups backend servers for load balancing. - Nginx uses this block to proxy requests to multiple servers.
- It supports different load balancing methods like round-robin and least connections.
- Improves availability and scalability of applications.
Key Takeaways
upstream block defines backend servers for Nginx to proxy requests.proxy_pass to point to the upstream group.