Linux Exercise 11c - optional - Weighted-Load-Balancing
Optional Extension: Weighted Load Balancing with Nginx
Section titled “Optional Extension: Weighted Load Balancing with Nginx”1. Goal
Section titled “1. Goal”In this extension you will:
- Configure weighted load balancing for your backend pool
- Make one backend receive more traffic than the other
- Verify the distribution using
curl
Weights are useful when:
- One backend server has more CPU/RAM
- You want to gradually shift traffic to a new version (canary style)
2. Step 1 – Configure Weighted Upstream
Section titled “2. Step 1 – Configure Weighted Upstream”Edit:
sudo nano /etc/nginx/sites-available/loadbalance.localFind your upstream block and adjust it as follows (ensure ip_hash is NOT used here):
upstream backend_pool { server 127.0.0.1:8001 weight=3; server 127.0.0.1:8002 weight=1;}Explanation:
- Backend 1 has weight 3
- Backend 2 has weight 1
- Ratio of requests: ~3:1 (about 75% vs 25%)
Save, test, and reload:
sudo nginx -tsudo systemctl reload nginx3. Step 2 – Test the Distribution
Section titled “3. Step 2 – Test the Distribution”Run multiple requests:
for i in {1..20}; do curl http://loadbalance.local/; echo; doneCount how many times you see each backend:
{"backend":"1"}{"backend":"2"}
You should see backend 1 significantly more often than backend 2.
For a more precise count, you can use:
for i in {1..50}; do curl -s http://loadbalance.local/; echo; done | sort | uniq -cThis will group and count occurrences.
4. Step 3 – Try Different Ratios
Section titled “4. Step 3 – Try Different Ratios”Experiment by changing the weights:
upstream backend_pool { server 127.0.0.1:8001 weight=5; server 127.0.0.1:8002 weight=1;}Or:
upstream backend_pool { server 127.0.0.1:8001 weight=1; server 127.0.0.1:8002 weight=3;}Each time:
- Save the file
- Run
sudo nginx -t - Run
sudo systemctl reload nginx - Perform the test loop again
5. Step 4 – Document Your Observations
Section titled “5. Step 4 – Document Your Observations”In your protocol, describe:
- The weight values you tried
- The approximate ratio of responses you observed
- How weights could be used in real deployments, e.g.:
- Slowly shifting traffic to a new version
- Sending most traffic to a more powerful server
- “Canary testing” a new backend for a small percentage of users