A simple FastAPI application that returns the container ID it runs in, perfect for demonstrating load balancing in Docker and Kubernetes.
- Returns the container/host identifier on each request
- Health check endpoint
- Ready for Docker and Kubernetes deployment
docker build -t kube-demo:latest .docker run -p 8000:8000 kube-demo:latestcurl http://localhost:8000You should see a response like:
{
"container_id": "abc123def456",
"hostname": "abc123def456",
"message": "Request served by container: abc123def456",
"counter": 1
}- Kubernetes cluster (Minikube, Kind, or any Kubernetes cluster)
- kubectl configured to connect to your cluster
minikube start- Configure your
.envfile with GCP registry details:
REGISTRY=gcr.io/YOUR_PROJECT_ID
# or for Artifact Registry:
# REGISTRY=REGION-docker.pkg.dev/YOUR_PROJECT_ID/REPO_NAME
IMAGE_NAME=kube-demo
IMAGE_TAG=latest- Authenticate with GCP:
gcloud auth configure-docker- Build and push the image:
make push_gcpThis will build and push the image to your GCP container registry.
The deployment will pull the image from your GCP registry. Make sure deployment.yaml uses the same image name as in your .env file, or update it manually:
# Update deployment.yaml with your GCP image, then:
kubectl apply -f deployment.yamlOr use the Makefile to deploy (automatically uses image from .env):
make deployCheck that pods are running:
kubectl get pods -l app=kube-demoYou should see 3 pods running (as configured with replicas: 3).
# Get the service URL
minikube service kube-demo-service --url
# Or access directly via NodePort
curl $(minikube ip):30080kubectl port-forward service/kube-demo-service 8000:8000Then test:
curl http://localhost:8000Make multiple requests to see different container IDs:
# Using NodePort (Minikube)
for i in {1..10}; do
curl $(minikube ip):30080
echo ""
done
# Or using port-forward
for i in {1..10}; do
curl http://127.0.0.1:57825/
echo ""
doneEach request will be load balanced across the 3 pods, and you'll see different container_id values in the responses, demonstrating that Kubernetes is distributing requests across multiple instances.
To see which pod handled each request:
# View logs from all pods
kubectl logs -l app=kube-demo --tail=10
# View logs from a specific pod
kubectl logs <pod-name>kubectl delete -f deployment.yamlIf using Minikube:
minikube stop