🎓 What You Will Learn
- Docker: Containerize FastAPI applications
- Kubernetes: Orchestrate containers at scale
- AWS Deployment: EC2, ECS, EKS, Beanstalk
- Google Cloud: Cloud Run, GKE deployment
- Heroku: Simple zero-config deployment
- CI/CD: GitHub Actions for automated testing and deployment
1Deployment Challenges
Moving from localhost to production requires handling multiple concerns: environment configuration, dependency management, process isolation, scaling, and monitoring.
Principle: Everything that works locally should work in production with the same dependencies and configuration.
2Docker Fundamentals
Docker containers package your app with all dependencies, ensuring consistency across environments.
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]3Docker Best Practices
Build optimized, secure container images.
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.11-slim
# Non-root user for security
RUN useradd -m -u 1000 appuser
WORKDIR /app
COPY --from=builder /root/.local /home/appuser/.local
COPY . .
USER appuser
ENV PATH=/home/appuser/.local/bin:$PATH
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0"]4Docker Compose for Local Development
Use Docker Compose to run multi-container setups locally (app + database + cache).
version: "3.8"
services:
web:
build: .
ports:
- "8000:8000"
environment:
DATABASE_URL: postgresql://user:password@db:5432/appdb
REDIS_URL: redis://cache:6379
depends_on:
- db
- cache
db:
image: postgres:15
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: appdb
volumes:
- postgres_data:/var/lib/postgresql/data
cache:
image: redis:7-alpine
volumes:
postgres_data:5Kubernetes Basics
Kubernetes orchestrates containers across multiple machines with auto-scaling, self-healing, and rolling updates.
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-app
spec:
replicas: 3
selector:
matchLabels:
app: fastapi
template:
metadata:
labels:
app: fastapi
spec:
containers:
- name: fastapi
image: my-registry/fastapi-app:latest
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 106AWS EC2 Deployment
Deploy to a single EC2 instance for simple applications.
# SSH into EC2 instance
ssh -i key.pem ec2-user@instance-ip
# Install Docker
sudo yum install docker -y
sudo systemctl start docker
# Clone repository
git clone your-repo
cd your-repo
# Build and run
docker build -t fastapi-app .
docker run -d -p 80:8000 fastapi-app7AWS ECS for Container Orchestration
ECS is AWS's managed container orchestration service (simpler than Kubernetes).
ECS vs EKS: ECS is easier and cheaper, Kubernetes is more powerful and portable.
8AWS Elastic Beanstalk
Beanstalk handles deployment, scaling, and monitoring automatically.
# Install Elastic Beanstalk CLI
pip install awsebcli
# Initialize
eb init -p python-3.11 my-app
# Create environment
eb create production
# Deploy
git commit -m "new version"
eb deploy9Google Cloud Run
Serverless container execution. Pay only for actual usage.
# Build and push to Container Registry
gcloud builds submit --tag gcr.io/project-id/fastapi-app
# Deploy to Cloud Run
gcloud run deploy fastapi-app \
--image gcr.io/project-id/fastapi-app \
--platform managed \
--region us-central1 \
--allow-unauthenticated10Heroku Simple Deployment
Heroku is the easiest platform for quick deployments.
web: gunicorn -w 4 -b 0.0.0.0:$PORT app.main:app# Install Heroku CLI
curl https://cli-assets.heroku.com/install.sh | sh
# Login and create app
heroku login
heroku create my-fastapi-app
# Deploy
git push heroku main
# View logs
heroku logs --tail11CI/CD with GitHub Actions
Automate testing and deployment on every commit.
name: Deploy
on:
push:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- run: pip install -r requirements.txt
- run: pytest
- run: docker build -t fastapi-app .
deploy:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: docker build -t fastapi-app .
- run: docker push registry/fastapi-app:latest12Environment Configuration
Manage configuration safely across environments.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
redis_url: str
debug: bool = False
environment: str = "development"
class Config:
env_file = ".env"
settings = Settings()Never: Commit secrets (.env files, keys, tokens) to version control. Use environment variables.
13Monitoring and Logging
Track application health and debug issues in production.
| Tool | Purpose |
|---|---|
| Prometheus | Metrics and alerting |
| ELK Stack | Centralized logging |
| Datadog | Full observability platform |
| New Relic | APM and monitoring |
| Sentry | Error tracking |
14Auto-Scaling Strategies
Scale applications based on demand.
- Horizontal Scaling: Add more instances (Kubernetes, ECS, ASG)
- Vertical Scaling: Use larger instances (simple but limited)
- Database Scaling: Read replicas, sharding
- Caching: Redis, CDN for static content
15Resources & What's Next
You now understand how to deploy FastAPI applications to production. Choose the platform that fits your needs (serverless, managed, or self-hosted).
Deployment Path: Start with Heroku or Cloud Run for simplicity, graduate to Kubernetes as you scale.
Congratulations! Your FastAPI app is ready for production. Deploy with confidence and monitor continuously! 🚀