FastAPI + Docker + AWS EC2 Deployment Guide
Prerequisites (Local)
1. Create a Dockerfile
Create a Dockerfile in your project root:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
If your project structure follows
app/main.py, set the entry point asapp.main:app
2. Push to GitHub
git add Dockerfile
git commit -m "Add Dockerfile"
git push origin main
AWS EC2 Setup
⚠️ We were using a provided AWS account, so the EC2 setup process is slightly different from the standard approach. Follow the steps below carefully.
3. Create a Security Group First
- EC2 Console → Left menu Security Groups → Create security group
- Enter name and description
- Select VPC → Click Create
- Wait 5–10 seconds (for automatic tag attachment)
4. Add Inbound Rules
After confirming the tag is attached, edit inbound rules:
| Type | Port | Source |
|---|---|---|
| SSH | 22 | 0.0.0.0/0 |
| HTTP | 80 | 0.0.0.0/0 |
| Custom TCP | 8000 | 0.0.0.0/0 |
Click Save rules
5. Launch an EC2 Instance
- Enter a name (e.g.,
my_projectname) - OS: Ubuntu 22.04 LTS
- Instance type: t3.micro
- Key pair: Create new → Download and save the
.pemfile - Security group: Select the one you just created
- Click Launch instance
6. Set an Instance Profile
- Select instance → Actions → Security → Modify IAM role
- Choose
SafeInstanceProfile-{username}→ Save
EC2 Server Configuration
7. Connect to EC2
- Confirm instance status is
running - Click Connect → EC2 Instance Connect tab → Click Connect
- A black terminal window in your browser means success
8. Set Up the Server Environment
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-venv git -y
9. Install Docker
sudo apt install docker.io -y
sudo systemctl start docker
sudo systemctl enable docker
sudo usermod -aG docker ubuntu
⚠️ After installation, close the terminal and reconnect via EC2 Instance Connect!
After reconnecting, verify Docker is installed:
docker --version
10. Clone the Repository
Use a Personal Access Token instead of your GitHub password
git clone https://YOUR_TOKEN@github.com/teamname/my_projectname.git
cd my_projectname
To generate a token: GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic) → Generate new token → Check repo
11. Build the Docker Image
docker build -t my_projectname .
12. Run the Docker Container
docker run -d --name my_projectname -p 8000:8000 my_projectname
13. Verify It's Running
# Check container status
docker ps
# Check logs
docker logs my_projectname
Verify Access
Open your browser and navigate to:
http://YOUR_EC2_PUBLIC_IP:8000/docs
Top comments (0)