Gunicorn and Nginx in a Nutshell
When hosting a Python web app in production you can’t get around using a WSGI server and a web server.
Gunicorn and Nginx are solid and popular options - but what are those two apps? Why do people run both, and not just one of them?
Nginx and Gunicorn work together
Nginx is where requests from the internet arrive first. It can handle them very quickly, and is usually configured to only let those requests through, which really need to arrive at your web application.
Gunicorn translates requests which it gets from Nginx into a format which your web application can handle, and makes sure that your code is executed when needed.
They make a great team! Each can do something, which the other can’t. Let’s look at their strengths in detail, and how they complete each other.
Nginx is a web server and reverse proxy. It’s highly optimized for all the things a web server needs to do. Here are a few things it’s great at:
- Take care of domain name routing (decides where requests should go, or if an error response is in order)
- Serve static files
- Handle lots of requests coming in at once
- Handle slow clients
- Forwards requests which need to be dynamic to Gunicorn
- Terminate SSL (https happens here)
- Save computing resources (CPU and memory) compared to your Python code
- And a lot more, if you configure it to do so (load balancing, caching, …)
Things Nginx can’t do for you:
- Running Python web applications for you
- Translate requests to WSGI
Once Nginx decides, that a particular request should be passed on to Gunicorn (due to the rules you configured it with), it’s Gunicorn’s time to shine.
Gunicorn is really great at what it does! It’s highly optimized and has a lot of convenient features. Mostly, its jobs consist of:
- Running a pool of worker processes/threads (executing your code!)
- Translates requests coming in from Nginx to be WSGI compatible
- Translate the WSGI responses of your app into proper http responses
- Actually calls your Python code when a request comes in
- Gunicorn can talk to many different web servers
What Gunicorn can’t do for you:
- Not prepared to be front-facing: easy to DOS and overwhelm
- Can’t terminate SSL (no https handling)
- Not as blazing fast as a hyper-optimized webserver
Gunicorn is just one of many valid WSGI servers. Your app doesn’t care which one you use, and Nginx doesn’t care either. But Gunicorn is a mighty- fine choice!
There’s more to production deployments
For a Python web application deployment, you need more than an application server and a web server. If you’re interested in an overview, make sure to subscribe to the newsletter below, and I’ll let you know once the article is published.
I hope this quick comparison of Nginx and Gunicorn was helpful to you! Have fun deploying your Python web application ;)