Flask with Gunicorn
Gunicorn is used for production Flask deployments because it’s a robust, pre-fork worker model WSGI (Web Server Gateway Interface) server that efficiently handles multiple requests concurrently. Unlike Flask’s built-in development server, Gunicorn is designed for performance, scalability, and reliability in real-world, multi-user environments.
Here we have a simple Flask app that runs on development mode
Before we start running it with Gunicorn, lets contain this app inside a virtual environment called flaskenv
1
2
python3 -m venv ~/evn/flaskenv
source ~/evn/flaskenv/bin/activate
Next we install Flask and Gunicorn inside the venv
Then create a new file named “wsgi.py”
1
2
3
4
from main import app
if __name__ == '__main__'
app.run()
Now we can run the gunicorn on port 5000, spawning 4 workers and calling the wsgi.py file
1
gunicorn --bind 0.0.0.0:5000 --workers 4 wsgi:app
And the flask app is up and running using gunicorn
Running as Service
Now we want to run Gunicorm/Flask as a service, create a new service file on /etc/systemd/system/flask.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=Gunicorn for flaskapp
After=network.target
[Service]
User=helena
Group=helena
WorkingDirectory=/home/helena/flask
Environment="PATH=/home/helena/env/flaskenv/bin"
ExecStart=/home/helena/env/flaskenv/bin/gunicorn --workers 4 --bind 0.0.0.0:5000 -m 007 wsgi:app
Restart=always
[Install]
WantedBy=multi-user.target
Then we can start the service
1
2
3
sudo systemctl daemon-reload
sudo systemctl start flask
sudo systemctl enable flask
Nginx Reverse Proxy
Lastly we add an Nginx Reverse Proxy to serve traffic from clients, follow this NGINX post for detailed steps.
Here we create a new reverse-proxy file on sites-available directory
Then activate the file by creating a symlink sites-enabled directory
After reloading nginx, we should now serve the flask app on port 80 through nginx