How to Run a Python Flask API Server on AWS EC2 (Step-by-Step Guide)

In this article, I will show you how to run a simple Python Flask API server on your AWS EC2 Ubuntu instance using a virtual environment.
📌
Prerequisite
I am assuming you have already created an EC2 Linux/Ubuntu Instance. If not, follow this step-by-step guide:
👉 How to Create an AWS EC2 Instance
After creating your EC2 instance, it is recommended to set up FileZilla and PuTTY for easier server access. If not configured yet, follow these guides:
🔄 Step 1: Update the Server & Install Python venv
After connecting to your EC2 instance via SSH, first update the system packages and install Python virtual environment support.
sudo apt-get update
sudo apt-get install python3-venv
        
📁 Step 2: Create Project Folder Structure
Now create a working directory for your API project.
mkdir codingfolder
cd codingfolder

mkdir testing
cd testing

cd codingfolder/testing
        
Your API will later be accessible using your EC2 Public IP like:
http://3.140.251.200:8001
🐍 Step 3: Create and Activate Virtual Environment
Create a Python virtual environment inside your project folder.
python3 -m venv venv
source venv/bin/activate
        
📦 Step 4: Install Flask & Create App File
Install Flask and create your API file.
pip install Flask
sudo vi app.py
        
📝 Step 5: Add Flask API Code
Paste the following simple Flask application inside app.py:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8001)
        
🚀 Step 6: Run the Python API Server
Now start your Flask server:
python app.py
        
Once the server is running, open your browser and access:
http://44.203.192.53:8000
⚠️ Make sure port 8001 (or 8000 if you changed it) is allowed in your EC2 Security Group inbound rules.
✅ Success!
Congratulations 🎉 Your Python Flask API server is now running on AWS EC2.

You can now build REST APIs, connect databases, or deploy production-ready applications using Gunicorn and Nginx.