Table of Contents
Deploying FastAPI applications using Docker and Kubernetes is a powerful way to ensure scalability, portability, and efficient management of your APIs. This step-by-step workflow guides you through the process from containerization to deployment on a Kubernetes cluster.
Prerequisites
- Basic knowledge of FastAPI and Python
- Docker installed on your machine
- Kubernetes cluster (local or cloud-based)
- kubectl configured to access your cluster
- Optional: Helm for managing Kubernetes resources
Step 1: Create Your FastAPI Application
Start by developing your FastAPI app. Save it in a directory, for example, app.py.
Example app.py:
from fastapi import FastAPI
app = FastAPI()
@app.get(“/”)
def read_root():
return {“Hello”: “World”}
Step 2: Containerize the Application with Docker
Create a Dockerfile in the same directory:
FROM python:3.11-slim
WORKDIR /app
RUN pip install fastapi uvicorn
COPY . /app
CMD [“uvicorn”, “app:app”, “–host”, “0.0.0.0”, “–port”, “80”]
Build the Docker image:
docker build -t fastapi-app:latest .
Step 3: Push the Image to a Container Registry
Tag your image and push it to Docker Hub or your preferred registry:
docker tag fastapi-app:latest yourusername/fastapi-app:latest
docker push yourusername/fastapi-app:latest
Step 4: Create Kubernetes Deployment and Service
Define a deployment in a YAML file, deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-deployment
spec:
replicas: 3
selector:
matchLabels:
app: fastapi
template:
metadata:
labels:
app: fastapi
spec:
containers:
– name: fastapi
image: yourusername/fastapi-app:latest
ports:
– containerPort: 80
Apply the deployment:
kubectl apply -f deployment.yaml
Next, create a service in service.yaml:
apiVersion: v1
kind: Service
metadata:
name: fastapi-service
spec:
type: LoadBalancer
selector:
app: fastapi
ports:
– port: 80
targetPort: 80
Deploy the service:
kubectl apply -f service.yaml
Step 5: Access Your FastAPI Application
Once the service is running, retrieve the external IP address:
kubectl get services
Open your browser and navigate to the external IP to see your FastAPI app in action.
Conclusion
This workflow demonstrates how to containerize a FastAPI application with Docker and deploy it seamlessly on a Kubernetes cluster. This setup provides a scalable and portable API infrastructure suitable for production environments.