Server Configuration & Deployment

Production deployment, security, and optimization guide

Production Environment Setup

This guide covers deploying InveTrack in a production environment with proper security, performance, and monitoring configurations.

Server Requirements

  • CPU: 2+ cores (4+ recommended)
  • RAM: 8GB minimum (16GB+ recommended)
  • Storage: 50GB+ SSD storage
  • OS: Ubuntu 20.04 LTS or CentOS 8+
  • Network: Static IP address, domain name

Environment Configuration

Production .env Configuration

# Database Configuration
                        
DB_HOST=localhost
DB_PORT=3306
DB_NAME=invetrack_db
DB_USERNAME=root
DB_PASSWORD=your_mysql_password

# JWT Configuration
JWT_SECRET=your-super-secure-jwt-secret-key-change-this-in-production
JWT_EXPIRES_IN=24h

# Server Configuration
PORT=3000
NODE_ENV=development

# CORS Configuration
ALLOWED_ORIGINS=http://localhost:5000,http://localhost:3000

# Rate Limiting
RATE_LIMIT_MAX=1000
AUTH_RATE_LIMIT_MAX=1000
API_RATE_LIMIT_MAX=1000

# Logging
LOG_LEVEL=info

Security Warning

Never commit the .env file to version control. Use environment-specific configuration files and secure secret management.

Process Management

PM2 Configuration

Create

ecosystem.config.js
for production deployment:

module.exports = {
  apps: [{
    name: 'invetrack-server',
    script: './bin/www',
    instances: 'max', // Use all CPU cores
    exec_mode: 'cluster',
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_file: './logs/combined.log',
    time: true,
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
  }]
};

Systemd Service

Create

/etc/systemd/system/invetrack.service
:

[Unit]
Description=InveTrack Inventory Management System
After=network.target mysql.service
Requires=mysql.service

[Service]
Type=forking
User=www-data
Group=www-data
WorkingDirectory=/var/www/invetrack/server
ExecStart=/usr/bin/pm2 start ecosystem.config.js
ExecReload=/usr/bin/pm2 reload all
ExecStop=/usr/bin/pm2 stop all
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Web Server Configuration

Nginx Configuration

Create

/etc/nginx/sites-available/invetrack
:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;

    # Security Headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Rate Limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

    # API Routes
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        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;
    }

    # Frontend
    location / {
        root /var/www/invetrack/client/dist;
        try_files $uri $uri/ /index.html;
        
        # Cache static assets
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # File uploads
    location /uploads/ {
        alias /var/www/invetrack/server/public/uploads/;
        expires 1y;
        add_header Cache-Control "public";
    }
}

Apache Configuration

Create

/etc/apache2/sites-available/invetrack.conf
:

<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    Redirect permanent / https://yourdomain.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    DocumentRoot /var/www/invetrack/client/dist

    # SSL Configuration
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/yourdomain.com/chain.pem

    # Security Headers
    Header always set X-Frame-Options DENY
    Header always set X-Content-Type-Options nosniff
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    # API Proxy
    ProxyPreserveHost On
    ProxyPass /api/ http://localhost:3000/api/
    ProxyPassReverse /api/ http://localhost:3000/api/

    # File uploads
    Alias /uploads /var/www/invetrack/server/public/uploads
    <Directory /var/www/invetrack/server/public/uploads>
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    # Frontend
    <Directory /var/www/invetrack/client/dist>
        Options -Indexes
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

SSL Certificate Setup

Let's Encrypt with Certbot

1

Install Certbot

# Ubuntu/Debian
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install certbot python3-certbot-nginx
2

Obtain Certificate

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
3

Auto-renewal

# Test renewal
sudo certbot renew --dry-run

# Add to crontab for auto-renewal
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet

Monitoring and Logging

Log Management

Configure log rotation in

/etc/logrotate.d/invetrack
:

/var/www/invetrack/server/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 www-data www-data
    postrotate
        /usr/bin/pm2 reloadLogs
    endscript
}

Health Monitoring

Set up monitoring with tools like:

  • PM2 Monitoring: Built-in process monitoring
  • Uptime Robot: External uptime monitoring
  • New Relic: Application performance monitoring
  • DataDog: Infrastructure monitoring

Backup Strategy

#!/bin/bash
# Database backup script
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/invetrack"
DB_NAME="invetrack_production"

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup database
mysqldump -u root -p$DB_PASSWORD $DB_NAME > $BACKUP_DIR/db_backup_$DATE.sql

# Backup uploads
tar -czf $BACKUP_DIR/uploads_backup_$DATE.tar.gz /var/www/invetrack/server/public/uploads/

# Keep only last 7 days of backups
find $BACKUP_DIR -name "*.sql" -mtime +7 -delete
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

Security Hardening

Server Security

  • Keep the system and packages updated
  • Configure firewall (UFW or iptables)
  • Disable root login and use SSH keys
  • Install fail2ban for brute force protection
  • Use non-standard ports for SSH

Application Security

  • Use environment variables for sensitive data
  • Implement proper input validation
  • Use HTTPS everywhere
  • Set secure HTTP headers
  • Regular security audits and updates

Database Security

  • Use strong passwords
  • Limit database user privileges
  • Enable SSL for database connections
  • Regular security updates
  • Monitor database access logs

Performance Optimization

Node.js Optimization

Setting Value Description
NODE_ENV production Enables production optimizations
UV_THREADPOOL_SIZE 128 Increases thread pool size
NODE_OPTIONS --max-old-space-size=4096 Increases memory limit

Database Optimization

  • Add appropriate indexes
  • Optimize queries
  • Use connection pooling
  • Regular database maintenance

Caching Strategy

  • Implement Redis for session storage
  • Use CDN for static assets
  • Enable browser caching
  • Database query caching

Deployment Checklist

Pre-deployment

  • ✅ Test all functionality in staging environment
  • ✅ Configure production environment variables
  • ✅ Set up SSL certificates
  • ✅ Configure web server (Nginx/Apache)
  • ✅ Set up database with proper security
  • ✅ Configure monitoring and logging

Deployment

  • ✅ Deploy application code
  • ✅ Run database migrations
  • ✅ Start application services
  • ✅ Configure load balancer (if applicable)
  • ✅ Test all endpoints
  • ✅ Verify SSL certificate

Post-deployment

  • ✅ Monitor application performance
  • ✅ Check error logs
  • ✅ Verify backup procedures
  • ✅ Test failover procedures
  • ✅ Document any custom configurations