3

I have a Flask app running in a python virtual environment and working with uWSGI and Nginx.

I want to use systemd socket activation to manage the startup of the app.

here is the relevant configurations:

uwsgi-flask.service

[Unit]
Description=a uWSGI app
After=syslog.target

[Service]
Type=notify
User=www-data
Group=www-data
WorkingDirectory=/home/www-data/my-app
ExecStart=/bin/bash -c "source venv/bin/activate && uwsgi \
          --ini flask-uwsgi.ini \
          --socket /dev/shm/flask.sock"
Restart=always
KillSignal=SIGQUIT
StandardError=syslog
NotifyAccess=all

uwsgi-flask.socket

[Unit]
Description=Socket for uWSGI app

[Socket]
ListenStream=/dev/shm/flask.sock
SocketUser=www-data
SocketGroup=www-data
SocketMode=0660

[Install]
WantedBy=sockets.target

nginx.conf

server {
    listen  80;
    server_name localhost;

    location / {
        root /home/www-data/my-app/public;
        try_files $uri @flask;
    }

    location @flask {
        uwsgi_pass   unix:/dev/shm/flask.sock;
        include      uwsgi_params;
    }
}

When I started the systemd socket and make requests:

systemctl start uwsgi-flask.socket

The first request always gets a 504 response like below:

504 Gateway Time-out

But the second and subsequent requests are normal. As if the unix socket was not ready when the first request was made.

The weird thing is that if I start the uwsgi-flask.service directly there is no problem:

systemctl start uwsgi-flask.service

What could be the reason for the above problem?

Runbing
  • 31
  • 4
  • I'd concentrate on this man page: https://www.freedesktop.org/software/systemd/man/systemd.socket.html at the paragraph beginning with "Note that the daemon software configured for socket activation with socket units needs to be able to accept sockets from systemd". – A.B Mar 13 '22 at 23:05
  • @A.B Thanks for your advice. I put the directive `StandardInput=socket` into the service file according to the information you provided, problem solved! But I'm not very familiar with systemd and don't quite understand what role `StandardInput` plays here. – Runbing Mar 14 '22 at 07:05
  • I just found out that the option `--socket /dev/shm/flask.sock` is not required if the directive `StandardInput=socket` is used. It looks like the original problem was not resolved. – Runbing Mar 14 '22 at 09:44
  • Maybe related to https://stackoverflow.com/a/45450506/757777 ? Quote: "_The reason the socket activation only works the first time is because uwsgi overwrites the socket file created by the systemd socket._" – Erik Sjölund Aug 03 '22 at 20:07

0 Answers0