Deploying a Flask application with Nginx and securing it with Let's Encrypt is a common task for deploying production-ready web services. This guide provides a step-by-step process to help you set up your Flask app, configure Nginx as a reverse proxy, and obtain SSL certificates for secure communication.

Prerequisites

  • A server running Ubuntu 20.04 or later
  • Root or sudo access to the server
  • Python 3 and pip installed
  • Domain name pointing to your server's IP address
  • Basic knowledge of terminal commands

Step 1: Set Up Your Flask Application

Create a directory for your Flask app and set up a virtual environment:

mkdir ~/myflaskapp

cd ~/myflaskapp

python3 -m venv venv

Activate the virtual environment:

source venv/bin/activate

Install Flask:

pip install Flask

Create a simple Flask app in app.py:

nano app.py

Insert the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

return "Hello, Flask with Nginx and Let's Encrypt!"

if __name__ == "__main__":

app.run(host="0.0.0.0", port=5000)

Step 2: Run Your Flask Application with Gunicorn

Install Gunicorn:

pip install gunicorn

Test run your app:

gunicorn --bind 0.0.0.0:8000 app:app

If it works, you can set up a systemd service for automatic startup.

Step 3: Install and Configure Nginx

Install Nginx:

sudo apt update

sudo apt install nginx

Create a new Nginx configuration file:

sudo nano /etc/nginx/sites-available/myflaskapp

Insert the following configuration:

server {

listen 80;

server_name your_domain.com www.your_domain.com;

location / {

proxy_pass http://127.0.0.1:8000;

proxy_set_header Host $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;

}

error_page 404 /404.html;

}

Enable the site and restart Nginx:

sudo ln -s /etc/nginx/sites-available/myflaskapp /etc/nginx/sites-enabled

sudo nginx -t

sudo systemctl restart nginx

Step 4: Obtain SSL Certificates with Let's Encrypt

Install Certbot:

sudo apt install certbot python3-certbot-nginx

Obtain and install the certificate:

sudo certbot --nginx -d your_domain.com -d www.your_domain.com

Follow the prompts to complete the setup. Certbot will automatically configure SSL in Nginx.

Step 5: Final Checks and Automation

Verify that your site is accessible via HTTPS. You should see a secure padlock in the browser address bar.

Set up automatic renewal:

sudo certbot renew --dry-run

This command tests automatic renewal. Certbot will renew certificates before they expire.

Conclusion

By following these steps, you have successfully deployed a Flask application with Nginx and secured it with Let's Encrypt SSL certificates. This setup provides a robust, secure, and scalable environment for your web application.