Deploying Flask Applications on AWS EC2
Complete guide to deploying Flask applications on AWS EC2 using Gunicorn and Nginx for production-ready deployment.
March 15, 2024 · 10 min read · AWS, Flask, DevOps, Nginx
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
- Understanding of Python virtual environments
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 (or newer)
- Select t2.micro (free tier eligible)
- Configure security group to allow HTTP (80), HTTPS (443), and SSH (22)
2. Connect to Your Instance
ssh -i /path/to/your-key.pem ubuntu@your-public-ip3. Install Required Packages
sudo apt update
sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv nginx git -y4. Set Up Your Application
Clone your application repository and set up a virtual environment:
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 gunicorn5. Configure Gunicorn
Create a systemd service file: `sudo nano /etc/systemd/system/myflaskapp.service`
[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.target6. Configure Nginx
Create configuration: `sudo nano /etc/nginx/sites-available/myflaskapp`
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. Conclusion
Your Flask application is now running on EC2 with Gunicorn and Nginx! Don't forget to set up HTTPS next.