Search code examples
socketsnginxflaskpermissionsuwsgi

Nginx and uWSGI: Proper permissions setup for 502 Bad Gateway issue


In uWSGI, if I change my socket location to /tmp/api, the website renders. However, if I change the socket address to /srv/www/api/, I get a 502 gateway error.

I believe this is due to a permissions issue regarding the /srv folder and the Nginx/uWSGI users.

In /var/log/nginx/error.log:

*1 connect() to unix:///srv/www/api/app.sock failed (2: No such file or directory) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: api.example.com, request: "GET / HTTP/2.0", upstream: "uwsgi://unix:///srv/www/api/app.sock:", host: "api.example.com"

The Flask project code is located in /srv/www/api. I am logged in as username user.

Permissions:

$ ll -ld /srv/www/api/
drwxrwxr-x 4 www-data www-data 4096 Jun 28 20:52 /srv/www/api/
$ ll -ld /srv/www
drwxrwxr-x 4 username www-data 4096 Jun 27 21:41 /srv/www
$ ll -ld /srv
drwxrwxr-x 4 username username 4096 Jun 27 21:37 /srv
$ ll -ld /tmp
drwxrwxrwt 9 root root 4096 Jun 28 23:05 /tmp

User groups:

$ groups username
username : username sudo dev
$ groups www-data
www-data : www-data dev
$ grep 'dev' /etc/group
dev:x:1001:username,www-data

I have several users setup to be in the dev group. The goal is so that users in the group would be able to read and write to /srv without also being in the root group (is this a bad practice?).

/srv/www/api/app.ini:

[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = /tmp/app.sock
chmod-socket = 660
vacuum = true

die-on-term = true

/etc/nginx/sites/sites-available/api.example.com (location section):

location / {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/app.sock;
}

Is there a way to fix my permissions setup so that:

  1. The socket would be able to be created in that folder
  2. Users in the dev group without sudo would also be able to read and write the /srv folder and subdirectories

Solution

  • I figured this out. I ended up setting the owners for my folder to:

    chown -R username:www-data /srv/www/api
    

    I also made sure to restart the systemctl service after each change. I don't remember doing that earlier so that was very likely the reason why nothing was working even after all the changes made. I only restarted Nginx and not the service itself -- the one responsible for creating the sockets.

    To restart the systemctl service:

    sudo systemctl restart <service_name>