# Docker Deployment Guide - Finventory

**Developer:** Abdulaziz Alqudimi  
**Company:** Alqudimi Technology  
**Contact:** eng7mi@gmail.com  
**Repository:** https://github.com/Alqudimi/Finventory

## 📋 Overview

This guide explains how to deploy Finventory using Docker and Docker Compose for both development and production environments.

## 🚀 Quick Start

### Prerequisites

- Docker Engine 20.10 or higher
- Docker Compose 2.0 or higher
- 2GB RAM minimum (4GB recommended)
- 5GB free disk space

### Development Deployment

1. **Clone the repository**
```bash
git clone https://github.com/Alqudimi/Finventory.git
cd Finventory
```

2. **Configure environment variables**
```bash
cp .env.docker .env
# Edit .env with your settings
```

3. **Build and start services**
```bash
make build
make up
```

4. **Access the application**
- Application: http://localhost:5000
- Default credentials: admin / admin

## 🏭 Production Deployment

### 1. Prepare Environment

```bash
# Copy and configure environment file
cp .env.docker .env
nano .env  # Edit with production values

# Important: Change these values
# - POSTGRES_PASSWORD
# - SESSION_SECRET (use a strong random key)
# - GEMINI_API_KEY
```

### 2. Build Production Image

```bash
make prod-build
```

### 3. Deploy Services

```bash
make prod-up
```

### 4. Configure SSL (Optional but Recommended)

#### Using Let's Encrypt

```bash
# Initialize SSL certificates
make ssl-init

# Renew certificates (setup cron job for this)
make ssl-renew
```

#### Manual SSL Setup

1. Place your SSL certificates in `nginx/ssl/`:
   - `fullchain.pem`
   - `privkey.pem`

2. Uncomment the HTTPS server block in `nginx/conf.d/finventory.conf`

3. Restart Nginx:
```bash
docker-compose -f docker-compose.production.yml restart nginx
```

## 📁 Project Structure

```
Finventory/
├── Dockerfile                      # Development Dockerfile
├── Dockerfile.production           # Production Dockerfile with Gunicorn
├── docker-compose.yml              # Development compose file
├── docker-compose.production.yml   # Production compose file
├── .dockerignore                   # Docker ignore file
├── .env.docker                     # Docker environment template
├── Makefile                        # Convenient commands
├── nginx/
│   ├── nginx.conf                  # Main Nginx config
│   ├── conf.d/
│   │   └── finventory.conf        # Site configuration
│   └── ssl/                        # SSL certificates (create this)
└── scripts/
    ├── entrypoint.sh              # Container startup script
    ├── backup.sh                  # Database backup script
    └── restore.sh                 # Database restore script
```

## 🛠️ Available Commands

### Using Makefile

```bash
# Development
make build          # Build Docker images
make up             # Start containers
make down           # Stop containers
make logs           # View logs
make shell          # Access app shell
make test           # Run tests
make clean          # Clean up everything

# Production
make prod-build     # Build production images
make prod-up        # Start production
make prod-down      # Stop production
make prod-logs      # View production logs

# Database
make backup         # Backup database
make restore        # Restore database

# SSL
make ssl-init       # Initialize Let's Encrypt SSL
make ssl-renew      # Renew SSL certificates
```

### Using Docker Compose Directly

```bash
# Development
docker-compose up -d
docker-compose down
docker-compose logs -f

# Production
docker-compose -f docker-compose.production.yml up -d
docker-compose -f docker-compose.production.yml down
```

## 💾 Database Management

### Backup Database

**Automatic (using script):**
```bash
./scripts/backup.sh
```

**Manual:**
```bash
docker-compose exec -T db pg_dump -U finventory_user finventory > backup.sql
```

**Using Makefile:**
```bash
make backup
```

### Restore Database

**Using script:**
```bash
./scripts/restore.sh backups/backup_20250101_120000.sql.gz
```

**Manual:**
```bash
gunzip -c backup.sql.gz | docker-compose exec -T db psql -U finventory_user finventory
```

**Using Makefile:**
```bash
make restore
# Enter backup filename when prompted
```

### Automated Backups (Cron)

Add to crontab:
```bash
# Daily backup at 2 AM
0 2 * * * cd /path/to/Finventory && ./scripts/backup.sh >> /var/log/finventory_backup.log 2>&1
```

## 🔒 Security Best Practices

### 1. Environment Variables

- **Never commit .env files** to version control
- Use strong, random values for:
  - `POSTGRES_PASSWORD`
  - `SESSION_SECRET`
- Store `GEMINI_API_KEY` securely

### 2. Network Security

- Use HTTPS in production (SSL certificates)
- Configure firewall to only allow ports 80 and 443
- Keep Docker and images updated

### 3. Container Security

- Run containers as non-root user (already configured in production)
- Limit container resources
- Use Docker secrets for sensitive data in Swarm mode

### 4. Database Security

- Change default PostgreSQL password
- Restrict database access to app container only
- Regular backups
- Use encrypted connections

## 📊 Monitoring and Logs

### View Application Logs

```bash
# Real-time logs
docker-compose logs -f app

# Last 100 lines
docker-compose logs --tail=100 app

# All services
docker-compose logs -f
```

### View Nginx Logs

```bash
docker-compose exec nginx cat /var/log/nginx/access.log
docker-compose exec nginx cat /var/log/nginx/error.log
```

### Container Status

```bash
docker-compose ps
docker stats
```

## 🔧 Troubleshooting

### Container Won't Start

```bash
# Check logs
docker-compose logs app

# Rebuild image
docker-compose build --no-cache app
docker-compose up -d
```

### Database Connection Issues

```bash
# Check database status
docker-compose exec db pg_isready -U finventory_user

# Check connection from app
docker-compose exec app python -c "from backend.utils.database import engine; print(engine.connect())"
```

### Port Already in Use

```bash
# Find process using port 5000
lsof -i :5000
# or
netstat -tunlp | grep 5000

# Kill process or change port in docker-compose.yml
```

### Permission Issues

```bash
# Fix ownership
sudo chown -R $USER:$USER .

# Fix script permissions
chmod +x scripts/*.sh
```

## 🚀 Scaling

### Horizontal Scaling (Multiple Workers)

Edit `docker-compose.production.yml`:
```yaml
app:
  deploy:
    replicas: 3
  environment:
    WORKERS: 2  # 2 workers per container
```

### Docker Swarm Deployment

```bash
# Initialize swarm
docker swarm init

# Deploy stack
docker stack deploy -c docker-compose.production.yml finventory

# Scale service
docker service scale finventory_app=5
```

## 🔄 Updates and Maintenance

### Update Application

```bash
# Pull latest code
git pull origin main

# Rebuild and restart
make prod-build
make prod-down
make prod-up
```

### Update Docker Images

```bash
# Update base images
docker-compose pull
docker-compose up -d --build
```

### Cleanup Old Images

```bash
docker image prune -a
docker volume prune
```

## 🌐 Reverse Proxy Configuration

### Nginx (Included)

Already configured in `nginx/conf.d/finventory.conf`

### Apache (Alternative)

```apache
<VirtualHost *:80>
    ServerName yourdomain.com
    
    ProxyPreserveHost On
    ProxyPass / http://localhost:5000/
    ProxyPassReverse / http://localhost:5000/
</VirtualHost>
```

### Traefik (Alternative)

Add labels to `docker-compose.production.yml`:
```yaml
app:
  labels:
    - "traefik.enable=true"
    - "traefik.http.routers.finventory.rule=Host(`yourdomain.com`)"
```

## 📈 Performance Optimization

### 1. Resource Limits

Edit `docker-compose.production.yml`:
```yaml
app:
  deploy:
    resources:
      limits:
        cpus: '2'
        memory: 2G
      reservations:
        cpus: '1'
        memory: 1G
```

### 2. Database Optimization

```sql
-- Inside PostgreSQL container
ALTER SYSTEM SET shared_buffers = '256MB';
ALTER SYSTEM SET effective_cache_size = '1GB';
ALTER SYSTEM SET work_mem = '16MB';
```

### 3. Nginx Caching

Add to `nginx/conf.d/finventory.conf`:
```nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g;

location / {
    proxy_cache app_cache;
    proxy_cache_valid 200 1h;
    # ...
}
```

## 🆘 Support

For issues and questions:
- **Email**: eng7mi@gmail.com
- **Repository**: https://github.com/Alqudimi/Finventory
- **Issues**: https://github.com/Alqudimi/Finventory/issues

## 📄 License

Copyright © 2025 Alqudimi Technology. All rights reserved.

---

**Made with ❤️ by Abdulaziz Alqudimi**
