hostbasket/actix_mvc_app/PRODUCTION_DEPLOYMENT.md
Mahmoud-Emad d3a66d4fc8 feat: Add initial production deployment support
- Add .env.example file for environment variable setup
- Add .gitignore to manage sensitive files and directories
- Add Dockerfile.prod for production-ready Docker image
- Add PRODUCTION_CHECKLIST.md for pre/post deployment steps
- Add PRODUCTION_DEPLOYMENT.md for deployment instructions
- Add STRIPE_SETUP.md for Stripe payment configuration
- Add config/default.toml for default configuration settings
- Add config/local.toml.example for local configuration template
2025-06-25 18:32:20 +03:00

411 lines
9.4 KiB
Markdown

# Production Deployment Guide
## Overview
This guide covers deploying the Freezone Company Registration System to production with proper security, monitoring, and reliability.
## Prerequisites
- Docker and Docker Compose installed
- SSL certificates for HTTPS
- Stripe production account with API keys
- Domain name configured
- Server with at least 4GB RAM and 2 CPU cores
## Environment Variables
Create a `.env.prod` file with the following variables:
```bash
# Application
RUST_ENV=production
RUST_LOG=info
# Database
POSTGRES_DB=freezone_prod
POSTGRES_USER=freezone_user
POSTGRES_PASSWORD=your_secure_db_password
DATABASE_URL=postgresql://freezone_user:your_secure_db_password@db:5432/freezone_prod
# Redis
REDIS_URL=redis://:your_redis_password@redis:6379
REDIS_PASSWORD=your_secure_redis_password
# Stripe (Production Keys)
STRIPE_SECRET_KEY=sk_live_your_production_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_production_webhook_secret
# Session Security
SESSION_SECRET=your_64_character_session_secret_key_for_production_use_only
# Monitoring
GRAFANA_PASSWORD=your_secure_grafana_password
```
## Security Checklist
### Before Deployment
- [ ] **SSL/TLS Certificates**: Obtain valid SSL certificates for your domain
- [ ] **Environment Variables**: All production secrets are set and secure
- [ ] **Database Security**: Database passwords are strong and unique
- [ ] **Stripe Configuration**: Production Stripe keys are configured
- [ ] **Session Security**: Session secret is 64+ characters and random
- [ ] **Firewall Rules**: Only necessary ports are open (80, 443, 22)
- [ ] **User Permissions**: Application runs as non-root user
### Stripe Configuration
1. **Production Account**: Ensure you're using Stripe production keys
2. **Webhook Endpoints**: Configure webhook endpoint in Stripe dashboard:
- URL: `https://yourdomain.com/payment/webhook`
- Events: `payment_intent.succeeded`, `payment_intent.payment_failed`
3. **Webhook Secret**: Copy the webhook signing secret to environment variables
### Database Security
1. **Connection Security**: Use SSL connections to database
2. **User Permissions**: Create dedicated database user with minimal permissions
3. **Backup Strategy**: Implement automated database backups
4. **Access Control**: Restrict database access to application only
## Deployment Steps
### 1. Server Preparation
```bash
# Update system
sudo apt update && sudo apt upgrade -y
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Install Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# Create application directory
sudo mkdir -p /opt/freezone
sudo chown $USER:$USER /opt/freezone
cd /opt/freezone
```
### 2. Application Deployment
```bash
# Clone repository
git clone https://github.com/your-org/freezone-registration.git .
# Copy environment file
cp .env.prod.example .env.prod
# Edit .env.prod with your production values
# Create necessary directories
mkdir -p data logs nginx/ssl static
# Copy SSL certificates to nginx/ssl/
# - cert.pem (certificate)
# - key.pem (private key)
# Build and start services
docker-compose -f docker-compose.prod.yml up -d --build
```
### 3. SSL Configuration
Create `nginx/nginx.conf`:
```nginx
events {
worker_connections 1024;
}
http {
upstream app {
server app:8080;
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /health {
proxy_pass http://app/health;
access_log off;
}
}
}
```
### 4. Monitoring Setup
The deployment includes:
- **Prometheus**: Metrics collection (port 9090)
- **Grafana**: Dashboards and alerting (port 3000)
- **Loki**: Log aggregation (port 3100)
- **Promtail**: Log shipping
Access Grafana at `https://yourdomain.com:3000` with admin credentials.
## Health Checks
The application provides several health check endpoints:
- `/health` - Overall system health
- `/health/detailed` - Detailed component status
- `/health/ready` - Readiness for load balancers
- `/health/live` - Liveness check
## Monitoring and Alerting
### Key Metrics to Monitor
1. **Application Health**
- Response time
- Error rate
- Request volume
- Memory usage
2. **Payment Processing**
- Payment success rate
- Payment processing time
- Failed payment count
- Webhook processing time
3. **Database Performance**
- Connection pool usage
- Query response time
- Database size
- Active connections
4. **System Resources**
- CPU usage
- Memory usage
- Disk space
- Network I/O
### Alerting Rules
Configure alerts for:
- Application downtime (> 1 minute)
- High error rate (> 5%)
- Payment failures (> 2%)
- Database connection issues
- High memory usage (> 80%)
- Disk space low (< 10%)
## Backup Strategy
### Database Backups
```bash
# Daily backup script
#!/bin/bash
BACKUP_DIR="/opt/freezone/backups"
DATE=$(date +%Y%m%d_%H%M%S)
docker exec freezone-db pg_dump -U freezone_user freezone_prod > $BACKUP_DIR/db_backup_$DATE.sql
# Keep only last 30 days
find $BACKUP_DIR -name "db_backup_*.sql" -mtime +30 -delete
```
### Application Data Backups
```bash
# Backup registration data and logs
tar -czf /opt/freezone/backups/app_data_$(date +%Y%m%d).tar.gz \
/opt/freezone/data \
/opt/freezone/logs
```
## Maintenance
### Regular Tasks
1. **Weekly**
- Review application logs
- Check system resource usage
- Verify backup integrity
- Update security patches
2. **Monthly**
- Review payment processing metrics
- Update dependencies
- Performance optimization review
- Security audit
### Log Rotation
Configure log rotation in `/etc/logrotate.d/freezone`:
```
/opt/freezone/logs/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 644 appuser appuser
}
```
## Troubleshooting
### Common Issues
1. **Application Won't Start**
- Check environment variables
- Verify database connectivity
- Check SSL certificate paths
2. **Payment Processing Fails**
- Verify Stripe API keys
- Check webhook configuration
- Review payment logs
3. **Database Connection Issues**
- Check database container status
- Verify connection string
- Check network connectivity
### Log Locations
- Application logs: `/opt/freezone/logs/`
- Docker logs: `docker-compose logs [service]`
- Nginx logs: `docker-compose logs nginx`
- Database logs: `docker-compose logs db`
### Emergency Procedures
1. **Application Rollback**
```bash
# Stop current deployment
docker-compose -f docker-compose.prod.yml down
# Restore from backup
git checkout previous-stable-tag
docker-compose -f docker-compose.prod.yml up -d --build
```
2. **Database Recovery**
```bash
# Restore from backup
docker exec -i freezone-db psql -U freezone_user freezone_prod < backup.sql
```
## Security Maintenance
### Regular Security Tasks
1. **Update Dependencies**
```bash
# Update Rust dependencies
cargo update
# Rebuild with security patches
docker-compose -f docker-compose.prod.yml build --no-cache
```
2. **SSL Certificate Renewal**
```bash
# Using Let's Encrypt (example)
certbot renew --nginx
```
3. **Security Scanning**
```bash
# Scan for vulnerabilities
cargo audit
# Docker image scanning
docker scan freezone-registration-app
```
## Performance Optimization
### Application Tuning
1. **Database Connection Pool**
- Monitor connection usage
- Adjust pool size based on load
2. **Redis Configuration**
- Configure memory limits
- Enable persistence if needed
3. **Nginx Optimization**
- Enable gzip compression
- Configure caching headers
- Optimize worker processes
### Scaling Considerations
1. **Horizontal Scaling**
- Load balancer configuration
- Session store externalization
- Database read replicas
2. **Vertical Scaling**
- Monitor resource usage
- Increase container resources
- Optimize database queries
## Support and Maintenance
For production support:
1. **Monitoring**: Use Grafana dashboards for real-time monitoring
2. **Alerting**: Configure alerts for critical issues
3. **Logging**: Centralized logging with Loki/Grafana
4. **Documentation**: Keep deployment documentation updated
## Compliance and Auditing
### PCI DSS Compliance
- Secure payment processing with Stripe
- No storage of sensitive payment data
- Regular security assessments
- Access logging and monitoring
### Data Protection
- Secure data transmission (HTTPS)
- Data encryption at rest
- Regular backups
- Access control and audit trails
### Audit Trail
The application logs all critical events:
- Payment processing
- User actions
- Administrative changes
- Security events
Review audit logs regularly and maintain for compliance requirements.