Gunicorn
Learn how to set up Gunicorn to run our web application.
What is Gunicorn?
Gunicorn is a very popular WSGI container for Flask applications. As our Flask application gets up and running using Gunicorn, it performs the role of an application server and responds to requests for dynamic content.
Let’s switch back over to our Flask REST application and see how we can setup Gunicorn.
Installing Gunicorn
Conveniently for us, Gunicorn is PIP installable. (Note that this is for Linux only):
pip install gunicorn
Starting a server with Gunicorn
In its simplest form, Gunicorn can start serving our Flask application from the command line with no options. In a terminal window, we’ll run this command:
gunicorn appserver:app
This will start the Gunicorn application server, which should now be listening for requests on its default port 8000
. We can run our SPA web application below to open it in our web browser.
Once the application is up and running, we can also try this command in the terminal to ensure that the Gunicorn application server is running on port 8000
.
curl http://localhost:8000/api/books
In return, there is a JSON response showing the book records from the Books table in SQLite.
Explanation
The command-line argument passed to the Gunicorn server is the Python module, which is the entry point for our Flask application, and the module-level variable that holds the main Flask object. The Flask object has the necessary API interface that allows Gunicorn to communicate with our Flask application using WSGI.
Other configuration options in Gunicorn
Gunicorn has many configuration options that can be used to tune the service, including specifying the number of worker threads used to service requests, timeout options, logging options, and changing the port that it listens on. For the full list of configuration options available and how to use them, documentation is available on the Gunicorn project website.
Now, these are the steps to follow to test its working:
- Click on the terminal below to open it.
- Run
gunicorn appserver:app
, and the server will start at port8000
. - Open another terminal and run the
curl http://localhost:8000/api/books
command to get the JSON response.
Get hands-on with 1400+ tech skills courses.