Technical Blog

Deploying Flask Applications on AWS EC2

Published on March 15, 2024 10 min read

Deploying a Flask application properly is crucial for ensuring your web application runs efficiently and securely in a production environment. This guide will walk you through the process of deploying a Flask application on AWS EC2 using Gunicorn as the WSGI server and Nginx as the reverse proxy.

Prerequisites

  • An AWS account
  • Basic knowledge of command line and SSH
  • A Flask application ready for deployment

1. Launch an EC2 Instance

First, we'll need to set up our EC2 instance:

  • Sign in to AWS Management Console
  • Navigate to EC2 Dashboard
  • Click "Launch Instance"
  • Choose Ubuntu Server 20.04 LTS
  • Select t2.micro (free tier eligible)
  • Configure security group to allow HTTP (80) and SSH (22)
  • Create or select an existing key pair

2. Connect to Your Instance

ssh -i /path/to/your-key.pem ubuntu@your-public-ip

3. Install Required Packages

sudo apt update
sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv nginx git -y

4. Set Up Your Application

cd ~
git clone https://github.com/yourusername/your-repo.git
cd your-repo
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

5. Configure Gunicorn

Create a systemd service file for Gunicorn:

sudo nano /etc/systemd/system/myflaskapp.service

Add the following configuration:

[Unit]
Description=Gunicorn instance for myflaskapp
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/your-repo
Environment="PATH=/home/ubuntu/your-repo/.venv/bin"
ExecStart=/home/ubuntu/your-repo/.venv/bin/gunicorn --workers 3 --bind unix:myflaskapp.sock -m 007 app:app

[Install]
WantedBy=multi-user.target

6. Configure Nginx

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

Add the following configuration:

server {
    listen 80;
    server_name your-public-ip;

    location / {
        proxy_pass http://unix:/home/ubuntu/your-repo/myflaskapp.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

7. Enable and Start Services

sudo ln -s /etc/nginx/sites-available/myflaskapp /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
sudo systemctl start myflaskapp
sudo systemctl enable myflaskapp

Conclusion

Your Flask application should now be running on your EC2 instance. You can access it using your instance's public IP address. Remember to:

  • Set up HTTPS using Let's Encrypt for production
  • Implement proper monitoring and logging
  • Regularly update your packages and security groups
  • Back up your application and data regularly