Search code examples
pythonnginxflaskuwsgiwebfaction

How do I load 2 flask apps to serve 2 subdomains for nginx/uwsgi using unix sockets?


I am following this uwsgi guide to setting up nginx/uwsgi to have 1 flask app run the "www" subdomain and another flask app to run the "api" subdomain. My nginx.conf:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    access_log  /path/to/access_nginx.log combined;
    error_log   /path/to/error_nginx.log  crit;

    include mime.types;
    sendfile on;

    server {
    server_name   api.example.com;
        listen 14265;

        location / {
        include uwsgi_params;
        uwsgi_param UWSGI_SCRIPT wsgi_api;
        uwsgi_pass unix:///path/to/api.sock;
        }
    }

    server {
    server_name   www.example.com;
        listen 14265;

        location / {
            include uwsgi_params;
            uwsgi_param UWSGI_SCRIPT wsgi;
            uwsgi_pass unix:///path/to/wsgi.sock;
        }
    }
}

For starting uwsgi, I do:

#!/bin/bash
APPNAME=nginx
# Start uwsgi
${HOME}/webapps/${APPNAME}/bin/uwsgi \
  --uwsgi-socket "${HOME}/webapps/${APPNAME}/wsgi.sock" \
  --master \
  --workers 1 \
  --max-requests 10000 \
  --harakiri 60 \
  --daemonize ${HOME}/webapps/${APPNAME}/uwsgi.log \
  --pidfile ${HOME}/webapps/${APPNAME}/uwsgi.pid \
  --vacuum \
  --python-path ${HOME}/webapps/${APPNAME}

# Start nginx
${HOME}/webapps/${APPNAME}/bin/nginx

When I visit www.example.com it works as expected. However, I get a 502 error for api.example.com. To fix the 502 error I can change api.sock to wsgi.sock in my nginx.conf but it will give me the page for www.example.com when I visit api.example.com (even though wsgi.py and wsgi_api.py are different).

EDIT: The examples I have found for setting up multiple subdomains on nginx/uwsgi (including the one I linked to) all show how to do subdomains with static sites. I cannot find one that shows how to do it with unix sockets.


Solution

  • I've also noticed that only wsgi.sock gets created

    That is the answer of your question, if you didn't get api.sock nginx will not be able to pass query to it. So you will get 502. You should start uwsgi for each of your apps:

    #!/bin/bash
    
    # Start uwsgi 
    for APPNAME in "app_1" "app_2"
    do
        uwsgi \
          --uwsgi-socket "${HOME}/webapps/${APPNAME}/wsgi.sock" \
          --master \
          --workers 1 \
          --max-requests 10000 \
          --harakiri 60 \
          --daemonize ${HOME}/webapps/${APPNAME}/uwsgi.log \
          --pidfile ${HOME}/webapps/${APPNAME}/uwsgi.pid \
          --vacuum \
          --python-path ${HOME}/webapps/${APPNAME}
    done