Deploy flask app with nginx using gunicorn and supervisor
In this blog, I will discuss how to set a Flask app up on an Ubuntu server.
This is a walkthrough that illustrates how to deploy a Flask application using an easy technique.
We will be using the following technologies:
Flask: Server backend
Nginx: Reverse proxy
Gunicorn: Deploy flask app
Supervisor: Monitor and control gunicorn process
Install required packages
$ sudo apt-get install nginx supervisor python-pip python-virtualenv
Create a virtual environment
If you are not using python virtual environments, you should! Virtual environments create isolated python environments. This allows to run multiple versions of library on the same machine.
Let’s create a virtual environment.
$ virtualenv .env
And activate it.
$ source .env/bin/activate
Create a Flask app
Install Flask and other dependencies.
$ pip install Flask
$ pip install -r requirements.txt
Write the code for Flask app.
You can run the Flask app simply by running the following command:
$ python app.py
But it is not safe to use the Flask development server for a production environment. So, you can use Gunicorn to server our python code.
Setup Gunicorn
Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX.
Install gunicorn.
$ pip install gunicorn
Let’s start a Gunicorn process to serve your Flask app.
$ gunicorn app:app -b localhost:8000 &
You can make Gunicorn process listen to any open port.
This will set your Gunicorn process off running in the background, which will work fine for your purposes here. An improvement that can made here is to run Gunicorn via Supervisor.
Use supervisor
Supervisor allows to monitor and control a number of processes on UNIX-like operating systems.
Supervisor will look after the Gunicorn process and make sure that they are restarted if anything goes wrong, or to ensure the processes are started at boot time.
Create a supervisor file in /etc/supervisor/conf.d/ and configure it according to your requirements.
To enable the configuration, run the following commands:
$ sudo supervisorctl reread
$ sudo service supervisor restart
This should start a new process. To check the status of all monitored apps, use the following command:
$ sudo supervisorctl status
Setup nginx
Nginx is an HTTP and reverse proxy server.
Let’s define a server block for our flask app.
$ sudo vim /etc/nginx/conf.d/virtual.conf
Paste the following configuration:
Proxy pass directive must be the same port on which the gunicorn process is listening.
Restart the nginx web server.
$ sudo nginx -t
$ sudo service nginx restart
Now, if you visit your public DNS name in a web browser, you should see Hello World page.
Congratulations! Now the Flask app is successfully deployed using a configured nginx, gunicorn and supervisor.
There are some other ways to deploy flask app which are as follows:
- Using uwsgi
- Using gevent
- Using twisted web