Saturday, November 16, 2024
Google search engine
HomeGuest BlogsInstall Flask with Gunicorn and Nginx on Rocky Linux 9

Install Flask with Gunicorn and Nginx on Rocky Linux 9

Welcome to this guide on how to install Flask with Gunicorn and Nginx on Rocky Linux 9. But before we dive into the nub of this matter, we need to know a few things.

Programming is a fundamental concept in the tech world today. It can be defined as writing code with a set of instructions that the computer can comprehend and execute. Python is one of the highly used programming languages. It is used for automation, machine learning, software & website development, data science, e.t.c

Flask is a python module that helps simplify web development with Python. It is preferred dues to its flexibility and extensibility offering innumerable built-in modules that make the development process very easy. Developers are able to develop a web application with a single file. Flask is based on the Jinja template engine that builds HTML pages using the familiar python concepts such as loops, lists, variables e.t.c.

Flask finds use in both domestic and enterprise firms. These companies include LinkedIn, Reddit, Uber, Netflix, Pinterest, Uber, Airbnb, Mailgun, PythonAnyWhere e.t.c. Flask is popularly used for:

  • Weather Applications
  • Feedback Form
  • Rest API App
  • Blogging applications
  • Deploying Machine Learning models
  • Portfolio Website
  • Social Network Web App

Let’s dive in!

#1. Install Required Components

There are several packages required for this setup. Some of them are provided in the EPEL repository which needs to be enabled with the command:

sudo dnf install epel-release

Once the EPEL repository has been enabled on Ropcky Linux 9, install the Python package manager(PIP), a compiler, and the Python development package required by Gunicorn.

sudo yum install python3-pip python3-devel gcc

The Nginx web server is also required for proxying:

sudo dnf install nginx -y

#2. Create a Python Environment

The Python environment is required here to cocoon our python project. First, install the virtualenv package using PIP.

sudo pip3 install virtualenv

Next, create the project directory:

sudo mkdir /sample_project && cd /sample_project
sudo chmod 777 /sample_project

Now create the project environment and activate it:

virtualenv projectenv
source projectenv/bin/activate

#3. Create the Flask Application

Before we create the application, we need both Flask and Gunicorn installed. This can be achieved by executing the command:

pip3 install gunicorn flask

Now create the application:

vim /sample_project/hello.py

Below is a simple application code, where Flask has been imported as a Python module to initialize a web application.

from flask import Flask
application = Flask(__name__)

@application.route("/")
def hello():
    return "<h1 style='color:chocolate'>Hello World! Flask is stupefying!</h1>"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

This web application will be served when the root domain is queried on port 5000. Allow this port through the firewall:

sudo firewall-cmd --add-port=5000/tcp --permanent
sudo firewall-cmd --reload

Test the application with the command:

$ python hello.py
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Serving Flask app 'hello'
 * Debug mode: off
 * Running on all addresses (0.0.0.0)
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://127.0.0.1:5000
 * Running on http://192.168.205.12:5000 (Press CTRL+C to quit)

Verify if the application is working by accessing it on the browser using the provided URL

Flask with Gunicorn and Nginx on Rocky Linux 9

#4. Configure Gunicorn for Flask

For Gunicorn to interact with the application, we need to create a WSGI Entry Point.

vim /sample_project/wsgi.py

Import the Flask instance from the created application.

from hello import application

if __name__ == "__main__":
    application.run()

Save the file and allow port 8080 through the firewall:

sudo firewall-cmd --add-port=8080/tcp --permanent
sudo firewall-cmd --reload

Now test Gunicorn’s ability to serve the application on the desired port(8080).

cd /sample_project
gunicorn --bind 0.0.0.0:8080 wsgi

Access the application on the web using the provided port:

Flask with Gunicorn and Nginx on Rocky Linux 9 1

Close the instance using CTRL+C and deactivate the virtual environment.

deactivate

#5. Manage the Flask Application

We need to create a systemd service file that will automatically start Gunicorn and serve the Flask application each time the system boots.

sudo vim /etc/systemd/system/web-app.service

The file will contain the below lines:

[Unit]
Description=The Gunicorn instance to serve Flask Project
After=network.target

[Service]
User=nginx
Group=nginx
WorkingDirectory=/sample_project
Environment="PATH=/sample_project/projectenv/bin"
ExecStart=/sample_project/projectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi

[Install]
WantedBy=multi-user.target

In the above file, replace /sample_project with the correct path to your project. We have also set Gunicorn to create a Unix socket called myproject.sock with a umask value of 007 that allows the Nginx group t access it.

Seve the file and configure SELinux for the path to be accessible.

sudo chcon -R -t bin_t /sample_project/projectenv/bin/

Reload the system daemon

sudo systemctl daemon-reload

Start and enable the application to start automatically on boot:

sudo systemctl start web-app
sudo systemctl enable web-app

Confirm if the service is running as desired:

$ systemctl status web-app
● web-app.service - The Gunicorn instance to serve Flask Project
     Loaded: loaded (/etc/systemd/system/web-app.service; enabled; vendor preset: disabled)
     Active: active (running) since Thu 2022-08-04 15:05:51 CEST; 7s ago
   Main PID: 31603 (gunicorn)
      Tasks: 4 (limit: 23441)
     Memory: 61.0M
        CPU: 370ms
     CGroup: /system.slice/web-app.service
             ├─31603 /sample_project/projectenv/bin/python /sample_project/projectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock ->
             ├─31604 /sample_project/projectenv/bin/python /sample_project/projectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock ->
             ├─31605 /sample_project/projectenv/bin/python /sample_project/projectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock ->
             └─31606 /sample_project/projectenv/bin/python /sample_project/projectenv/bin/gunicorn --workers 3 --bind unix:myproject.sock

#6. Configure the Nginx Web Server

We need to configure Nginx to proxy pass the HTTP requests as well as instruct Gunicorn to capture some information about the client.

sudo vim /etc/nginx/conf.d/sampleapp.conf

In the file, add the below lines;

server {
    listen 80;
    server_name server_domain_or_IP;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/sample_project/myproject.sock;
    }
}

In the file, replace the server_domain_or_IP and the Unix socket path /sample_project/myproject.sock.

Now allow the Gunicorn sock to be accessed by Nginx:

sudo semanage permissive -a httpd_t 

Also, allow Nginx to access the project directory:

sudo chgrp -R nginx /sample_project/

Verify the syntax of the config:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Start and enable Nginx:

sudo systemctl start nginx
sudo systemctl enable nginx

Allow the HTTP port through the firewall:

sudo firewall-cmd --add-port=80/tcp --permanent
sudo firewall-cmd --reload

Now access the URL http://IP_Address or http://domain_name

Flask with Gunicorn and Nginx on Rocky Linux 9 2

Verdict

We have systematically walked through how to install Flask with Gunicorn and Nginx on Rocky Linux 9. The knowledge gathered here can be used to create and use any other Flask application with Gunicorn and Nginx. I hope this was significant.

See more:

Best Books To Learn Object Oriented Programming

How To Install NetBox IPAM on Rocky Linux 8 / CentOS 8

Install Python 3.9 on CentOS 8 / CentOS 7

RELATED ARTICLES

Most Popular

Recent Comments