Files
inventory-barcode-system/docs/DEPLOYMENT.md

581 lines
11 KiB
Markdown

# Deployment Guide
## Overview
This guide covers the deployment of the Inventory Barcode System in production environments. The system supports both Docker-based containerized deployment and traditional server deployment.
## Prerequisites
### System Requirements
**Minimum Requirements:**
- CPU: 2 cores
- RAM: 2GB
- Storage: 10GB free space
- OS: Linux, Windows, or macOS
**Recommended Requirements:**
- CPU: 4 cores
- RAM: 4GB
- Storage: 50GB free space
- OS: Linux (Ubuntu 20.04+ or CentOS 8+)
### Software Dependencies
**Required:**
- Docker 20.10+
- Docker Compose 2.0+
- Node.js 18+ (for non-Docker deployment)
**Optional:**
- Nginx (for reverse proxy)
- SSL certificates (for HTTPS)
## Docker Deployment (Recommended)
### Quick Start
1. **Clone the repository:**
```bash
git clone <repository-url>
cd inventory-barcode-system
```
2. **Configure environment:**
```bash
cp .env.example .env
# Edit .env file with your settings
```
3. **Deploy with Docker Compose:**
```bash
# Linux/macOS
./scripts/deploy.sh
# Windows PowerShell
.\scripts\deploy.ps1
```
4. **Verify deployment:**
```bash
curl http://localhost:3000/health
```
### Environment Configuration
Edit the `.env` file with your production settings:
```bash
# Server Configuration
NODE_ENV=production
PORT=3000
HOST=0.0.0.0
# Database Configuration
DATABASE_PATH=./data/inventory.db
DATABASE_BACKUP_PATH=./data/backups
DATABASE_BACKUP_INTERVAL=3600000
# File Upload Configuration
UPLOAD_MAX_SIZE=10485760
TEMP_DIR=./data/temp
# Logging Configuration
LOG_LEVEL=info
LOG_DIR=./logs
# Backup Configuration
BACKUP_ENABLED=true
BACKUP_SCHEDULE=0 2 * * *
BACKUP_RETENTION_DAYS=30
```
### Docker Compose Configuration
The `docker-compose.yml` file includes:
- **Application container** with health checks
- **Persistent volumes** for data and logs
- **Environment variable** configuration
- **Automatic restart** policies
### Deployment Commands
```bash
# Deploy application
./scripts/deploy.sh deploy
# Check status
./scripts/deploy.sh status
# View logs
./scripts/deploy.sh logs
# Restart application
./scripts/deploy.sh restart
# Stop application
./scripts/deploy.sh stop
# Rollback deployment
./scripts/deploy.sh rollback
```
## Manual Deployment
### Server Setup
1. **Install Node.js:**
```bash
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# CentOS/RHEL
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
```
2. **Install system dependencies:**
```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y build-essential python3 sqlite3
# CentOS/RHEL
sudo yum groupinstall -y "Development Tools"
sudo yum install -y python3 sqlite
```
3. **Create application user:**
```bash
sudo useradd -m -s /bin/bash inventory
sudo usermod -aG sudo inventory
```
### Application Deployment
1. **Deploy application files:**
```bash
# Copy files to server
scp -r . inventory@server:/opt/inventory-barcode-system/
# Set permissions
sudo chown -R inventory:inventory /opt/inventory-barcode-system
```
2. **Install dependencies:**
```bash
cd /opt/inventory-barcode-system
npm ci --only=production
```
3. **Configure environment:**
```bash
cp .env.example .env
# Edit .env with production settings
```
4. **Create systemd service:**
```bash
sudo tee /etc/systemd/system/inventory-barcode.service > /dev/null <<EOF
[Unit]
Description=Inventory Barcode System
After=network.target
[Service]
Type=simple
User=inventory
WorkingDirectory=/opt/inventory-barcode-system
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
EOF
```
5. **Start service:**
```bash
sudo systemctl daemon-reload
sudo systemctl enable inventory-barcode
sudo systemctl start inventory-barcode
```
## Reverse Proxy Setup
### Nginx Configuration
1. **Install Nginx:**
```bash
# Ubuntu/Debian
sudo apt-get install nginx
# CentOS/RHEL
sudo yum install nginx
```
2. **Configure virtual host:**
```bash
sudo tee /etc/nginx/sites-available/inventory-barcode > /dev/null <<EOF
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
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;
proxy_cache_bypass \$http_upgrade;
}
# Static file serving
location /static/ {
alias /opt/inventory-barcode-system/public/;
expires 1y;
add_header Cache-Control "public, immutable";
}
}
EOF
```
3. **Enable site:**
```bash
sudo ln -s /etc/nginx/sites-available/inventory-barcode /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```
### SSL Configuration
1. **Install Certbot:**
```bash
sudo apt-get install certbot python3-certbot-nginx
```
2. **Obtain SSL certificate:**
```bash
sudo certbot --nginx -d your-domain.com
```
3. **Auto-renewal:**
```bash
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet
```
## Database Management
### Backup Configuration
The system includes automated backup functionality:
```javascript
// Backup settings in .env
BACKUP_ENABLED=true
BACKUP_SCHEDULE=0 2 * * * // Daily at 2 AM
BACKUP_RETENTION_DAYS=30
```
### Manual Backup
```bash
# Create backup
node -e "
const BackupManager = require('./utils/backup');
const backup = new BackupManager();
backup.createBackup().then(console.log).catch(console.error);
"
# List backups
ls -la data/backups/
# Restore from backup
node -e "
const BackupManager = require('./utils/backup');
const backup = new BackupManager();
backup.restoreBackup('data/backups/backup-file.db').then(console.log).catch(console.error);
"
```
### Database Migration
For schema updates:
```bash
# Backup current database
cp inventory.db inventory.db.backup
# Run migration script (if available)
node scripts/migrate.js
# Verify migration
node -e "
const db = require('./models/database');
console.log('Database schema version:', db.getSchemaVersion());
"
```
## Monitoring and Logging
### Log Management
Logs are stored in the `logs/` directory:
- `application.log` - General application logs
- `error.log` - Error logs
- `http.log` - HTTP request logs
### Log Rotation
Configure log rotation with logrotate:
```bash
sudo tee /etc/logrotate.d/inventory-barcode > /dev/null <<EOF
/opt/inventory-barcode-system/logs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 644 inventory inventory
postrotate
systemctl reload inventory-barcode
endscript
}
EOF
```
### Health Monitoring
The system provides a health check endpoint:
```bash
# Check application health
curl http://localhost:3000/health
# Response format:
{
"status": "OK",
"timestamp": "2024-01-01T00:00:00.000Z",
"uptime": 3600,
"memory": {...},
"version": "v18.17.0"
}
```
### Performance Monitoring
Monitor key metrics:
- **Response time**: Average API response time
- **Memory usage**: Node.js heap usage
- **Database size**: SQLite file size growth
- **Error rate**: Application error frequency
## Security Considerations
### Network Security
- Use HTTPS in production
- Configure firewall rules
- Limit database access
- Use reverse proxy for SSL termination
### Application Security
- Keep dependencies updated
- Use environment variables for secrets
- Implement rate limiting
- Enable security headers (Helmet.js)
### Data Security
- Regular database backups
- Encrypt sensitive data
- Implement access controls
- Monitor for unauthorized access
## Scaling Considerations
### Horizontal Scaling
For high-traffic deployments:
1. **Load Balancer Setup:**
```nginx
upstream inventory_backend {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
server {
location / {
proxy_pass http://inventory_backend;
}
}
```
2. **Database Considerations:**
- SQLite limitations for concurrent writes
- Consider PostgreSQL for high concurrency
- Implement database connection pooling
### Vertical Scaling
- Increase server resources (CPU, RAM)
- Optimize Node.js memory settings
- Configure PM2 for process management
## Troubleshooting
### Common Issues
**Application won't start:**
```bash
# Check logs
docker-compose logs inventory-app
# or
journalctl -u inventory-barcode -f
# Check port availability
netstat -tlnp | grep :3000
# Check file permissions
ls -la /opt/inventory-barcode-system
```
**Database errors:**
```bash
# Check database file
sqlite3 inventory.db ".schema"
# Check disk space
df -h
# Check file permissions
ls -la inventory.db
```
**Performance issues:**
```bash
# Check system resources
top
htop
free -h
# Check application metrics
curl http://localhost:3000/health
```
### Log Analysis
```bash
# View recent errors
tail -f logs/error.log
# Search for specific errors
grep "ERROR" logs/application.log
# Monitor HTTP requests
tail -f logs/http.log
```
## Maintenance
### Regular Tasks
**Daily:**
- Check application health
- Monitor error logs
- Verify backup completion
**Weekly:**
- Review performance metrics
- Update system packages
- Clean temporary files
**Monthly:**
- Update Node.js dependencies
- Review security patches
- Optimize database
### Update Procedure
1. **Backup current deployment:**
```bash
./scripts/deploy.sh rollback # Creates backup
```
2. **Deploy new version:**
```bash
git pull origin main
./scripts/deploy.sh deploy
```
3. **Verify deployment:**
```bash
./scripts/deploy.sh status
curl http://localhost:3000/health
```
4. **Rollback if needed:**
```bash
./scripts/deploy.sh rollback
```
## Support
For deployment issues:
1. Check this documentation
2. Review application logs
3. Verify system requirements
4. Contact system administrator
5. Refer to troubleshooting section
## Appendix
### Environment Variables Reference
| Variable | Default | Description |
|----------|---------|-------------|
| `NODE_ENV` | `production` | Application environment |
| `PORT` | `3000` | Server port |
| `HOST` | `0.0.0.0` | Server host |
| `DATABASE_PATH` | `./inventory.db` | Database file path |
| `LOG_LEVEL` | `info` | Logging level |
| `BACKUP_ENABLED` | `true` | Enable automatic backups |
### Port Requirements
| Port | Service | Description |
|------|---------|-------------|
| `3000` | Application | Main application port |
| `80` | HTTP | Web server (if using reverse proxy) |
| `443` | HTTPS | Secure web server |
### File Permissions
```bash
# Application files
chown -R inventory:inventory /opt/inventory-barcode-system
chmod -R 755 /opt/inventory-barcode-system
chmod 644 /opt/inventory-barcode-system/.env
# Database files
chmod 660 /opt/inventory-barcode-system/inventory.db
chmod 755 /opt/inventory-barcode-system/data
# Log files
chmod 644 /opt/inventory-barcode-system/logs/*.log
```