Nginx作为Grafana反向代理时出现Bad Gateway错误求助(附配置及错误日志)
Alright, let's tackle that frustrating 502 error you're seeing. The connect() failed (111 connection refused) log entry tells us exactly what's going wrong: Nginx can't establish a connection to your Grafana instance running on port 8080. Let's walk through the most likely fixes step by step.
1. Verify Grafana's Protocol & Listener First
The biggest red flag here is your Nginx config using https://localhost:8080 as the upstream, but default Grafana installs use HTTP, not HTTPS, by default.
Test if you can reach Grafana directly from the server:
# Try HTTP first (default) curl -I http://localhost:8080 # Then try HTTPS if the above fails curl -I https://localhost:8080 --insecureIf the HTTP request works but HTTPS doesn't, that's your issue. Update your Nginx
proxy_passlines to usehttp://localhost:8080instead ofhttps://.Double-check Grafana's config file (usually
/etc/grafana/grafana.ini) in the[server]section:- Ensure
http_port = 8080matches what you're targeting - Check
protocol = http(if you haven't explicitly enabled Grafana's SSL, this will be the default)
- Ensure
2. Check Firewall/SELinux Restrictions
Even if Grafana is running, your server's security tools might be blocking Nginx from accessing port 8080:
Firewall: Verify port 8080 allows local connections. For firewalld:
firewall-cmd --add-port=8080/tcp --permanent firewall-cmd --reloadFor iptables, ensure there's no rule dropping traffic to 127.0.0.1:8080.
SELinux: By default, SELinux prevents Nginx from making outgoing network connections. Fix this with:
setsebool -P httpd_can_network_connect 1
3. Confirm Grafana's Listening Address
Sometimes Grafana is configured to only listen on a specific IP, not localhost or all interfaces:
- In
grafana.ini, check thehttp_addrsetting. If it's set to something other than127.0.0.1or0.0.0.0, update it to127.0.0.1(for local access only) or0.0.0.0(to allow all interfaces). Then restart Grafana:systemctl restart grafana-server
4. Fix Nginx Config Syntax & Path Issues
Your config has two small but important issues that could cause problems even after fixing the connection:
- Wrong quotes: The line
proxy_set_header Connection “Upgrade”;uses Chinese double quotes instead of English ones. Replace them with standard quotes:proxy_set_header Connection "Upgrade"; - Incorrect proxy_pass path for
/api/live: Right now, your/api/livelocation proxies tohttps://localhost:8080/, which strips the/api/livepath. Update it to preserve the path:location /api/live { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $http_host; proxy_pass https://localhost:8080; # Remove the trailing slash to keep the path }
After making these changes, restart Nginx to apply them:
systemctl restart nginx
内容的提问来源于stack exchange,提问作者Mohamed Emad

