How to Install Flask with Nginx and Gunicorn on Ubuntu 22.04

Flask is a microframework written in Python for developing modern web applications and API (Application Programming Interface). It's based on the Werkzeug toolkit and Jinja2 template. Instead of using complex architecture, Flask is a small web framework that easy-to-extent the core and easy to learn because Flask has less code. Flask doesn't include the ORM, but still has cool features like URL routing and template engine.

Gunicorn or "Green Unicorn" is a WSGI HTTP Server with pre-fork worker mode. Its ported from the Ruby's Unicorn project. Gunicorn can be paired with several web frameworks, it's lightweight on server resources and fasts. Gunicorn stands between your application and the web server, so you can pair the Gunicorn with a web server such as Nginx and Apache2.

In this post, we will show you how to install and configure the Python Flask Web Framework with Gunicorn and Nginx on the Ubuntu 22.04 system. This tutorial also covers how to set up Python Flask with Gunicorn and Supervisord.

Prerequisites

For this guide, you will need the following prerequisites:

  • An Ubuntu 22.04 system - You can use Ubuntu 22.04 Desktop or Server.
  • A root user - or non-root user.

Setting Up New User

In the first step, you will be setting up a new user for the development environment Python Flask web framework. You can skip this step if you already have a non-root user with root/sudo privileges. This user will be used for running the Python Flask application.

In this example, you will be creating a new user with the name "james". Run the following command to create a new user "james" and set up the password for the user "james". Be sure to use a strong password.

sudo useradd -m -s /bin/bash james
sudo passwd james

Next, add the user "james" to the "sudo" group using the below command. This will allows the new user "james" to run the "sudo su" command and get the root administrator privileges. which is needed for installing packages and setting up system configurations.

sudo usermod -aG sudo james

Lastly, check and verify the new user by logging in as the user "james" and running the "sudo su" command t get the root privileges. Input the password for the user "james", and you will get the root shell. The current shell will be changed from "[email protected]" to "[email protected]".

su - james
sudo su

setup new user

Now press "Ctrl+d" or type "exit" to go back to the non-root user "james".

Installing Packages Dependencies

Now you will be installing some package dependencies for Python Flask installation, this includes the "python3-pip" and "python3-venv". In the end, you will also be installing the Nginx web server and supervisor.

Before start installing packages, run the apt command below to update and refresh your package repository.

sudo apt update

Now install python3-pip and python3-venv using the following command. The python3-pip will be used as the package manager for Python packages, and the python3-venv will be used for creating a virtual environment for the Flask application development.

sudo apt install python3-pip python3-venv

Input Y to confirm the installation and press ENTER to continue. The installation will begin.

install pip and venv

After installation is completed, run the following command to set up the default Python on your Ubuntu system.

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

Now verify the version of Python and Pip, and also check the Python venv module by running the following commands. In the following example, you will be installing the Python Flask web framework with Python 3.10.

python --version
pip --version
python -m venv -h

setup default python

Next, run the following apt command to install the Nginx web server and supervisor package. The Nginx web server will be used as the default web server for the Python Flask web framework, and the supervisor will be used for controlling the Flask application, such as starting and stopping the Flask process.

sudo apt install nginx supervisor

Input Y to confirm the installation and press ENTER to continue. Wait for package installation to complete.

install nginx supervisor

Setting Up Development Environment

In this section, you will be creating a new Python virtual environment that will be used as the development environment of the Python Flask web framework.

Run the following command to create a new project directory "/var/www/myapp". This directory will be used as the main project directory for your FLask application.

sudo mkdir -p /var/www/myapp

Change the ownership of the new directory to the user "james" and change the permission to "755" using the below command.

sudo chown -R james:james /var/www/myapp
sudo chmod 755 /var/www/myapp

Move to the project directory "/var/www/myapp" and create a new Python virtual environment with the name "myenv" using the following command.

cd /var/www/myapp
python -m venv myenv

Lastly, activate the virtual environment "myenv" using the following command. When activated, your shell prompt will become like "(myenv) [email protected]".

source myenv/bin/activate

setup virtual environment

Installing Python Flask on the Virtual Environment

After setting up the virtual environment, you can run the pip command below to install the Python Flask and Gunicorn on your virtual environment. All of these packages will be installed from the PyPi Python repository.

pip install flask gunicorn

Now the installation will begin.

install flask gunicorn

Create First App Project with Flask

You now have installed the Python Flask web framework. Now you will be creating the first application using Flask.

Before creating the Flask project, be sure you are on the main project directory "/var/www/myapp" and the virtual environment "myenv" is activated.

Create a new file "myapp.py" using nano editor.

nano myapp.py

Now add the following Python script to the file.

# myapp.py
from flask import Flask, render_template  # importing the render_template function

app = Flask(__name__)
# route to index page
@app.route("/")
def hello():
    return render_template('index.html')

if __name__ == ' __main__':
    app.run(debug=True)

Save and close the file when you are done.

Next, create a new directory "templates" and create a new file "index.html" inside the "template" directory.

mkdir -p templates/
nano templates/index.html

Add the following HTML script to it.

<html>
    <body>
        <h1><center>Hello World!</center></h1>
    </body>
</html>

Save and close the file when you are done.

Lastly, run the script "myapp.py" to run your first Flask application.

python myapp.py

You will see that your Flask project is running on the default localhost with port 5000.

setup flask app

Open the new terminal shell of your Ubuntu machine and run the curl command below.

curl http://127.0.0.1:5000/

Now you can see the output of the index.html page in the following screenshot.

check glask app

To terminate the Flask application process, you can press the "Ctrl+c" button.

Setting Up Gunicorn

Gunicorn or "Green Unicorn" is a Python web server gateway interface for the HTTP server. It allows you to run a Python application as an HTTP process or using the sock file. Now you will be adding the Gunicorn to your Flask project.

Inside the Flask project directory, create a new file "wsgi.py" using nano editor.

nano wsgi.py

Add the following script to it.

# import myapp Flask application
from myapp import app

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

Save and close the file when you are done.

Next, run the following command to start and run your Flask project using Gunicorn. In this example, your Flask project will be running on the public IP address with port 8000.

gunicorn -w 4 --bind 0.0.0.0:8000 wsgi:app

setup guncorn flask

Open your web browser and input your Ubuntu system IP address with port 8000 (i.e http://192.168.5.28:8000/). And you should see the index page of your Flask project.

running flask with gunicorn

Now press "Ctrl+c" to terminate the Guncorn process.

Running Flask Application with Gunicorn and Supervisor

Now you have configured the Gunicorn for the FLask project. And is time to set up the Supervisor for the Flask web framework.

The supervisor is process management which allows you to control processes in one place. So instead of running the Flask application as a system service, you will be using Supervisor.

Create a new configuration file "/etc/supervisor/conf.d/myapp.conf" using nano editor.

sudo nano /etc/supervisor/conf.d/myapp.conf

Add the following configuration to the file. And be sure to change the details path of configuration and the user.

Using this configuration, you will be running your Flask project with Gunicorn, and instead of using the IP address for your application, you will be running the Flask project like a sock file.

[program:myapp] 
command=/bin/bash -c 'source /var/www/myapp/myenv/bin/activate; gunicorn -w 3 --bind unix:/var/www/myapp/ipc.sock wsgi:app'
directory=/var/www/myapp
user=james
group=www-data
autostart=true
autorestart=true
stdout_logfile=/var/www/myapp/myapp.log
stderr_logfile=/var/www/myapp/error.log

Save and close the file when you are done.

Now restart the supervisor service using the below command to apply new changes.

sudo systemctl restart supervisor

Lastly, check and verify the list of processes under the Supervisor using the following command. You should see the "myapp" process running.

sudo supervisorctl status

And if you check the supervisor service, you will see the supervisor service is active and running.

sudo systemctl status supervisor

checking supervisor

Setup Nginx as Reverse Proxy for Flask Application

Create a new virtual host configuration "/etc/nginx/sites-available/myapp.conf" using nano editor.

sudo nano /etc/nginx/sites-available/myapp.conf

Add the following configuration to the file. In this example, the Flask project will be running under the local domain "www.myapp.local". Also, you can see the "proxy_pass" option is pointed to the UNIX  sock file which is running under Gunicorn and Supervisor.

server {
    listen 80;
    server_name www.myapp.local;

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

Save and close the file when you are done.

Next, run the following command to activate the server block configuration "myapp.conf", then verify the Nginx configuration. If you don't get any error, you will see the output message such as "Syntax OK - test successful".

sudo ln -s /etc/nginx/sites-available/myapp.conf /etc/nginx/sites-enabled/
sudo nginx -t

After that, you can restart the Nginx service using the following command to apply new changes to the Nginx configuration.

sudo systemctl restart nginx

Now on your local machine, edit the /etc/hosts file using the nano editor.

sudo nano /etc/hosts

Define the Ubuntu machine IP address with the domain name "www.myapp.local" as below.

192.168.5.28 www.myapp.local

Save and close the file.

Now open up your web browser and input the Flask project domain name (i.e http://www.myapp.local) on the address bar. And you should get the index page of your Python Flask project.

setup nginx reverse proxy flask

Conclusion

Congratulation! You have successfully installed the Python Flask web framework with Gunicorn and Nginx on the Ubuntu 22.04 machine. You have also learned how to create the first Python Flask project, set up a Python virtual environment, and set up Supervisor process management for the Flask project.

Share this page:

Suggested articles

0 Comment(s)

Add comment