Green Unicorn (Gunicorn)

Green Unicorn, commonly shortened to "Gunicorn", is a Web Server Gateway Interface (WSGI) server implementation that is commonly used to run Python web applications.

Official Green Unicorn (Gunicorn) logo.

Why is Gunicorn important?

Gunicorn is one of many WSGI server implementations, but it's particularly important because it is a stable, commonly-used part of web app deployments that's powered some of the largest Python-powered web applications in the world, such as Instagram.

Gunicorn implements the PEP3333 WSGI server standard specification so that it can run Python web applications that implement the application interface. For example, if you write a web application with a web framework such as Django, Flask or Bottle, then your application implements the WSGI specification.

Gunicorn is an implementation of the WSGI servers concept. Learn how these pieces fit together in the deployment chapter or view the table of contents for all topics.

How does Gunicorn know how to run my web app?

Gunicorn knows how to run a web application based on the hook between the WSGI server and the WSGI-compliant web app.

Here is an example of a typical Django web application and how it is run by Gunicorn. We'll use the django_defaults as an example Django project. Within the django_defaults project subdirectory, there is a short wsgi.py file with the following contents:

"""
WSGI config for django_defaults project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_defaults.settings")

application = get_wsgi_application()

That wsgi.py file was generated by the django-admin.py startproject command when the Django project was first created. Django exposes an application variable via that wsgi.py file so that a WSGI server can use application as a hook for running the web app. Here's how the situation looks visually:

Gunicorn WSGI server invoking a Django WSGI application.

What's a "pre-fork" worker model?

Gunicorn is based on a pre-fork worker model, compared to a worker model architecture. The pre-work worker model means that a master thread spins up workers to handle requests but otherwise does not control how those workers perform the request handling. Each worker is independent of the controller.

Gunicorn resources

What else do you want to learn about deployments?

What runs a Python application execute on the server?

What is Docker and how does it fit with Python deployments?

Show me options for bare metal and virtualized servers.


Matt Makai 2012-2022