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 Abhishek Testing
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:
Access AWS EC2 Instance using FileZilla
Access AWS EC2 Instance using PuTTY
đ 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/testingYour API will later be accessible using your EC2 Public IP like:
http://3.140.251.200:8001
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.pyOnce the server is running, open your browser and access:
http://44.203.192.53:8000
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.
You can now build REST APIs, connect databases, or deploy production-ready applications using Gunicorn and Nginx.