Skip to content

aleynadedee/flask-mongodb-kubernetes-rest-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python Bookstore API - Containerized Application with MongoDB on Kubernetes

Table of Contents

Overview

This project is a containerized system that runs a Python Flask application with MongoDB database on a Kubernetes cluster. The application provides RESTful API endpoints for CRUD (Create, Read, Update, Delete) operations.

Technologies Used:

  • Python 3.9
  • Flask 2.3.0
  • MongoDB 5.0
  • Docker
  • Kubernetes
  • PyMongo 4.4.0

Prerequisites

You need to have the following tools installed on your computer:

  • Docker (v20.10+)
    docker --version
  • Kubernetes (kubectl)
    kubectl version --client
  • Minikube (for local Kubernetes cluster)
    minikube version
  • Git
    git --version

Project Structure

CLOUD-PROJECT-1/
├── app.py                      # Flask application (CRUD operations)
├── requirements.txt            # Python dependencies
├── Dockerfile                  # Docker image configuration
├── .dockerignore               # Files to exclude from Docker build
├── README.md                   # This file
└── k8s/                        # Kubernetes configuration files
    ├── secret.yaml             # MongoDB credentials
    ├── mongodb-service.yaml    # MongoDB Service
    ├── mongodb-statefulset.yaml # MongoDB StatefulSet
    ├── flask-configmap.yaml    # Flask ConfigMap
    ├── flask-deployment.yaml   # Flask Deployment
    └── flask-service.yaml      # Flask Service

Installation Steps

Step 1 - Start Minikube

# Start Minikube cluster (may take time on first run)
minikube start --driver=docker

# Check Minikube status
minikube status

# Set up Docker environment with Minikube
eval $(minikube docker-env)

Step 2 - Build Docker Image

# Navigate to project directory
cd CLOUD-PROJECT-1

# Build Docker image
docker build -t python-bookstore:v1 .

# Verify image was created
docker images | grep python-bookstore

Step 3 - Create Kubernetes Secret and ConfigMap

# Create Secret (MongoDB credentials)
kubectl apply -f k8s/secret.yaml

# Create ConfigMap (Flask configuration)
kubectl apply -f k8s/flask-configmap.yaml

# Verify created resources
kubectl get secrets
kubectl get configmaps

Step 4 - Deploy MongoDB

# Create MongoDB Service
kubectl apply -f k8s/mongodb-service.yaml

# Deploy MongoDB StatefulSet
kubectl apply -f k8s/mongodb-statefulset.yaml

# Wait for MongoDB to be ready (2-3 minutes)
kubectl get statefulset

# Check MongoDB Pod status
kubectl get pods | grep mongodb

Step 5 - Deploy Flask Application

# Create Flask Deployment
kubectl apply -f k8s/flask-deployment.yaml

# Create Flask Service (LoadBalancer)
kubectl apply -f k8s/flask-service.yaml

# Wait for Deployment to be ready
kubectl get deployment

# Check all Pods
kubectl get pods

Docker Build and Push

Local Build (for Minikube)

# Use Minikube's Docker environment
eval $(minikube docker-env)

# Build image
docker build -t python-bookstore:v1 .

# List images
docker images | grep python-bookstore

Push to Azure Container Registry (Optional)

# Login to ACR
az acr login --name <your-registry-name>

# Tag the image
docker tag python-bookstore:v1 <your-registry>.azurecr.io/python-bookstore:v1

# Push image
docker push <your-registry>.azurecr.io/python-bookstore:v1

Kubernetes Deployment

Deploy All Resources with Single Command

# Deploy all YAML files in k8s directory
kubectl apply -f k8s/

# Check Deployment status
kubectl get deployments
kubectl get statefulsets
kubectl get pods
kubectl get svc

Delete Resources (Optional)

# Delete all resources
kubectl delete -f k8s/

# Or individually
kubectl delete deployment flask-app
kubectl delete statefulset mongodb
kubectl delete service flask-service mongodb-service
kubectl delete secret mongodb-secret
kubectl delete configmap flask-config

API Endpoints

1. Health Check

GET - Check system status

curl http://localhost:8000/

Expected Response:

{
  "message": "Python Bookstore API is Running!",
  "status": "OK",
  "database": "Connected",
  "timestamp": "2025-01-06T10:30:00.000000"
}

2. Add Book (CREATE)

POST - Add new book

curl -X POST http://localhost:8000/books \
  -H "Content-Type: application/json" \
  -d '{"title": "1984", "author": "George Orwell"}'

Expected Response:

{
  "message": "Book added successfully",
  "id": "507f1f77bcf86cd799439011",
  "book": {
    "title": "1984",
    "author": "George Orwell",
    "created_at": "2025-01-06T10:30:00.000000"
  }
}

3. List All Books (READ)

GET - Get all books

curl http://localhost:8000/books

Expected Response:

{
  "count": 1,
  "books": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "title": "1984",
      "author": "George Orwell",
      "created_at": "2025-01-06T10:30:00.000000"
    }
  ]
}

4. Get Specific Book (READ by ID)

GET - Get book by ID

curl http://localhost:8000/books/507f1f77bcf86cd799439011

5. Update Book (UPDATE)

PUT - Update book

curl -X PUT http://localhost:8000/books/507f1f77bcf86cd799439011 \
  -H "Content-Type: application/json" \
  -d '{"title": "1984 - Revised Edition", "author": "George Orwell"}'

6. Delete Book (DELETE)

DELETE - Delete book

curl -X DELETE http://localhost:8000/books/507f1f77bcf86cd799439011

Testing

Test Script

Save this as test.sh and run with bash test.sh:

#!/bin/bash
# To run this test script: bash test.sh

API_URL="http://localhost:8000"

# 1. Health Check
echo "Running health check..."
curl -s $API_URL/

# 2. Add Book
echo -e "\n\nAdding book..."
RESPONSE=$(curl -s -X POST $API_URL/books \
  -H "Content-Type: application/json" \
  -d '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}')
echo $RESPONSE
BOOK_ID=$(echo $RESPONSE | grep -o '"id":"[^"]*' | cut -d'"' -f4)

# 3. List All Books
echo -e "\n\nListing all books..."
curl -s $API_URL/books

# 4. Get Specific Book
echo -e "\n\nGetting specific book..."
curl -s $API_URL/books/$BOOK_ID

# 5. Update Book
echo -e "\n\nUpdating book..."
curl -s -X PUT $API_URL/books/$BOOK_ID \
  -H "Content-Type: application/json" \
  -d '{"title": "The Great Gatsby - Classic Edition", "author": "F. Scott Fitzgerald"}'

# 6. Delete Book
echo -e "\n\nDeleting book..."
curl -s -X DELETE $API_URL/books/$BOOK_ID

Troubleshooting

1. MongoDB Pod is Not Ready

# Check Pod logs
kubectl logs mongodb-0

# See Pod description
kubectl describe pod mongodb-0

# Recreate StatefulSet
kubectl delete statefulset mongodb
kubectl apply -f k8s/mongodb-statefulset.yaml

2. Flask Pod Cannot Connect to MongoDB

# Check Flask logs
kubectl logs deployment/flask-app

# Test network connectivity between Pods
kubectl exec -it <flask-pod-name> -- ping mongodb-service

# Verify ConfigMap
kubectl get configmap flask-config -o yaml

3. Cannot Access Service

# Check Service IP address
kubectl get svc flask-service

# Get LoadBalancer URL on Minikube
minikube service flask-service

# Use port forwarding (alternative)
kubectl port-forward svc/flask-service 8000:80

4. Image Not Found

# Check Docker images
docker images | grep python-bookstore

# Is Minikube Docker environment selected?
eval $(minikube docker-env)
docker build -t python-bookstore:v1 .

Information

  • Course: Database Systems and Cloud Computing
  • Department: Artificial Intelligence Engineering
  • University: Bahçeşehir University
  • Assignment Number: Project 1
  • Due Date: January 8, 2026
  • Student Name: Aleyna Dede
  • Student ID: 2102664

Helpful Commands

# Show all Pods
kubectl get pods -A

# Show all Services
kubectl get svc -A

# Access Pod shell
kubectl exec -it <pod-name> -- /bin/bash

# Open Minikube dashboard
minikube dashboard

# Watch Kubernetes events (real-time)
kubectl get events -w

# Restart Deployment
kubectl rollout restart deployment/flask-app

About

Containerized Flask REST API connected to MongoDB and deployed on Kubernetes using Docker, ConfigMaps, Secrets and StatefulSets.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors