A cloud-native, microservices-based Library Management System built with Node.js, Express, MongoDB, and Docker. The system demonstrates modern distributed architecture patterns with API Gateway routing, Kubernetes orchestration, and service-to-service communication.
- Quick Start
- Architecture Overview
- Services
- Technology Stack
- Prerequisites
- Setup & Installation
- Running the Project
- Load Balancing
- API Documentation
- Environment Variables
- Project Structure
- Development Workflow
Get the Library System running in 3 minutes:
# 1. Clone and navigate to project
git clone <repository-url>
cd Library_System
# 2. Create environment file
cat > .env << EOF
JWT_SECRET=your-secret-key-change-in-production
MONGO_URI=mongodb://mongo:27017/library_system
DOCKER_USERNAME=your-docker-username
EOF
# 3. Build and start all services
docker compose up --build
# 4. Access the API
# Gateway: http://localhost:4000# 1. Create namespace and secrets
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/secrets.yaml
kubectl apply -f k8s/configmap.yaml
# 2. Deploy databases
kubectl apply -f k8s/mongo.yaml
kubectl apply -f k8s/redis.yaml
# 3. Deploy services
kubectl apply -f k8s/auth-service.yaml
kubectl apply -f k8s/book-service.yaml
kubectl apply -f k8s/borrow-service.yaml
kubectl apply -f k8s/api-gateway.yaml
# 4. Deploy ingress
kubectl apply -f k8s/ingress.yaml
# 5. Get API endpoint
kubectl get ingress -n library-system# Install all dependencies
npm install --prefix API_Gateway
npm install --prefix Auth_service
npm install --prefix Book_service
npm install --prefix Borrow_service
npm install --prefix shared
# Start MongoDB and Redis
mongod &
redis-server &
# Start each service in separate terminals
npm run dev --prefix Auth_service # Port 3000
npm start --prefix Book_service # Port 5001
npm start --prefix Borrow_service # Port 5000
npm start --prefix API_Gateway # Port 4000# 1. Register a user
curl -X POST http://localhost:4000/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"user@test.com","password":"test123","name":"Test User","role":"member"}'
# 2. Login
curl -X POST http://localhost:4000/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@test.com","password":"test123"}'
# 3. Get books (replace TOKEN with the token from login response)
curl -X GET http://localhost:4000/books \
-H "Authorization: Bearer TOKEN"For detailed setup instructions, see Setup & Installation.
This is a microservices architecture with the following components:
βββββββββββββββ
β Client β
ββββββββ¬βββββββ
β
βΌ
ββββββββββββββββββββ
β API Gateway β
β (Express.js) β
ββββββββ¬βββββββ¬βββββ¬βββββββββ
β β β β
βΌ βΌ βΌ βΌ
ββββββββββββββ βββββββββββββββ ββββββββββββββ
β Auth β β Book β β Borrow β
β Service β β Service β β Service β
β (Pods) β β (Pods) β β (Pods) β
ββββββββββββββ βββββββββββββββ ββββββββββββββ
β β β
ββββββββββββββββΌβββββββββββββββ
βΌ
ββββββββββββββββββββ
β MongoDB β
β (StatefulSet) β
ββββββββββββββββββββ
ββββββββββββββββββββ
β Redis β
β (Deployment) β
ββββββββββββββββββββ
- API Gateway Pattern: Single entry point for all client requests
- Kubernetes Orchestration: Container orchestration with auto-scaling
- Service-to-Service Communication: Direct HTTP calls between services
- Authentication: JWT token-based authentication with role-based access control (RBAC)
- Containerization: Docker containers for each service
- Caching: Redis for performance optimization in Book Service
- Data Persistence: MongoDB with StatefulSet for data durability
- Service Discovery: Kubernetes DNS for automatic service discovery
- Load Balancing: Nginx (Docker), Kubernetes Services (K8s)
Purpose: Single entry point for all client requests; handles routing, authentication verification, and role-based authorization.
Responsibilities:
- Route requests to appropriate services
- Verify JWT tokens
- Enforce role-based access control
- Handle proxy errors gracefully
Technology: Express.js, http-proxy, JWT
Purpose: User authentication and registration management.
Endpoints:
POST /auth/register- Register a new userPOST /auth/login- User login with JWT token generationPOST /auth/reset-password- Reset user password
Features:
- User registration with email validation
- Secure password hashing with bcrypt
- JWT token generation
- Password reset functionality
- Role assignment (member/librarian)
Technology: Express.js, MongoDB, JWT, Bcrypt
Purpose: Manage library book catalog with search, filtering, and book operations.
Routes:
GET /books- Retrieve all books (cached with Redis)GET /books/search- Search and filter booksGET /books/:bookId- Get specific book detailsPOST /books- Add new book (Librarian only)PATCH /books/:bookId- Update book details (Librarian only)
Features:
- Redis caching for frequently accessed data
- Role-based operations (members view, librarians manage)
- Book inventory management
- Search and filtering capabilities
- Book metadata (title, author, ISBN, count, etc.)
Technology: Express.js, MongoDB, Redis (ioredis), JWT
Load Balancing:
- Docker: 2 instances behind Nginx load balancer (round-robin)
- Kubernetes: Multiple replicas managed by Kubernetes Service
Purpose: Manage book borrowing and return operations for members.
Endpoints:
POST /borrow- Create a borrow recordGET /borrow- View borrowing historyPATCH /borrow/:borrowId- Return a book
Features:
- Create borrow transactions
- Track borrowed books
- Manage due dates
- Process book returns
- Communicate with Book Service for inventory updates
Technology: Express.js, MongoDB, JWT
Location: shared/middleware/
Components:
verifyToken.js- JWT token validation middlewareauthorizeRole.js- Role-based access control middleware
Purpose: Centralized authentication and authorization logic used across services.
Purpose: Primary data persistence layer for all services.
Kubernetes: StatefulSet with persistent volumes for data durability
Purpose: Caching and session storage for performance optimization.
Kubernetes: Deployment with persistent volume for cache data
| Layer | Technology |
|---|---|
| API Gateway | Express.js, http-proxy |
| Services | Node.js, Express.js 5.x |
| Database | MongoDB 9.x |
| Caching | Redis |
| Authentication | JWT (jsonwebtoken), Bcrypt |
| Containerization | Docker, Docker Compose |
| Orchestration | Kubernetes 1.28+ |
| Load Balancing | Nginx (Docker), Kubernetes Services (K8s) |
| Environment Management | dotenv, ConfigMaps, Secrets |
Before starting, ensure you have:
- Node.js (v18+)
- npm (v8+)
- Docker (v20.10+)
- Docker Compose (v1.29+) - for Docker deployment
- Kubernetes (v1.28+) - for K8s deployment
- kubectl (v1.28+) - Kubernetes CLI
- MongoDB (v5.0+) - or use Docker/Kubernetes
- Redis (v6.0+) - or use Docker/Kubernetes
- Git
git clone <repository-url>
cd Library_SystemInstall dependencies for all services:
# API Gateway
cd API_Gateway && npm install && cd ..
# Auth Service
cd Auth_service && npm install && cd ..
# Book Service
cd Book_service && npm install && cd ..
# Borrow Service
cd Borrow_service && npm install && cd ..
# Shared middleware
cd shared && npm install && cd ..Create a .env file in the root directory with the following variables:
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this
# MongoDB Connection
MONGO_URI=mongodb://localhost:27017/library_system
# Docker Registry (if using Docker Hub)
DOCKER_USERNAME=your-docker-usernameFor development without Docker, also add:
# Auth Service
PORT=3000
# Book Service
PORT=5001
REDIS_HOST=localhost
REDIS_PORT=6379
# Borrow Service
PORT=5000
BOOK_SERVICE_URL=http://localhost:5001cat > .env << EOF
JWT_SECRET=your-super-secret-jwt-key-change-this
MONGO_URI=mongodb://localhost:27017/library_system
DOCKER_USERNAME=your-docker-username
EOF# Build and start all services
docker compose up --build
# Run in background
docker compose up -d --build
# View logs
docker compose logs -f
# Stop services
docker compose downThe API Gateway will be available at http://localhost:4000
Note: Docker Compose includes an Nginx reverse proxy that load balances the Book Service (2 instances).
- Kubernetes cluster running (local: Minikube, Kind; cloud: EKS, GKE, AKS)
- kubectl configured and connected to your cluster
- Persistent volume provisioner available (for MongoDB and Redis)
Step 1: Create Namespace
kubectl apply -f k8s/namespace.yamlStep 2: Create Secrets and ConfigMaps
kubectl apply -f k8s/secrets.yaml
kubectl apply -f k8s/configmap.yamlStep 3: Deploy Databases
kubectl apply -f k8s/mongo.yaml
kubectl apply -f k8s/redis.yaml
# Wait for databases to be ready
kubectl rollout status statefulset/mongo -n library-system
kubectl rollout status deployment/redis -n library-systemStep 4: Deploy Microservices
kubectl apply -f k8s/auth-service.yaml
kubectl apply -f k8s/book-service.yaml
kubectl apply -f k8s/borrow-service.yaml
kubectl apply -f k8s/api-gateway.yaml
# Wait for services to be ready
kubectl rollout status deployment/auth-service -n library-system
kubectl rollout status deployment/book-service -n library-system
kubectl rollout status deployment/borrow-service -n library-system
kubectl rollout status deployment/api-gateway -n library-systemStep 5: Deploy Ingress
kubectl apply -f k8s/ingress.yaml
# Get Ingress URL
kubectl get ingress -n library-system
kubectl describe ingress api-gateway-ingress -n library-system# Get service endpoints
kubectl get svc -n library-system
# Port forward to access locally (alternative to Ingress)
kubectl port-forward svc/api-gateway 4000:4000 -n library-system
# Then access at http://localhost:4000# View pod status
kubectl get pods -n library-system
# View pod logs
kubectl logs -f pod/auth-service-xyz -n library-system
# Describe pod for events
kubectl describe pod auth-service-xyz -n library-system
# Access pod shell
kubectl exec -it pod/auth-service-xyz -n library-system -- sh
# Check resource usage
kubectl top pods -n library-system# Scale auth-service to 5 replicas
kubectl scale deployment auth-service --replicas=5 -n library-system
# Check HPA (Horizontal Pod Autoscaler)
kubectl get hpa -n library-system
kubectl describe hpa book-service-hpa -n library-system# Delete all resources in namespace
kubectl delete namespace library-system
# Or delete individual components
kubectl delete -f k8s/cd Auth_service
npm install
npm run dev
# Runs on http://localhost:3000cd Book_service
npm install
npm start
# Runs on http://localhost:5001cd Borrow_service
npm install
npm start
# Runs on http://localhost:5000cd API_Gateway
npm install
npm start
# Runs on http://localhost:4000Prerequisites for local setup:
- Ensure MongoDB is running:
mongod - Ensure Redis is running:
redis-server
The system uses different load balancing strategies depending on the deployment method:
What: Nginx reverse proxy distributes traffic across multiple Book Service instances
How it works:
Borrow Service β http://nginx:80 β [Nginx Round-Robin] β Book Service 1
β Book Service 2
Configuration (nginx.conf):
upstream book_service {
server book_service_1:3001;
server book_service_2:3001;
}
server {
listen 80;
location / {
proxy_pass http://book_service;
}
}Usage in docker-compose.yml:
- Nginx service runs on port 8080
- Borrow Service calls:
BOOK_SERVICE_URL=http://nginx:80 - Nginx forwards requests to Book Service instances
Benefits:
- Simple round-robin load balancing
- Easy to add/remove book service instances
- Traffic distribution across replicas
What: Kubernetes Services provide built-in load balancing (no Nginx needed)
How it works:
Borrow Service β http://book-service:3001 β [K8s Service] β Book Service Pod 1
β Book Service Pod 2
β Book Service Pod N
Service Configuration (k8s/book-service.yaml):
apiVersion: v1
kind: Service
metadata:
name: book-service
spec:
selector:
app: book-service
ports:
- port: 3001
targetPort: 3001Usage in services:
- Services use Kubernetes DNS:
http://book-service:3001 - Kubernetes automatically routes to available pods
- Default algorithm: round-robin
Benefits:
- Native Kubernetes load balancing
- Automatic failover if pods crash
- Service discovery via DNS
- HPA automatically scales pods based on metrics
- No external load balancer needed
| Feature | Docker (Nginx) | Kubernetes |
|---|---|---|
| Load Balancer | Nginx container | Kubernetes Service |
| Discovery | Manual DNS | Automatic DNS |
| Scaling | Manual pod addition | HPA auto-scaling |
| Failover | Manual | Automatic |
| Config | nginx.conf file | Service manifest |
| Setup Complexity | Simple | More infrastructure |
Register New User
POST /auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123",
"name": "John Doe",
"role": "member" // or "librarian"
}
Response: 201 Created
{
"message": "User registered successfully",
"user": {
"_id": "...",
"email": "user@example.com",
"name": "John Doe",
"role": "member"
}
}Login
POST /auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123"
}
Response: 200 OK
{
"message": "Login successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}Reset Password
POST /auth/reset-password
Content-Type: application/json
{
"email": "user@example.com",
"newPassword": "newSecurePassword123"
}
Response: 200 OK
{
"message": "Password reset successfully"
}Get All Books
GET /books
Authorization: Bearer <token>
Response: 200 OK
[
{
"_id": "...",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"isbn": "978-0743273565",
"count": 5,
"availableCount": 3
}
]Search Books
GET /books/search?query=gatsby&author=Fitzgerald
Authorization: Bearer <token>
Response: 200 OK
[
{
"_id": "...",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"isbn": "978-0743273565",
"count": 5,
"availableCount": 3
}
]Get Book by ID
GET /books/:bookId
Authorization: Bearer <token>
Response: 200 OK
{
"_id": "...",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"isbn": "978-0743273565",
"count": 5,
"availableCount": 3
}Add New Book (Librarian only)
POST /books
Authorization: Bearer <token>
Content-Type: application/json
{
"title": "1984",
"author": "George Orwell",
"isbn": "978-0451524935",
"count": 10
}
Response: 201 Created
{
"_id": "...",
"title": "1984",
"author": "George Orwell",
"isbn": "978-0451524935",
"count": 10,
"availableCount": 10
}Update Book (Librarian only)
PATCH /books/:bookId
Authorization: Bearer <token>
Content-Type: application/json
{
"count": 15,
"title": "1984 - Updated Edition"
}
Response: 200 OK
{
"_id": "...",
"title": "1984 - Updated Edition",
"author": "George Orwell",
"isbn": "978-0451524935",
"count": 15,
"availableCount": 12
}Borrow a Book
POST /borrow
Authorization: Bearer <token>
Content-Type: application/json
{
"bookId": "...",
"memberId": "...",
"dueDate": "2026-07-21"
}
Response: 201 Created
{
"_id": "...",
"bookId": "...",
"memberId": "...",
"borrowDate": "2026-06-21",
"dueDate": "2026-07-21",
"status": "active"
}Get Borrow History
GET /borrow
Authorization: Bearer <token>
Response: 200 OK
[
{
"_id": "...",
"bookId": "...",
"memberId": "...",
"borrowDate": "2026-06-21",
"dueDate": "2026-07-21",
"status": "active"
}
]Return a Book
PATCH /borrow/:borrowId
Authorization: Bearer <token>
Content-Type: application/json
{
"returnDate": "2026-06-25",
"status": "returned"
}
Response: 200 OK
{
"_id": "...",
"bookId": "...",
"memberId": "...",
"borrowDate": "2026-06-21",
"dueDate": "2026-07-21",
"returnDate": "2026-06-25",
"status": "returned"
}| Variable | Description | Example |
|---|---|---|
JWT_SECRET |
Secret key for JWT token signing | your-super-secret-key |
MONGO_URI |
MongoDB connection string | mongodb://localhost:27017/library_system |
DOCKER_USERNAME |
Docker Hub username for image registry | your-docker-username |
ConfigMap (k8s/configmap.yaml):
MONGO_URI:mongodb://mongo:27017/library_systemREDIS_HOST:redisREDIS_PORT:6379
Secrets (k8s/secrets.yaml):
JWT_SECRET: Base64 encoded secret key
Auth Service & All Services:
MONGO_URI- MongoDB connection stringJWT_SECRET- JWT token secret
Book Service:
REDIS_HOST- Redis server host (default:redis)REDIS_PORT- Redis server port (default:6379)
Borrow Service:
- Docker:
BOOK_SERVICE_URL=http://nginx:80(routes through Nginx) - Kubernetes:
BOOK_SERVICE_URL=http://book-service:3001(routes through K8s Service)
Library_System/
βββ API_Gateway/ # API Gateway Service
β βββ Dockerfile
β βββ index.js
β βββ package.json
β βββ README.md
β
βββ Auth_service/ # Authentication Service
β βββ Dockerfile
β βββ server.js
β βββ package.json
β βββ config/
β βββ models/
β βββ routes/
β
βββ Book_service/ # Book Management Service
β βββ Dockerfile
β βββ server.js
β βββ package.json
β βββ config/
β βββ models/
β βββ controllers/
β βββ routes/
β
βββ Borrow_service/ # Borrow Management Service
β βββ Dockerfile
β βββ server.js
β βββ package.json
β βββ config/
β βββ models/
β βββ controllers/
β βββ routes/
β
βββ shared/ # Shared Middleware
β βββ package.json
β βββ middleware/
β
βββ k8s/ # Kubernetes Manifests
β βββ README.md
β βββ namespace.yaml
β βββ secrets.yaml
β βββ configmap.yaml
β βββ mongo.yaml
β βββ redis.yaml
β βββ auth-service.yaml
β βββ book-service.yaml
β βββ borrow-service.yaml
β βββ api-gateway.yaml
β βββ ingress.yaml
β
βββ docker-compose.yml # Docker Compose (with Nginx)
βββ nginx.conf # Nginx load balancer config
βββ .env # Environment variables
βββ .env.example
βββ README.md
βββ .gitignore
npm install --prefix API_Gateway
npm install --prefix Auth_service
npm install --prefix Book_service
npm install --prefix Borrow_service
npm install --prefix shared# Terminal 1
npm run dev --prefix Auth_service
# Terminal 2
npm start --prefix Book_service
# Terminal 3
npm start --prefix Borrow_service
# Terminal 4
npm start --prefix API_Gateway# Register
curl -X POST http://localhost:4000/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password123","name":"John Doe","role":"member"}'
# Login
curl -X POST http://localhost:4000/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password123"}'
# Get Books
curl -X GET http://localhost:4000/books \
-H "Authorization: Bearer <TOKEN>"# Build and start
docker compose up --build
# View logs
docker compose logs -f
# Stop
docker compose down# Deploy
kubectl apply -f k8s/
# Check status
kubectl get pods -n library-system
# View logs
kubectl logs -f deployment/auth-service -n library-system
# Port forward
kubectl port-forward svc/api-gateway 4000:4000 -n library-system
# Clean up
kubectl delete namespace library-systemDocker Compose logs:
docker compose logs -f auth_service
docker compose logs -f book_service_1
docker compose logs -f nginxKubernetes pod logs:
kubectl logs -f pod/auth-service-xyz -n library-system
kubectl exec -it pod/auth-service-xyz -n library-system -- shβ
Microservices Architecture - Independent, scalable services
β
API Gateway Pattern - Centralized request routing
β
JWT Authentication - Secure token-based auth
β
Role-Based Access Control - Member and Librarian roles
β
Load Balancing - Nginx (Docker) + Kubernetes Services (K8s)
β
Auto-scaling - HPA in Kubernetes
β
Service Discovery - DNS-based discovery
β
Caching Layer - Redis for performance
β
Data Persistence - MongoDB with StatefulSet
β
Docker Containerization - Consistent deployment
β
Error Handling - Graceful error responses
- JWT Secret: Change in production to a strong, random value
- MongoDB Connection: Ensure MongoDB is running and accessible
- Redis Cache: Book Service requires Redis for optimal performance
- Nginx (Docker only): Used for load balancing Book Service instances
- Kubernetes: Uses native Services for load balancing (no Nginx needed)
- Port Mapping: API Gateway on 4000, other services internal
- Create a feature branch:
git checkout -b feature/your-feature - Commit changes:
git commit -am 'Add your feature' - Push to branch:
git push origin feature/your-feature - Submit a pull request
This project is licensed under the ISC License.
Port Already in Use
lsof -i :4000
kill -9 <PID>MongoDB Connection Error
mongod
# or
docker run -d -p 27017:27017 mongoRedis Connection Error
redis-server
# or
docker run -d -p 6379:6379 redisNginx not forwarding requests
docker compose logs nginx
docker compose exec nginx curl http://book_service_1:3001Pod Not Starting
kubectl describe pod <pod-name> -n library-system
kubectl logs <pod-name> -n library-systemService Not Accessible
kubectl get svc -n library-system
kubectl port-forward svc/api-gateway 4000:4000 -n library-systemPersistent Volume Issues
kubectl get pvc -n library-system
kubectl describe pvc <pvc-name> -n library-systemLast Updated: July 6, 2026
Version: 2.0.0 (with Kubernetes support)
For issues or questions, please open an issue on the repository.