How To Deploy Flask Application With Nginx and Gunicorn On Ubuntu 20.04 - RoseHosting
How To Deploy Flask Application With Nginx and Gunicorn On Ubuntu 20.04 - RoseHosting
Table of Contents
Prerequisites
Log in and Update Packages
Install Required Dependencies
Install Nginx Web Server
Create a Virtual Environment for Flask
Application
Create a Flask Application
Create a WSGI Entry Point for Gunicorn
Create a Systemd Service File for Flask
Application
ConOgure Nginx as a Reverse Proxy for
Flask Application
Access Flask Application
Prerequisites
A Ubuntu 20.04 VPS with root access
enabled, or a user with sudo
privileges.
apt-get update -y
apt-get upgrade -y
Install Required
Dependencies
Flask is a python-based application. So
Python and other required dependencies
must be installed on your server. If not
installed you can install all of them with the
following command:
Create a Virtual
Environment for Flask
Application
Next, you will need to create a virtual
environment for the Flask application.
mkdir ~/project
cd ~/project
python3 -m venv venv
source venv/bin/activate
Create a Flask
Application
Next, you will need to create a sample Flask
application for your project. Run the
following command to create it inside your
project directory:
nano ~/project/Xaskapp.py
cd ~/project/
python3 Xaskapp.py
nano ~/project/wsgi.py
cd ~/project/
gunicorn --bind 0.0.0.0:5000 wsgi:app
deactivate
Create a Systemd
Service File for Flask
Application
Next, you will need to create a systemd unit
Rle for the Flask application. You can create
it with the following command:
nano /etc/systemd/system/Xask.service
[Unit]
Description=Gunicorn instance to serve
Flask
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/project
Environment="PATH=/root/project/venv/
bin"
ExecStart=/root/project/venv/bin/gunico
rn --bind 0.0.0.0:5000 wsgi:app
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
Output:
ConOgure Nginx as a
Reverse Proxy for
Flask Application
Next, you will need to conRgure Nginx as a
reverse proxy to serve the Flask application
through port 80. To do so, create an Nginx
virtual host conRguration Rle:
nano /etc/nginx/conf.d/Xask.conf
NVME 2 VPS
server {
listen 80;
server_name Xask.example.com;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:5000;
}
}
nginx -t
Access Flask
Application
At this point, your Flask application is
installed, conRgured, and hosted with an
Nginx proxy. You can now access it using the
URL http://Uask.example.com. You should
see the following page:
Owen
May 24, 2022 at 07:29
Reply
admin
May 25, 2022 at 02:16
Reply
Leave a Comment
Name *
Email *
six × = 24
Post Comment
Categories
Select Category