Deploying Flask Applications on AWS EC2

AWS Flask Gunicorn Nginx DevOps
← Back to Blogs

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

1. Launch an EC2 Instance

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

2. Connect to Your Instance

Once your instance is running, connect to it via SSH:

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

3. Install Required Packages

Update your system and install necessary dependencies:

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

4. Set Up Your Application

Clone your application repository and set up a virtual environment:

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
pip install gunicorn

5. Configure Gunicorn

Create a systemd service file for Gunicorn to run your application:

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

Create an Nginx configuration file for your application:

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;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

7. Enable and Start Services

Link the Nginx configuration and start all 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
sudo systemctl status myflaskapp

8. Verify Deployment

Your Flask application should now be running. Test it by accessing your EC2 instance's public IP address in a web browser.

Troubleshooting Common Issues

Conclusion

Your Flask application should now be running on your EC2 instance. Remember to: