Deploying a Flask App on Ubuntu 20.04 with Nginx and Gunicorn: A Step-by-Step Guide
1. Updating the package index
sudo apt update
2. Afterwards, installing the necessary packages to set up your Python environment is essential. These packages comprise python3-pip, a manager for Python packages, along with other crucial development tools for establishing a resilient programming environment. Execute the following commands to install python3, python3-pip, and Nginx:
sudo apt install python3-pip python3-dev nginx -y
3. Now, proceed to install Flask and Gunicorn using the pip command:
pip3 install flask gunicorn
4. Creating a sample project and WSGI entry point
1. nano app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hey There! Welcome to Flask app!"
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
from app import app
if __name__ == "__main__":
app.run()
You can assess Gunicorn's capability to host your project by executing the following command:
gunicorn --bind 0.0.0.0:5000 wsgi:app
Note: - At this point, let's review the current organization of the folder structure:
myFlaskApp
|____ app.py
|____ wsgi.py
|____ env
5. Now, let's create a systemd service:
sudo nano /etc/systemd/system/app.service
Next, paste the following contents into this file:
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=raunak
Group=www-data
WorkingDirectory=/home/ubuntu/handsign #Ensure you specify the correct project folder when entering the provided content:
ExecStart=gunicorn --workers 3 --bind unix:myproject.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target
Activate this service by entering the following command:
sudo systemctl start app
sudo systemctl enable app
After activation, you'll notice that a file named app.sock is automatically generated. Let's take a look at the current folder structure:
myFlaskApp
|____ app.py
|____ wsgi.py
|____ app.sock
6. Now, let's proceed with configuring Nginx:
Create a file named app inside /etc/nginx/sites-available
sudo nano /etc/nginx/sites-available/handsign
Now, copy the following contents into this file:
server {
listen 80; # Listen on port 80 (HTTP)
server_name 52.65.168.78; # Replace with your domain or server IP
location / {
proxy_pass http://127.0.0.1:5000; # Forward requests to port 5000
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Activate this configuration by running the following command:
sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled
7. Afterwards, restart Nginx, and your website should be operational without any issues!
sudo systemctl restart nginx
8. If you are utilizing a firewall, such as ufw, remember to enable Nginx to receive incoming traffic on port 80:
sudo ufw allow 'Nginx Full'