Nginx Reverse Proxy Flask-restx Swagger Configuration

Few days ago, I was setting up nginx reverse proxy for my project. I was using gunicorn for the HTTP Server with flask-restx for the web framework. Actually this was the first time for me using this combination. I usually use uwsgi for the deployment.

It was quite simple to deploy flask with gunicorn. You can use port binding.

gunicorn --bind 0.0.0.0:9999 app:app

Or you can use unix sock.

gunicorn --workers 2 --bind unix:sockname.sock -m 644 app:app

I was using the second option, using unix sock, so this was the configuration I use for nginx reverse proxy.

location / {
    root /path/to/project/;
    proxy_pass http://unix:/path/to/unix.sock;
}

After finishing the configuration and testing the service, although I could access all function of the web service, I found out a problem when accessing the documentation.

The documentation page was still getting the swagger data from localhost, because we only set the reverse proxy option to the project.

Then, I realized that we have to config the proxy header also inside the configuration, so the documentation page will request the data from the domain we setup, instead of localhost. So this is my nginx configuration now.

location / {
    root /path/to/project/;
    proxy_pass http://unix:/path/to/unix.sock;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
}

We use proxy_set_header Host $host to set the proxy request to same name as the server_name directive, so it will request the domain name, not the original host where we deploy the service.

I also use proxy_set_header X-Forwarded-Proto $scheme because I am using SSL for the domain. If you don’t use that option, the request will be blocked, because of mixed content issue (domain with SSL request to non SSL domain).

Then, after adding that two lines and restarting the service, we can load the data from the swagger 😁

Well, maybe this is all I can share. If you found any problem when using gunicorn and flask restx with nginx as reverse proxy, you can try this solution. Thank you!

You may also like

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *