How To Run Python 3 Flask App with Gunicorn – Step by Step Guide

This article will be about how to set up the Python 3 application using Flask framework on Ubuntu and serve using Gunicorn server .
Our first step will be to install all of the pieces that we need from the repositories. We will install pip3, the Python package manager, in order to install and manage our Python components. We will also get the Python development files needed to build some of the Gunicorn components.
1 2 3 |
sudo apt-get update sudo apt-get install python3 python3-wheel sudo apt install python3-pip |
Next, we’ll set up a virtual environment in order to isolate our Flask application from the other Python files on the system.
1 |
sudo pip3 install virtualenv |
Now, we can make a parent directory for our Flask project. Move into the directory after you create it:
1 2 |
mkdir ~/yourprojectname cd ~/yourprojectname |
1 |
virtualenv yourprojectname |
Before we install applications within the virtual environment, we need to activate it. You can do so by typing:
1 |
source yourprojectname/bin/activate |
Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (yourprojectname) YUOR_HOST_PATH:~/yourprojectname
$.
Type the following commands to get Flask and Gunicorn components:
1 |
pip3 install gunicorn flask |
While your application might be more complex, we’ll create our Flask app in a single file, which we will call yourprojectname.py:
1 |
vim ~/yourprojectname/yourprojectname.py |
Past the below code in your yourprojectname.py file > save > – :wq!
1 2 3 4 5 6 7 8 9 |
from flask import Flask application = Flask(__name__) @application.route("/") def hello(): return "<h1 style='color:blue'>This is first Flask Gunicorn Application!</h1>" if __name__ == "__main__": application.run(host='0.0.0.0') |
You can test your Flask app by typing:
1 |
python3 yourprojectname.py |
Visit your server’s domain name or IP address followed by the port number specified in the terminal output (most likely :5000
) in your web browser.
Next, we’ll create a file that will serve as the entry point for our application. This will tell our Gunicorn server how to interact with the application.
We will call the file wsgi.py
:
1 |
vim ~/yourprojectname/wsgi.py |
Past the below code in your wsgi.py file > save > – :wq!
1 2 3 4 |
from yourprojectname import application if __name__ == "__main__": application.run() |
1 2 |
cd ~/yourprojectname gunicorn --bind 0.0.0.0:8000 wsgi |
If you visit your server’s domain name or IP address with :8000 appended to the end in your web browser, you should see a page.