title: Flask with SocketIO on Uwsgi and Nginx
body: <p>I am working on Flask app that uses WebSockets to communicate with frontend. It hosted on Amazon EC2 behind nginx and serverd by uwsgi.</p>
  
  <p>Here is uwsgi config I am using to serve then app:</p>
  
  <pre><code>[uwsgi]
  plugins=python3,logfile
  chdir=/srv/myapp/
  master=true
  home=/srv/myapp/.venv
  module=application
  callable=flask_app
  uid=uwsgi
  gid=myapp
  socket=/srv/myapp/uwsgi.sock
  chown-socket=uwsgi:myapp
  chmod-socket=660
  logto = /srv/myapp/logs/uwsgi.log
  for-readline = /srv/myapp/.vars
    env = %(_)
  endfor =
  </code></pre>
  
  <p>And excerpt from nginx config that covers socketio endpoint:</p>
  
  <pre><code>location /socket.io/ {
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
  
      proxy_http_version 1.1;
      proxy_buffering off;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      proxy_pass http://unix:///srv/myapp/uwsgi.sock;
  }
  </code></pre>
  
  <p>Without websockets everything works fine. Locally (I am using Windows) everything works perfect too - I just added <code>transport: ['websockets', 'polling']</code> on the client to ensure that correct protocol will be chosen.</p>
  
  <p>Locally I am running it as recommended in <a href="https://flask-socketio.readthedocs.io/en/latest/#initialization" rel="nofollow noreferrer">Flask-SocketIO</a> documentation and also I installed <code>eventlet</code> (I don't know why but in Windows x64 <code>gevent</code> wrapper works badly with <code>Werkzeug</code> dev server).</p>
  
  <p>When app is deployed I see only errors <code>websocket.js:112 WebSocket connection to 'ws://myapp.com/socket.io/?EIO=3&amp;transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 502</code> in browser. On the server side I have following in uwsgi log: <code>invalid request block size: 21573 (max 4096)...skip</code>. Increasing of the buffer size changes nothing.</p>
  
  <p>In nginx logs I have: <code>*413 upstream prematurely closed connection while reading response header from upstream, client: 171.6.248.10, server: localhost,, request: "GET /socket.io/?EIO=3&amp;transport=websocket HTTP/1.1", upstream: "http://unix:///srv/myapp/uwsgi.sock:/socket.io/?EIO=3&amp;transport=websocket", host: "myapp.com"</code></p>
  
  <p>I tried to add these lines to uwsgi.ini:</p>
  
  <pre><code>gevent=1000
  http-websockets=true
  </code></pre>
  
  <p>without any success</p>
  
  <p>What is it and how it can be solved?</p>