Nginx and Gunicorn

Recently I learned to deploy Django project on Elastic Beanstalk. My original thought is I get a VM and then run the app locally. However, the fact is that the way has not gone through security audits or performance tests. This article will introduce Nginx and Gunicorn in EC2 instance.

Nginx

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.

Things it is great at

  • Take care of domain name routing (decides where requests should go)

  • Handle lots of requests coming in at once

  • Serve static files from disk (e.g. css and js files)

  • load balancing and caching..

  • Forward requests which need to be dynamic to Gunicorn

  • Terminate SSL (i.e. decrypt https traffic to use the host header information)

  • Save computing resources (CPU and memory) compared to your Python code

Things it can not do

  • Running Python web applications for you
  • Translate requests into WSGI

Gunicorn

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. Gunicorn is one of the examples for a WSGI server.

Things it is great at

  • Running a pool of worker processes/threads (executing your code!)
  • Translate 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 different web servers

Things it can not do

  • Not prepared to be front-facing: easy to DOS and overwhelm
  • Can’t terminate SSL (no https handling)
  • Do the job of a webserver like Nginx

EC2 instance with EB

Back to the Dajngo project I am working on, the EC2 instances in EB are using Nginx and Gunicorn. The whole structure is showing in the picture. Basically, when new HTTPs requests come, load balancer does two things. Firstly, it terminates SSL by https handling. Secondly, it forwards the request to an appropriate instance. In Gunicorn, each work processor will run the django code, and the master workers will manage the list of running workers by listening for some signals. These workers can access to external database. I mean EB also support to use integrated DB instance, but we use the external DB in the project.

Reference: Gunicorn and Nginx in a Nutshell

Thank you for reading!