How to Deploy Flask with Gunicorn and Nginx (on Ubuntu)

3 min read 6 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

  1. Access Google Domains where your domain is registered.
  2. Create an A record mapping your domain to the server's IP address.

Step 2: SSH into the Server and Create a New User

  1. SSH into your server using the new domain or IP address.
  2. Create a new user for running the Flask app.
  3. Grant sudo privileges to the new user using usermod -aG sudo username.

Step 3: Clone Flask App Code from GitHub

  1. Clone the Flask app code repository from GitHub into a directory on the server.
  2. Set up a Python virtual environment inside the directory for the new user.

Step 4: Install Gunicorn and Set Up Gateway Interface

  1. Install Gunicorn using pip install gunicorn.
  2. Create a file named GatewayInterface.py in the Flask app directory.
  3. Configure the Gateway Interface file to run the Flask app using Gunicorn.

Step 5: Set Up Systemd Service for Flask App

  1. Create a systemd service file for the Flask app to manage its process.
  2. Define the service settings including user, group, working directory, environment, and command.

Step 6: Start and Enable the Flask App Service

  1. Start the Flask app service using sudo systemctl start servicename.
  2. Enable the service to start automatically on server boot using sudo systemctl enable servicename.
  3. Check the status of the service to ensure it is active and running.

Step 7: Set Up Nginx as a Reverse Proxy

  1. Install Nginx on the server using sudo apt install nginx.
  2. Configure Nginx to act as a reverse proxy for the Flask app.
  3. Test the Nginx configuration and restart Nginx to apply the changes.

Step 8: Adjust Firewall Settings

  1. Allow Nginx traffic through the firewall using sudo ufw allow 'Nginx Full'.
  2. Open ports 80 and 443 for HTTP traffic using sudo ufw allow 80 and sudo ufw allow 443.

Step 9: Debug and Test the Deployment

  1. Check the Nginx error log for any permission denied issues related to socket file access.
  2. Change the permissions of the directory where the socket file is located using chmod 775 directory.
  3. Refresh the webpage to ensure the Flask app is being served via Nginx.

Step 10: Optional - Enable HTTPS for Flask App

  1. 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.