Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Live reloading πŸ“¦ IMS (Inventory Management System) with Redis and Web sockets 🌐 + fully optimized to deploy πŸš€ with docker-compose 🐳

Notifications You must be signed in to change notification settings

kevinThulnith/devops-project

Open more actions menu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Django DRF JWT PostgreSQL Redis Vite React Tailwind Axios NodeJS npm Docker Nginx

DevOps Project - Live Reloading Inventory Management System

The project includes a complete Docker Compose setup for easy deployment and development with version 3.0 configuration | WebSocket | Live reloading. With Django backend and React frontend styled with Tailwind CSS.

πŸ› οΈ Tech Stack

🐍 Backend

  • Django 5.2+ - 🌐 Web framework
  • Django REST Framework - πŸ”§ API development
  • Django Channels - πŸ“‘ WebSocket support
  • Daphne - πŸš€ ASGI server for WebSockets
  • Redis - πŸ’Ύ Channel layer backend
  • Simple JWT - πŸ” Authentication
  • Pillow - πŸ–ΌοΈ Image processing

βš›οΈ Frontend

  • React 18+ - 🎨 UI library
  • Vite 7.0+ - ⚑ Build tool and dev server
  • Tailwind CSS - πŸ’… Styling framework
  • Framer Motion - 🎬 Animations
  • Axios - πŸ“¬ HTTP client
  • React Router - πŸ—ΊοΈ Navigation
  • JWT Decode - πŸ”“ Token handling

πŸ—„οΈ Database & Infrastructure

  • PostgreSQL (production) or SQLite (development) - πŸ“Š Database
  • Redis - πŸ“‘ WebSocket channel layer & caching
  • WhiteNoise - πŸ“ Static file serving

🐳 DevOps & Deployment

  • Docker - 🐳 Containerization platform
  • Docker Compose 3.0 - πŸ”§ Multi-container orchestration
  • Nginx - 🌐 Reverse proxy and load balancer
  • Alpine Linux - πŸ”οΈ Lightweight container base images

πŸ“‹ Prerequisites

For Development (Local Setup)

  • 🐍 Python 3.13+
  • 🟒 Node.js 16+ and npm
  • πŸ”΄ Redis server (for WebSocket channel layer)
  • πŸ“ Git

For Docker Deployment

  • 🐳 Docker Engine 20.0+
  • πŸ”§ Docker Compose 3.0+
  • πŸ“ Git

πŸ› οΈ Development Environment Setup

πŸ“ Project Structure

πŸ“‚ LR 3.0/
β”œβ”€β”€ πŸ”§ pyproject.toml          # Python dependencies & project config
β”œβ”€β”€ πŸ”’ uv.lock                 # Dependency lock file
β”œβ”€β”€ πŸ“– README.md               # Project documentation
β”œβ”€β”€ πŸ“‚ backend/                # Django application
β”‚   β”œβ”€β”€ πŸ—„οΈ db.sqlite3          # Development database
β”‚   β”œβ”€β”€ βš™οΈ manage.py           # Django CLI
β”‚   └── πŸ“‚ api/                # Main API app
└── πŸ“‚ frontend/               # React application
    β”œβ”€β”€ πŸ“¦ package.json        # Node.js dependencies
    β”œβ”€β”€ ⚑ vite.config.js       # Vite configuration
    └── 🎨 tailwind.config.js  # Tailwind setup

πŸš€ Quick Start Commands

Clone Git Repository

git clone https://github.com/kevinThulnith/devops-project.git

# Go to project directory
cd devops-project

# Go to main branch
git checkout main

Backend Setup πŸ”™

  • Create .env file in backend/ directory and add this configuration:
DEBUG=True
REDIS_PORT=6379
REDIS_HOST=127.0.0.1
DATABASE_URL=sqlite:///db.sqlite3
SECRET_KEY="your_secret_key_here_generate_a_secure_one"
  • Redis Installation Required: Install Redis on your local device for WebSocket functionality
# If uv is not installed locally
pip install uv

# Install Python dependencies
uv sync

# Activate virtual environment (Windows PowerShell)
.\.venv\Scripts\Activate.ps1

# Navigate to backend directory
cd backend

# Run database migrations
py .\manage.py migrate

# Start backend server with Daphne (ASGI server)
daphne -b 0.0.0.0 -p 8000 backend.asgi:application

# Alternative: If virtual environment not activated
uv run daphne -b 0.0.0.0 -p 8000 backend.asgi:application

Frontend Setup 🎨

# Install Node.js dependencies
cd frontend
npm i

# Start development server with hot reload
npm run dev

# Create production build files
npm run build

# Start with network access (accessible from other devices)
npm run host

πŸ§ͺ Testing WebSocket Functionality

A test HTML file (ws_test.html) is included for WebSocket testing:

  1. πŸš€ Start the Django server
  2. 🌐 Open ws_test.html in a browser
  3. βž• Create/update/delete products in Django Admin
  4. πŸ‘€ See real-time updates in the test page

Production Setup - 🐳 Docker Deployment

For a complete containerized deployment with all services, check out the docker-compose branch which includes:

  • 🐍 Backend Container: Django application with PostgreSQL support
  • βš›οΈ Frontend Container: React application served with Nginx
  • 🐘 PostgreSQL Database: Fully configured database container
  • 🌐 Nginx Proxy: Load balancer and reverse proxy
  • πŸ”΄ Redis Server: Cache and WebSocket channel layer

πŸš€ Quick Docker Setup

  1. πŸ“‹ Prerequisites:

    • Docker Engine 20.0+
    • Docker Compose 3.0+
  2. βš™οΈ Environment Configuration:

    Create a .env.prod file in the project root:

    # Database Configuration
    POSTGRES_DB=devops_inventory
    POSTGRES_USER=devops_user
    POSTGRES_PASSWORD=your_secure_password
    DATABASE_URL=postgresql://devops_user:your_secure_password@lr-database:5432/devops_inventory
    
    # Django Configuration
    DEBUG=False
    DJANGO_SECRET_KEY=your-super-secret-key-here
    ALLOWED_HOSTS=localhost,127.0.0.1,lr-backend
    
    # Redis Configuration
    REDIS_HOST=lr-redis
    REDIS_PORT=6379
  3. πŸƒβ€β™‚οΈ Start All Services:

    # Change branch
    git checkout docker-compose
    
    # In root dir
    docker-compose up -d
  4. πŸ“Š Check Service Status:

    docker-compose ps

🌐 Service Access Points

πŸ”§ Docker Services Overview

Service Description Image/Build Ports Dependencies
lr-proxy 🌐 Nginx reverse proxy nginx:1.25-alpine-slim 80:80 frontend, backend
lr-frontend βš›οΈ React application Custom build 5173:5173 -
lr-backend 🐍 Django API server Custom build 8000:8000 database, redis
lr-database 🐘 PostgreSQL database postgres:14-alpine 5432:5432 -
lr-redis 🧠 Redis cache & pub/sub redis:7-alpine 6379:6379 -

✨ Features

🎯 Core Functionality

  • πŸ“¦ Product Management: CRUD operations for inventory items with image uploads
  • ⚑ Real-time Updates: Live WebSocket connections for instant product changes
  • πŸ” User Authentication: JWT-based auth with automatic token refresh
  • πŸ“± Responsive UI: Modern React interface with Tailwind CSS and Framer Motion animations
  • πŸ” Advanced Filtering: Search, category filtering, and sorting capabilities

βš™οΈ Technical Features

  • πŸ›‘οΈ Custom JWT WebSocket Middleware: Secure WebSocket authentication using JWT tokens
  • πŸ“‘ Django Signals Integration: Automatic real-time notifications on model changes
  • 🚧 Protected Routes: Client-side route protection with automatic redirects
  • πŸ–ΌοΈ Image Handling: Product image uploads with media file management
  • 🌐 CORS Support: Configured for cross-origin frontend-backend communication

🐳 DevOps Features

  • 🐳 Full Docker Containerization: Complete multi-container setup with Docker Compose 3.0
  • 🌐 Nginx Reverse Proxy: Load balancing and SSL termination ready
  • πŸ“¦ Multi-stage Builds: Optimized Docker images for production deployment
  • πŸ”§ Environment Configuration: Separate configurations for development and production
  • πŸ“Š Service Orchestration: Automated service dependency management
  • πŸ’Ύ Persistent Data Volumes: Configured volumes for database and Redis data persistence
  • πŸ”„ Health Checks: Container health monitoring and automatic restarts
  • 🌍 Network Isolation: Secure inter-service communication via Docker networks

πŸ“š API Documentation

πŸ”— Main Endpoints

Method Endpoint Description Authentication
POST /api/user/register/ User registration ❌ Public
POST /api/token/ User login (get JWT token) ❌ Public
POST /api/token/refresh/ Refresh JWT token πŸ” Required
POST /api/token/blacklist/ Logout (blacklist token) πŸ” Required
GET /api/user/ Get current user info πŸ” Required
GET /api/products/ List all products πŸ” Required
POST /api/products/ Create new product πŸ” Required
GET /api/products/{id}/ Get product details πŸ” Required
PUT /api/products/{id}/ Update product (full) πŸ” Required (Owner only)
PATCH /api/products/{id}/ Update product (partial) πŸ” Required (Owner only)
DELETE /api/products/{id}/ Delete product πŸ” Required (Owner only)
GET /api/products/my_products/ Get current user's products πŸ” Required

πŸ” Product Filtering & Search

The /api/products/ endpoint supports advanced filtering:

Parameter Description Example
search Search in name and description ?search=laptop
category Filter by category ?category=electronics
is_active Filter by active status ?is_active=true
ordering Sort by fields ?ordering=-created_at

Available Categories: books, other, sports, clothing, home, electronics

Sortable Fields: name, price, quantity, created_at (use - prefix for descending)

πŸ”Œ WebSocket Endpoints

Endpoint Description Authentication
/ws/products/ Real-time product updates πŸ” JWT Required

πŸ“‹ Example API Usage

// User Registration
const registerResponse = await fetch("/api/user/register/", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    username: "newuser",
    password: "securepassword",
    email: "user@example.com",
  }),
});

// User Login (Get JWT Token)
const loginResponse = await fetch("/api/token/", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username: "user", password: "pass" }),
});

const tokens = await loginResponse.json();
// Response: { "access": "...", "refresh": "..." }

// Get Current User Info
const userInfo = await fetch("/api/user/", {
  headers: { Authorization: `Bearer ${tokens.access}` },
});

// Create Product with Image
const productData = {
  name: "Gaming Laptop",
  description: "High-performance gaming laptop with RGB keyboard",
  price: 1299.99,
  quantity: 5,
  category: "electronics",
  is_active: true,
};

const formData = new FormData();
Object.keys(productData).forEach((key) => {
  formData.append(key, productData[key]);
});
// Add image file
formData.append("image", imageFile);

const createResponse = await fetch("/api/products/", {
  method: "POST",
  headers: { Authorization: `Bearer ${tokens.access}` },
  body: formData,
});

// Search Products
const searchResponse = await fetch(
  "/api/products/?search=laptop&category=electronics&ordering=-created_at",
  {
    headers: { Authorization: `Bearer ${tokens.access}` },
  }
);

// Get My Products Only
const myProductsResponse = await fetch("/api/products/my_products/", {
  headers: { Authorization: `Bearer ${tokens.access}` },
});

// Refresh Token
const refreshResponse = await fetch("/api/token/refresh/", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ refresh: tokens.refresh }),
});

// Logout (Blacklist Token)
const logoutResponse = await fetch("/api/token/blacklist/", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${tokens.access}`,
  },
  body: JSON.stringify({ refresh: tokens.refresh }),
});

πŸ› Troubleshooting

πŸ”΄ Common Issues & Solutions

Backend Issues

Problem Solution
🚫 Redis connection failed Install and start Redis server locally
πŸ—„οΈ Database migration errors Run python manage.py migrate --run-syncdb
πŸ” JWT authentication fails Check SECRET_KEY in .env file
πŸ“ Static files not loading Run python manage.py collectstatic
🌐 CORS errors Verify CORS_ALLOWED_ORIGINS in settings

Frontend Issues

Problem Solution
πŸ“¦ npm install fails Delete node_modules and package-lock.json, then retry
⚑ Vite dev server won't start Check if port 5173 is available
πŸ”— API connection refused Ensure backend is running on port 8000
🎨 Tailwind styles not applying Run npm run build to regenerate CSS

Docker Issues

Problem Solution
🐳 Container build fails Check Docker is running and has sufficient resources
🌐 Services can't communicate Verify Docker network configuration
πŸ“Š Database connection fails Check environment variables in .env.prod
πŸ’Ύ Volume mount errors Ensure proper file permissions

πŸ”§ Debug Commands

# Check backend logs
docker-compose logs lr-backend

# Check database connection
python manage.py dbshell

# Test WebSocket connection
# Open browser console and run:
# const ws = new WebSocket('ws://localhost:8000/ws/products/');

# Check Redis connection
redis-cli ping

# Verify environment variables
docker-compose config

πŸš€ Performance Optimization

⚑ Backend Optimizations

  • Database Indexing: Add indexes to frequently queried fields
  • Query Optimization: Use select_related() and prefetch_related()
  • Caching: Implement Redis caching for frequently accessed data
  • Image Optimization: Compress uploaded images automatically

🎨 Frontend Optimizations

  • Code Splitting: Implement React lazy loading for routes
  • Image Optimization: Use WebP format and responsive images
  • Bundle Analysis: Use npm run build -- --analyze to check bundle size
  • Service Worker: Implement PWA features for offline support

πŸ”’ Security Best Practices

πŸ›‘οΈ Implemented Security Features

  • JWT Authentication with automatic token refresh
  • CORS Configuration for cross-origin requests
  • Input Validation on all API endpoints
  • File Upload Security with type and size restrictions
  • Environment Variables for sensitive configuration

πŸ” Additional Security Recommendations

# Generate secure SECRET_KEY
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

# Set strong database passwords
openssl rand -base64 32

# Enable HTTPS in production
# Update ALLOWED_HOSTS and SECURE_* settings

πŸ“Š Monitoring & Logging

πŸ“ˆ Available Endpoints for Monitoring

  • Django Admin: /admin/ - Administrative interface
  • API Root: /api/ - API endpoint listing
  • DRF Browsable API: /api-auth/ - Interactive API browser

πŸ”§ Manual Health Checks

# Test database connection
cd backend
python manage.py dbshell

# Test Redis connection (if Redis is running)
redis-cli ping

# Check Django application
curl http://localhost:8000/api/

# Test WebSocket connection
# Open browser console and run:
# const ws = new WebSocket('ws://localhost:8000/ws/products/');

πŸ“ Log Locations

πŸ“‚ Logs/
β”œβ”€β”€ 🐍 Django: /app/logs/django.log
β”œβ”€β”€ 🌐 Nginx: /var/log/nginx/
β”œβ”€β”€ 🐳 Docker: docker-compose logs [service_name]
└── πŸ”΄ Redis: /var/log/redis/redis-server.log

🀝 Contributing

We welcome contributions! Please follow these steps:

πŸ”„ Development Workflow

  1. 🍴 Fork the repository

  2. 🌿 Create a feature branch

    git checkout -b feature/amazing-feature
  3. πŸ’» Make your changes

  4. βœ… Run tests

    # Backend tests
    cd backend
    python manage.py test
    
    # Frontend tests (if available)
    cd frontend
    npm test
  5. πŸ“ Commit your changes

    git commit -m "Add: Amazing new feature"
  6. πŸš€ Push to your branch

    git push origin feature/amazing-feature
  7. πŸ“‹ Open a Pull Request

πŸ“‹ Code Style Guidelines

  • Python: Follow PEP 8 standards
  • JavaScript: Use ESLint configuration provided
  • Commit Messages: Use conventional commit format
    • feat: for new features
    • fix: for bug fixes
    • docs: for documentation changes
    • style: for formatting changes
    • refactor: for code refactoring

πŸ§ͺ Testing Requirements

  • Write unit tests for new features
  • Ensure all existing tests pass
  • Test WebSocket functionality manually
  • Verify Docker deployment works

πŸ“ž Support & Contact

πŸ’¬ Getting Help

πŸ“š Additional Resources

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“œ MIT License Summary

  • βœ… Commercial use allowed
  • βœ… Modification allowed
  • βœ… Distribution allowed
  • βœ… Private use allowed
  • ❌ No warranty provided
  • ❌ No liability assumed

πŸ™ Acknowledgments

  • Django Team for the amazing web framework
  • React Team for the powerful UI library
  • Tailwind CSS for the utility-first CSS framework
  • Docker for containerization technology
  • Redis for real-time functionality
  • All Contributors who helped improve this project

πŸ“ˆ Project Statistics

GitHub stars GitHub forks GitHub issues GitHub license


πŸŽ‰ Happy Coding! If you found this project helpful, please give it a ⭐ star on GitHub!

About

Live reloading πŸ“¦ IMS (Inventory Management System) with Redis and Web sockets 🌐 + fully optimized to deploy πŸš€ with docker-compose 🐳

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
Morty Proxy This is a proxified and sanitized view of the page, visit original site.