Table of Contents
Implementing continuous integration and continuous deployment (CI/CD) workflows is essential for modern software development, especially when deploying FastAPI applications at scale. Combining Kubernetes and Jenkins provides a robust pipeline that automates testing, building, and deploying FastAPI services efficiently.
Overview of CI/CD for FastAPI
FastAPI is a high-performance web framework for building APIs with Python. To deploy FastAPI applications reliably, CI/CD workflows automate the process from code commit to live deployment. Kubernetes orchestrates containerized applications, while Jenkins manages the automation pipeline.
Prerequisites
- Docker installed for containerizing FastAPI applications
- Kubernetes cluster (local or cloud-based)
- Jenkins server set up and configured
- Git repository hosting the FastAPI codebase
- kubectl configured to interact with the Kubernetes cluster
Creating a Docker Image for FastAPI
Start by creating a Dockerfile in your FastAPI project directory:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Setting Up Jenkins Pipeline
Configure a Jenkins pipeline to automate the build, test, and deployment process. Use a Jenkinsfile in your repository:
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build Docker Image') {
steps {
script {
dockerImage = docker.build("your-dockerhub-username/fastapi-app:${env.BUILD_ID}")
}
}
}
stage('Push Image') {
steps {
script {
docker.withRegistry('https://registry.hub.docker.com', 'dockerhub-credentials') {
dockerImage.push()
}
}
}
}
stage('Deploy to Kubernetes') {
steps {
sh 'kubectl rollout restart deployment/fastapi-deployment'
}
}
}
}
Deploying to Kubernetes
Create a deployment YAML file for your FastAPI app:
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: your-dockerhub-username/fastapi-app:latest
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: fastapi-service
spec:
type: LoadBalancer
selector:
app: fastapi
ports:
- protocol: TCP
port: 80
targetPort: 80
Automating the Workflow
Integrate the Jenkins pipeline with your Git repository to trigger builds on code commits. Ensure your Kubernetes cluster is accessible from Jenkins, and your Docker registry credentials are configured securely.
Benefits of This Workflow
- Automated testing and deployment reduce manual errors
- Faster release cycles with continuous updates
- Scalable and reliable deployment using Kubernetes
- Consistent environments across development and production
By implementing this CI/CD workflow, teams can streamline FastAPI deployment, improve reliability, and accelerate feature delivery.