salnixon
By:
salnixon

How to create Systemd Unit File for a Flask App using SocketIO?

July 20, 2017 254 views
Python Frameworks Nginx Ubuntu 16.04

I want to use Flask and Flask SocketIO for realtime Data Visualization. I have set up the Flask App with this Digital Oceans Tutorial. Everything works. I want to create a systemd unit file for running flask with flask socketio in the background. I have tried to change the old systemd unit file (digital oceans tutorial) to run Flask with SocketIO but it doesn't work.

Systemd Unit File

  [Unit]
    Description=Gunicorn instance to serve my_app
    After=network.target

    [Service]
    User=app_user
    Group=www-data
    WorkingDirectory=/home/user/my_app
    Environment="PATH=/home/user/my_app/venv/bin"
    ExecStart=/home/user/my_app/venv/bin/gunicorn --workers 3 --bind unix:my_app.sock -m 007 wsgi:app

    [Install]
    WantedBy=multi-user.target

My new NGINX Config File:

server {
    listen 80;
    server_name my_server;

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:5000;
    }

    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://127.0.0.1:5000/socket.io;
    }
}

I stopped the the systemd my_app service and tested the Flask App by typing:

(venv) $ gunicorn --worker-class eventlet -w 1 --bind 127.0.0.1:5000 wsgi:app

It works.

Unfortunately the changes in the systemd Unit File doesn't work. I have tried:

ExecStart=/home/user/my_app/venv/bin/gunicorn --worker-class eventlet -w1 --workers 3 --bind 127.0.0.1:5000 wsgi:app

ExecStart=/home/user/my_app/venv/bin/gunicorn --worker-class eventlet -w1 --workers 3 --bind unix:my_app.sock -m 007 wsgi:app

Error Message (NGINX Error log): "failed (111: Connection refused) while connecting to upstream"

Changing User and Group doesn't work either.

I have no idea how to solve this problem. Can anyone help? Thanks.

1 Answer

Hi!

Try replacing these two blocks:

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:5000;
    }

    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://127.0.0.1:5000/socket.io;
    }

with just this:

    location / {
        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://127.0.0.1:5000;
    }

Don't forget to restart nginx so that the changes take effect. Does that work? If not, can you post the full nginx error that you get?

Have another answer? Share your knowledge.