DEV Community

S3CloudHub
S3CloudHub

Posted on

How to Deploy a Flask App on an AWS EC2 Instance: A Step-by-Step Guide

Image description
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:-
image alt text here

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

  1. Log in to your AWS Console and navigate to EC2.
  2. Click “Launch Instance”, choose Ubuntu Server 20.04 as your OS.
  3. Choose the instance type (t2.micro for free-tier users).
  4. Configure the security group to allow inbound traffic on port 22 (SSH) and port 80 (HTTP).
  5. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Install Flask using pip:

pip3 install Flask
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Or, create a simple Flask app (if you don’t have one already):

mkdir myflaskapp
cd myflaskapp
nano app.py
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now, run your Flask app with Gunicorn:

gunicorn --bind 0.0.0.0:5000 app:app
Enter fullscreen mode Exit fullscreen mode

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.

  1. Install Nginx:
sudo apt install nginx -y
Enter fullscreen mode Exit fullscreen mode
  1. Start and enable Nginx to run on boot:
sudo systemctl start nginx
sudo systemctl enable nginx
Enter fullscreen mode Exit fullscreen mode
  1. Configure Nginx:

Open the default Nginx config file:

sudo nano /etc/nginx/sites-available/default
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Save and close the file.

  1. Test the Nginx configuration for syntax errors:
sudo nginx -t

Enter fullscreen mode Exit fullscreen mode
  1. Restart Nginx to apply the changes:
sudo systemctl restart nginx

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

  1. Create a new service file:
sudo nano /etc/systemd/system/myflaskapp.service

Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. Start and enable the service:
sudo systemctl start myflaskapp
sudo systemctl enable myflaskapp
Enter fullscreen mode Exit fullscreen mode

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)