Nginx负载均衡异常:所有请求均指向同一服务器问题咨询
Let’s break down why all your traffic is only hitting the 3001 backend, even with least_conn configured. Here are the most likely culprits and fixes:
1. First: Confirm Your 3002/3003 Servers Are Actually Running
Nginx automatically drops backend servers it can’t reach. If your 3002 or 3003 services aren’t listening on their ports, Nginx will only route traffic to the working 3001 instance.
Test each backend directly with these commands:
curl http://127.0.0.1:3002 curl http://127.0.0.1:3003
If either returns a connection error, start those services first—this is the most common reason for this issue.
2. Keepalive Connection Reuse Is Tricking You
Browsers and most HTTP clients reuse keepalive connections by default. If you’re testing from the same client (like your browser) sending multiple requests in a row, Nginx will stick to the existing connection to 3001 instead of re-scheduling each request.
To verify and fix this:
- Use
curlwith aConnection: closeheader to force a new connection every time:
Run this several times—you should see traffic spread across all three backends.curl -H "Connection: close" http://localhost:3000 - Test from different clients (e.g., another browser, Postman, or a different machine) to see if traffic distributes properly.
- For testing purposes, tweak your upstream block to limit keepalive reuse:
Reload Nginx and test again—you’ll see traffic spread since each request uses a fresh connection thatupstream my_http_servers { least_conn; keepalive_requests 1; # Force new connection after 1 request server 127.0.0.1:3001; server 127.0.0.1:3002; server 127.0.0.1:3003; }least_conncan distribute.
3. You Forgot to Reload Nginx After Changing the Config
It’s an easy mistake! If you edited your config but didn’t tell Nginx to load the new settings, it’s still running the old configuration (maybe you only had 3001 in the upstream before?).
Reload Nginx to apply your changes:
# For most systems nginx -s reload # If using systemd systemctl reload nginx
4. Check Nginx’s Backend Connection Stats
Enable Nginx’s stub status module to see exactly how connections are being distributed. This will confirm if least_conn is working as expected.
Add this server block to your http section:
server { listen 8080; server_name localhost; location /nginx_status { stub_status on; allow 127.0.0.1; # Restrict access to localhost deny all; } }
Reload Nginx, then visit http://localhost:8080/nginx_status in your browser. You’ll see metrics like active connections and requests processed, which will show if 3002/3003 are receiving traffic.
If you saw the same issue with round_robin too, that’s a clear sign either your backends aren’t running or your config wasn’t reloaded—round_robin is Nginx’s default algorithm and should distribute traffic evenly out of the box.
内容的提问来源于stack exchange,提问作者Noober

