How to Deploy Flask with Gunicorn and Nginx (on Ubuntu)
3 min read
8 months ago
Published on Apr 23, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Step-by-Step Tutorial: Deploying Flask App with Gunicorn and Nginx on Ubuntu
Prerequisites:
- A Flask app that you want to deploy
- Access to a server with Ubuntu installed
- Basic knowledge of using the terminal and text editor
Step 1: Update Domain IP Address
- Access Google Domains where your domain is registered.
- Create an A record mapping your domain to the server's IP address.
Step 2: SSH into the Server and Create a New User
- SSH into your server using the new domain or IP address.
- Create a new user for running the Flask app.
- Grant sudo privileges to the new user using
usermod -aG sudo username
.
Step 3: Clone Flask App Code from GitHub
- Clone the Flask app code repository from GitHub into a directory on the server.
- Set up a Python virtual environment inside the directory for the new user.
Step 4: Install Gunicorn and Set Up Gateway Interface
- Install Gunicorn using
pip install gunicorn
. - Create a file named
GatewayInterface.py
in the Flask app directory. - Configure the Gateway Interface file to run the Flask app using Gunicorn.
Step 5: Set Up Systemd Service for Flask App
- Create a systemd service file for the Flask app to manage its process.
- Define the service settings including user, group, working directory, environment, and command.
Step 6: Start and Enable the Flask App Service
- Start the Flask app service using
sudo systemctl start servicename
. - Enable the service to start automatically on server boot using
sudo systemctl enable servicename
. - Check the status of the service to ensure it is active and running.
Step 7: Set Up Nginx as a Reverse Proxy
- Install Nginx on the server using
sudo apt install nginx
. - Configure Nginx to act as a reverse proxy for the Flask app.
- Test the Nginx configuration and restart Nginx to apply the changes.
Step 8: Adjust Firewall Settings
- Allow Nginx traffic through the firewall using
sudo ufw allow 'Nginx Full'
. - Open ports 80 and 443 for HTTP traffic using
sudo ufw allow 80
andsudo ufw allow 443
.
Step 9: Debug and Test the Deployment
- Check the Nginx error log for any permission denied issues related to socket file access.
- Change the permissions of the directory where the socket file is located using
chmod 775 directory
. - Refresh the webpage to ensure the Flask app is being served via Nginx.
Step 10: Optional - Enable HTTPS for Flask App
- Follow additional resources to configure HTTPS for your Flask app if needed.
Congratulations! You have successfully deployed your Flask app using Gunicorn and Nginx on an Ubuntu server.