Search code examples
python-3.xnginxflaskuwsgiflask-socketio

getting 400 Bad Request error frequently when trying to use flask-socket with uwsgi and nginx


I have a flask app running with Flask-SocketIO on port 5000.

I am using uwsgi to run this app on the production server.

This is my uwsgi .ini file for the app:

[uwsgi]
module = server.webserver:app
callable =  app

master = true
processes = 5

http-socket = 0.0.0.0:5000

die-on-term = true
plugin = python35

#chdir = /var/xyz/webapp
wsgi-file = /var/xyz/webapp/server/webserver.py
virtualenv = /opt/venv3
#home = /opt/venv3/bin
gevent = 1000
enable-threads = true

And I am using nginx as reverse proxy to this app & my nginx server block is :

 server {
        #listen 80 default_server;
        #listen [::]:80 default_server;

        client_body_timeout 15s;
        client_header_timeout 15s;

        server_name x.y.z;

        root /var/xyz/webapp;
        index index.html index.htm index.nginx-debian.html;
        location /{
            proxy_pass      http://127.0.0.1:5000;
            proxy_redirect  off;

            proxy_set_header        Host $host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /socket.io {
            include proxy_params;
            proxy_http_version 1.1;
            proxy_buffering off;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass http://localhost:5000/socket.io;
        }
 }

Now every time the client tries to connect to the socket the request gets 400 Bad Request Error frequently. But if I comment these lines from my uwsgi .ini file:

#master = true
#processes = 5

the socket gets connected and runs normally.


Solution

  • I know this is a little bit late however I believe it has to do with the processes = 5 portion. Per the dev at this link Nginx should be setup to do load balancing multiple processes across socket servers. This is more to help anyone else that stumbles across this. Flask-SocketIO imo is incredibly difficult to configure properly. Load balancing multiple servers is easy enough in Nginx though. It is as simple as binding the flask app to a new port (5001, 5002 etc) and adding the nodes with the uWSGI apps as nodes to Nginx.

    More details can be found at this link as they explain it better