What is Upstream in Nginx: Explanation and Example
upstream defines a group of backend servers that handle client requests. It acts like a traffic controller, distributing requests to multiple servers for load balancing and reliability.How It Works
Think of upstream in Nginx as a dispatcher in a busy restaurant. Instead of one chef handling all orders, the dispatcher sends each order to different chefs to work on simultaneously. This helps serve customers faster and avoids overloading a single chef.
In technical terms, upstream groups several backend servers (like application servers) under one name. When a client sends a request, Nginx forwards it to one of these servers based on a chosen method, such as round-robin or least connections. This setup improves performance and availability because if one server is busy or down, others can take over.
Example
This example shows how to define an upstream block with two backend servers and use it in a server block to proxy requests.
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}When to Use
Use upstream in Nginx when you want to distribute incoming traffic across multiple backend servers. This is helpful for:
- Load balancing to improve response times and handle more users.
- Increasing reliability by having backup servers if one fails.
- Scaling applications horizontally by adding more servers without changing client requests.
For example, a website with many visitors can use upstream to spread requests across several app servers, preventing any single server from becoming a bottleneck.
Key Points
- Upstream groups backend servers under one name.
- It enables load balancing and failover.
- Common load balancing methods include round-robin and least connections.
- Used with
proxy_passto forward client requests.
Key Takeaways
upstream defines backend server groups for load balancing in Nginx.proxy_pass with upstream to forward requests.