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
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
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 gunicorn
5. 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.target
6. 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.