billysoftacademy.com

Learn how to Install Flask with Nginx and Gunicorn on Ubuntu 22.04

Introduction

Flask, a lightweight Python web framework, empowers developers to construct web applications with ease. It offers the necessary tools and flexibility to build applications quickly without being overly restrictive. When combined with Nginx, a high-performance web server, Flask applications can achieve optimal performance and scalability. In this tutorial you will learn how to install Flask with NGINX and Gunicorn on Linux Ubuntu 22.04 LTS

Requirements

The following is a list of items needed to complete the installation successfully:
1) A desktop or laptop with 4GB RAM, a dual core processor and 50GB of free disk space
2) An SSH client such as Putty or the Terminal app for macOS
3) Linux Ubuntu 22.04 LTS or any newer version
4) For cloud deployment, a domain and a public static IP may be needed
5) A stable internet connection

Overview

The following is an overview of the steps covered in this tutorial: 1) Downloading and installing dependancies. 2) Creating a Flask app. 3) Setting up a service for the Flask app. 4) Configuring NGINX as a reverse proxy for the Flask app. 5) Conclusion and next steps.

Step 1: Downloading and installing dependancies.

Before you begin, it’s important to ensure that you have installed Python and other necessary dependencies on your server. Here are the steps to follow:

1. Install Python and Python virtual environment by running the command below:

   apt update -y
   apt install python3-pip python3-venv -y

2. Change the default Python version by running the following command:

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

3. Verify the Python version using the following command:

   python --version

You should see the following output:

   Python 3.10.12

4. Finally, install Nginx and Supervisor with the following command:

   apt install nginx supervisor -y

Step 2: Creating a Flask Application

To create your application, follow these steps:

1. Create your application directory: `mkdir -p /var/www/myapp`
2. Change the ownership of the application directory: `chown -R www-data:www-data /var/www/myapp`
3. Navigate to your application directory and create a Python virtual environment: `cd /var/www/myapp` followed by `python -m venv myenv`
4. Activate the Python virtual environment: `source myenv/bin/activate`
5. Install Flask and Gunicorn: `pip install flask gunicorn`
6. Create an application file: `nano app.py`
7. Add the following code to the app.py file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, World!"

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

8. Save and close the app.py file, and then run the application using the following command:

gunicorn -w 4 -b 0.0.0.0:8000 app:app

9. Verify that the application is running by checking the output:

[2024-02-15 03:29:22 +0000] [1] [INFO] Starting gunicorn 21.2.0
[2024-02-15 03:29:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (114941)
[2024-02-15 03:29:22 +0000] [1] [INFO] Using worker: sync
[2024-02-15 03:29:22 +0000] [2] [INFO] Booting worker with pid: 114942
[2024-02-15 03:29:22 +0000] [3] [INFO] Booting worker with pid: 114943
[2024-02-15 03:29:22 +0000] [4] [INFO] Booting worker with pid: 114944
[2024-02-15 03:29:22 +0000] [5] [INFO] Booting worker with pid: 114945

10. To stop the application, press `CTRL+C`.
11. Create a WSGI for your application: `nano wsgi.py`
12. Add the following code to the wsgi.py file:

from app import app

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

13. Verify your application using WSGI:

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

14. Open your web browser and access your Flask app using the URL http://your-server-ip:8000.
15. To stop the application, press `CTRL+C`.

Step 3: Setting up a service for the Flask app.

To manage your Flask app via systemd, you need to create a supervisor configuration file. Here’s how to do it:
1. Open the file using the following command: nano /etc/supervisor/conf.d/myapp.conf
2. Add the following configurations to the 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=www-data
group=www-data
autostart=true
autorestart=true
stdout_logfile=/var/www/myapp/myapp.log
stderr_logfile=/var/www/myapp/error.log

3. Save and close the file.
4. Restart the Supervisor to apply the changes: systemctl restart supervisor.
5. To check the status of the Supervisor, run the following command: systemctl status supervisor.

You should see an output similar to the one below:

● supervisor.service - Supervisor process control system for UNIX
     Loaded: loaded (/lib/systemd/system/supervisor.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2024-02-15 03:32:31 UTC; 5s ago
       Docs: http://supervisord.org
   Main PID: 115115 (supervisord)
      Tasks: 5 (limit: 4579)
     Memory: 67.8M
        CPU: 711ms
     CGroup: /system.slice/supervisor.service
             ├─115115 /usr/bin/python3 /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
             ├─115118 /var/www/myapp/myenv/bin/python /var/www/myapp/myenv/bin/gunicorn -w 3 --bind unix:/var/www/myapp/ipc.sock wsgi:app
             ├─115119 /var/www/myapp/myenv/bin/python /var/www/myapp/myenv/bin/gunicorn -w 3 --bind unix:/var/www/myapp/ipc.sock wsgi:app
             ├─115120 /var/www/myapp/myenv/bin/python /var/www/myapp/myenv/bin/gunicorn -w 3 --bind unix:/var/www/myapp/ipc.sock wsgi:app
             └─115121 /var/www/myapp/myenv/bin/python /var/www/myapp/myenv/bin/gunicorn -w 3 --bind unix:/var/www/myapp/ipc.sock wsgi:app

Step 4: Configuring NGINX as a reverse proxy for the Flask app.

To set up an Nginx virtual server block for your Flask app, follow these steps:

1. Open the terminal and type “nano /etc/nginx/conf.d/myapp.conf” to create a new configuration file.

2. Copy and paste the following configurations into the file:

    server {
        listen 80;
        server_name example.com;

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

3. Save and close the file then restart the Nginx service by typing `systemctl restart nginx` in the terminal.

5. Finally, open your web browser and access your Flask app using the URL http://example.com.

Conclusion

By following this tutorial, you’ve successfully deployed a Flask application on Ubuntu 22.04 LTS using Nginx and Gunicorn. This powerful combination offers several benefits:

1. Improved Performance: Nginx acts as a reverse proxy, handling static content requests and offloading dynamic content processing to Gunicorn. This improves overall application responsiveness.

2. Scalability: Gunicorn allows you to easily scale your application by adding more worker processes. This ensures smooth operation even under high traffic loads.

3. Security: Nginx provides an additional layer of security by filtering requests before they reach your Flask application.

Remember to adapt the configurations to your specific needs, such as using your actual domain name instead of “example.com”.

Here are some next steps to consider:

1. Explore advanced Flask features for building more complex web applications.
2. Implement additional security measures like authentication and authorization for your app.
3. Learn how to monitor and troubleshoot your deployed application for optimal performance.

Congratulations on deploying your first Flask application!

Scroll to Top