Flask is a popular, lightweight web framework for Python, and AWS EC2 is a widely used cloud service to deploy and manage virtual machines. Combining these two, you can easily deploy scalable web applications. In this tutorial, I’ll walk you through the steps to deploy a simple Flask app on an AWS EC2 instance.
For a visual walkthrough of the concepts covered in this article, check out my YouTube Video:-
Prerequisites:
- AWS Account
- Basic knowledge of Python and Flask
- AWS EC2 instance setup (Ubuntu 20.04 recommended)
- SSH access to your instance
- Security groups configured to allow traffic on ports 22 (SSH) and 80 (HTTP)
Step 1: Launch an EC2 Instance
- Log in to your AWS Console and navigate to EC2.
- Click “Launch Instance”, choose Ubuntu Server 20.04 as your OS.
- Choose the instance type (t2.micro for free-tier users).
- Configure the security group to allow inbound traffic on port 22 (SSH) and port 80 (HTTP).
- Launch the instance and download the key pair (make sure to save this). Once your EC2 instance is running, you can connect to it via SSH.
ssh -i /path-to-your-key.pem ubuntu@your-instance-public-ip
Step 2: Install Required Software
Update your instance and install necessary software packages, including Python3, pip, Flask, and Git (to pull your Flask app code):
sudo apt update
sudo apt upgrade -y
sudo apt install python3-pip python3-dev git -y
Install Flask using pip:
pip3 install Flask
Step 3: Clone or Create Your Flask App
If you have a Flask app in a GitHub repository, clone it onto your EC2 instance. Otherwise, you can create a simple Flask app directly.
Clone your repository:
git clone https://github.com/yourusername/your-flask-app.git
cd your-flask-app
Or, create a simple Flask app (if you don’t have one already):
mkdir myflaskapp
cd myflaskapp
nano app.py
Inside app.py, add the following simple Flask code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Flask on AWS EC2!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Save the file.
Step 4: Run the Flask App
To check if everything is working, you can run your Flask app using Python:
python3 app.py
Your app will run on port 5000. However, to access it over HTTP, we need to set up a production-ready server.
Step 5: Install and Configure Gunicorn
Gunicorn is a popular WSGI server for running Python web applications. Install it using pip:
pip3 install gunicorn
Now, run your Flask app with Gunicorn:
gunicorn --bind 0.0.0.0:5000 app:app
This will bind the app to your EC2 instance’s IP address on port 5000.
Step 6: Configure Nginx as a Reverse Proxy
We’ll use Nginx to serve the Flask app and act as a reverse proxy to Gunicorn.
- Install Nginx:
sudo apt install nginx -y
- Start and enable Nginx to run on boot:
sudo systemctl start nginx
sudo systemctl enable nginx
- Configure Nginx:
Open the default Nginx config file:
sudo nano /etc/nginx/sites-available/default
Replace the contents with the following configuration:
server {
listen 80;
server_name your-ec2-public-ip;
location / {
proxy_pass http://127.0.0.1:5000;
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;
}
}
Save and close the file.
- Test the Nginx configuration for syntax errors:
sudo nginx -t
- Restart Nginx to apply the changes:
sudo systemctl restart nginx
Step 7: Test Your Flask App
At this point, your Flask app should be accessible from the public IP address of your EC2 instance. Open a browser and navigate to:
http://your-ec2-public-ip
You should see “Hello, Flask on AWS EC2!” displayed.
Step 8: (Optional) Set Up a Systemd Service for Gunicorn
To ensure that Gunicorn starts automatically if your instance reboots, set it up as a systemd service.
- Create a new service file:
sudo nano /etc/systemd/system/myflaskapp.service
- Add the following configuration:
[Unit]
Description=Gunicorn instance to serve my Flask app
After=network.target
[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/myflaskapp
ExecStart=/usr/local/bin/gunicorn --workers 3 --bind 0.0.0.0:5000 app:app
[Install]
WantedBy=multi-user.target
- Start and enable the service:
sudo systemctl start myflaskapp
sudo systemctl enable myflaskapp
Now, your Flask app will run on boot without needing to be manually started.
Conclusion:
Congratulations! You’ve successfully deployed a Flask app on AWS EC2 using Nginx and Gunicorn. This setup allows you to scale your app and handle production traffic with ease. From here, you can explore more advanced topics like setting up a domain name, using HTTPS with SSL certificates, and even auto-scaling your instances.
This deployment method provides a solid foundation for any Flask-based web application, and AWS EC2 offers the flexibility to scale as your app grows.
Happy coding!
Connect with Us!
Stay connected with us for the latest updates, tutorials, and exclusive content:
WhatsApp:-https://www.whatsapp.com/channel/0029VaeX6b73GJOuCyYRik0i
Facebook:-https://www.facebook.com/S3CloudHub
Youtube:-https://www.youtube.com/@s3cloudhub
Free Udemy Course:-https://github.com/S3CloudHubRepo/Udemy-Free-Courses-coupon/blob/main/README.md
Connect with us today and enhance your learning journey!
Top comments (0)