nginx with flask

How to Use NGINX with Flask

NGINX is a popular web server that is also used as reverse proxy and load balancer. Flask is a popular framework to build & run python applications. Sometimes you may need to deploy flask with NGINX or host flask app on NGINX. In this article, we will look at how to use NGINX with Flask. We will configure NGINX as reverse proxy for Flask application that will be running within Gunicorn server.


How to Use NGINX with Flask

Here are the steps to use NGINX as reverse proxy for Flask app. Since Flask is only a framework, you will need a python application interface such as uwsgi or gunicorn to run the Flask application. Flask will run at a port other than http port 80 since NGINX will be running on it. We will configure NGINX with Flask such that all requests sent to NGINX are forwarded to Gunicorn (Flask).

Also read : How to Use NGINX Reverse Proxy with Django


1. Set up Flask App

First we will create Flask App and server environment to run the application. Open terminal and run the following commands to update Ubuntu, install flask and pip.

$ sudo apt-get update
$ sudo apt-get upgrade -y

python 2.x

$ sudo apt-get install python-pip
$ sudo apt-get install python-flask

python 3.x

$ sudo apt-get install python-pip3
$ sudo apt-get install python3-flask

Create directory to store your flask application

$ sudo mkdir /var/www/application
$ cd /var/www/application

Create a main.py file to hold the application.

$ sudo vi main.py

Add the following lines to set up website home page

from flask import Flask
 
app = Flask(__name__)
@app.route("/")
def home():
    return "<h1>Hello World</h1>"

Create wsgi.py page to run the application.

$ sudo vi wsgi.py

Add the following lines to import the app

from main import app
 
if __name__ == "__main__":
    app.run(debug=True)

Change folder ownership & permission to www-data to allow NGINX to easily work with these files.

$ sudo chown -R www-data:www-data /var/www/application/

Run the app with the following command

$ flask run

Open browser and go to http://localhost:5000 to access the app. You will be able to see “Hello World” response message displayed. Press Ctrl+C to stop flask app.

Also read : How to Convert Int to String in Python


2. Install & Setup Gunicorn

Run the following command to install Gunicorn.

python 2.x

$ sudo pip install gunicorn

python 3.x

$ sudo pip3 install gunicorn

Create gunicorn configuration file for

$ sudo vi /etc/systemd/system/gunicorn.service

Add the following lines to it.

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/application/

ExecStart=/usr/bin/gunicorn --access-logfile - --workers 3 --bind
unix:/var/www/application.sock wsgi:app

[Install]
WantedBy=multi-user.target

Let us look at each of the sections above

  • Unit – specifies metadata, dependencies and service name. Also tells init system to start service only after network target.
  • Service – describes the file paths, users and owners who have the permissions to run the service. We give permission to ubuntu user and give ownership to www-data, the default owner for NGINX/Apache web service files.
  • Install – tells systemd to start the service at boot after multi-user system is up & running.

Enable and start gunicorn

$ sudo systemctl start gunicorn
$ sudo systemctl enable gunicorn

Also read : How to Count Unique IPs and Requests Per IP in NGINX


3. Configure NGINX

Next, we configure NGINX to work with Flask via Gunicorn.

Copy default server file to create one for your domain. Replace your_domain.com with your domain below.

$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/your_domain.com.conf
$ sudo vi /etc/nginx/sites-available/your_domain.com.conf

Copy the following lines into this file. Replace your_domain.com with your domain

server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/application/application.sock;
    }
}

As you can see above all requests such as the one sent to / are forwarded to gunicorn with the help of proxy_pass function.

Also read : How to Configure Multiple Website in NGINX Server


Next, we enable this site by adding a symbolic link to /etc/nginx/sites-enabled which nginx read during startup.

sudo ln -s /etc/nginx/sites-available/your_domain.com /etc/nginx/sites-enabled/

Test NGINX configuration to ensure everything is all right.

$ sudo nginx -t

If you don’t any error messages, restart NGINX server to apply changes.

$ sudo systemctl restart nginx


4. Test your website

Just open your browser and go to http://your_domain.com and you should be able to see your Flask project’s home page.

Also read : How to Use NGINX Reverse Proxy with NodeJS


Leave a Reply

Your email address will not be published. Required fields are marked *