user2023861
user2023861

Reputation: 8208

How do I fix this NGINX 502 Bad Gateway error?

I'm working on web sockets in an angular app. I have it connect to a python back-end through nginx. I'm find that I'm getting 502 "Bad Gateway" errors about 90% of the time. I'll do this:

  1. Load page in browser and connect web socket
  2. Python back-end sends data to angular front-end
  3. Disconnect web socket
  4. Attempt to re-connect web socket <-- 502 Bad Gateway error
  5. Hard-reload in Chrome
  6. Load page in browser and connect web socket <-- No 502 error

I can't figure out why this is happening. I can't tell why I'm getting a 502 error. Nor can I figure out why doing a hard-reload fixes the problem. Things I've tried:

What should I be looking for that will help me fix this problem?

EDIT: Here's my nginx conf.d file:

server {
  listen  80;

  index index.html;
  root /var/www/mysite;

  location / {
    access_log  /var/log/nginx/mysite/ui.access.log;
    error_log /var/log/nginx/mysite/ui.error.log;
    try_files $uri $uri/ /index.html;
  }

  location /ws/ {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Host $proxy_host;
    proxy_pass http://WEBSOCKET/;
    access_log  /var/log/nginx/mysite/ws_services.access.log;
    error_log /var/log/nginx/mysite/ws_services.error.log;
    proxy_read_timeout 300s;
  }
}

upstream WEBSOCKET {
    ip_hash;
    server 127.0.0.1:8765;
}

Upvotes: 6

Views: 14484

Answers (1)

Dominik Ehrenberg
Dominik Ehrenberg

Reputation: 1746

Not the same problem the OP had, but just in case anyone comes across this and has the same setup as I had:

I was using WebSockets over SSL (so wss:// protocol) and had 502 popping up, even though the config had worked before. The config was as follows:

...
proxy_pass http://127.0.0.1:8080;
...

In the backend I was using a Node with the ws package to create a websocket server

As I said: It was working before, but suddenly stopped working. Additionally nginx wrote upstream prematurely closed connection while reading response header from upstream errors into the error log. I suppose that either nginx or node closed some kind of security issue, that lead to the setup not working anymore.

What I had to do in order to make it work, was to use https instead of http for the proxy_pass config

...
proxy_pass https://127.0.0.1:8080;
...

Upvotes: 4

Related Questions