This guide documents the steps to deploy a FastAPI CRUD API on an EC2 instance using Docker, including troubleshooting issues encountered along the way.
- AWS account with access to EC2
- Docker installed on your local machine
- Basic understanding of FastAPI
- SSH access to your EC2 instance
- Python installed locally for development
Create a new directory for your FastAPI project:
mkdir fastapi-crud
cd fastapi-crudInside this directory, create the following structure:
fastapi-crud/
│-- app/
│ │-- main.py # Entry point of the FastAPI app
│ │-- models.py # Database models
│ │-- database.py # Database connection
│ │-- schemas.py # Pydantic models for request validation
│ │-- crud.py # CRUD functions
│ │-- routers/
│ │ │-- items.py # API routes for handling CRUD
│-- requirements.txt # Dependencies
│-- Dockerfile # Docker configuration
│-- .env # Environment variables
│-- README.md # Documentation
The file contents can be copied from this repo.
- Log in to your AWS console and navigate to EC2.
- Launch a new instance using an Amazon Linux 2 or Ubuntu AMI.
- Select an instance type (e.g.,
t2.microfor free tier users). - Configure security group:
- Allow SSH (port 22) from your IP.
- Allow HTTP (port 80) and/or HTTPS (port 443).
- Allow your FastAPI app port (e.g., 8000).
- Create or use an existing key pair for SSH access.
- Launch the instance and note its public IP address.
ssh -i your-key.pem ec2-user@your-ec2-ipFor Ubuntu:
ssh -i your-key.pem ubuntu@your-ec2-ipsudo yum update -y # For Amazon Linux
sudo apt update -y # For Ubuntu
sudo yum install -y docker # Amazon Linux
sudo apt install -y docker.io # Ubuntu
sudo systemctl start docker
sudo systemctl enable docker
sudo usermod -aG docker ec2-user # Add user to Docker groupLogout and log back in to apply group changes.
Use SCP (or Git if you have a repo):
scp -i your-key.pem -r fastapi-crud ec2-user@your-ec2-ip:~cd fastapi-crud
docker build -t fastapi-app .
docker run -d -p 8000:8000 --restart always fastapi-app- Go to AWS EC2 Dashboard → Security Groups.
- Add an Inbound Rule for port 8000 with Source: 0.0.0.0/0 (or your IP for security).
Visit in your browser:
http://your-ec2-public-ip:8000Visit FastAPI Swagger UI:
http://your-ec2-public-ip:8000/docs- Cannot access FastAPI from browser:
- Check if the security group allows traffic on port 8000.
- Run
docker psto ensure the container is running. - Inspect logs with
docker logs <container_id>.
- Docker command not found:
- Ensure Docker is installed and running (
sudo systemctl start docker).
- Ensure Docker is installed and running (
- Permissions issue with Docker:
- Run
sudo usermod -aG docker $USERand restart your session.
- Run
Your FastAPI CRUD API is now running on an EC2 instance using Docker! 🎉