Skip to main content

Overview

This guide covers deploying Sistema de Productos to production, including building the frontend, configuring the server, and setting up the database.

Prerequisites

1

Node.js

Ensure Node.js 18+ is installed on your production server:
node --version
2

PostgreSQL

Install and configure PostgreSQL 12+ on your server:
psql --version
3

Process Manager

Install PM2 for process management:
npm install -g pm2

Database Setup

1. Create Production Database

-- Connect to PostgreSQL
psql -U postgres

-- Create database
CREATE DATABASE ejercicio_productos;

-- Create user (optional)
CREATE USER productos_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE ejercicio_productos TO productos_user;
Always use strong passwords for your database users and change default credentials.

2. Configure Database Connection

Set up your production environment variables:
.env
PG_USER=productos_user
PG_HOST=localhost
PG_DATABASE=ejercicio_productos
PG_PASSWORD=your_secure_production_password
PG_PORT=5432

Frontend Build

Build for Production

Build the Vue.js frontend for production:
1

Install Dependencies

npm install
2

Build Frontend

npm run build
This creates optimized static files in the dist/ directory.
3

Verify Build

Check that the build completed successfully:
ls -la dist/
The build process is configured in vite.config.js and uses Vite for fast, optimized builds.

Serve Static Files

You can serve the built files using:
Add to your server/app.js:
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// Serve static files from dist
app.use(express.static(path.join(__dirname, '../dist')));

// Handle SPA routing
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});
Configure Nginx to serve static files and proxy API requests:
server {
  listen 80;
  server_name yourdomain.com;
  
  # Serve frontend
  location / {
    root /path/to/your/dist;
    try_files $uri $uri/ /index.html;
  }
  
  # Proxy API requests
  location /api-productos {
    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_cache_bypass $http_upgrade;
  }
}

Environment Configuration

Create a production .env file with all required variables:
.env.production
# Server Configuration
PORT=3000
NODE_ENV=production

# Database Configuration
PG_USER=productos_user
PG_HOST=localhost
PG_DATABASE=ejercicio_productos
PG_PASSWORD=your_secure_production_password
PG_PORT=5432

# JWT Configuration
JWT_SECRET=your_very_long_and_secure_random_secret_key_minimum_64_characters

# Email Configuration
EMAIL_USER=[email protected]
EMAIL_PASS=your_app_specific_password
Never use development secrets in production. Generate new, secure secrets for production deployment.

Process Management

Using PM2

PM2 is recommended for managing your Node.js application in production:
1

Create PM2 Configuration

Create ecosystem.config.js:
ecosystem.config.js
module.exports = {
  apps: [{
    name: 'sistema-productos',
    script: './server/index.js',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
  }]
};
2

Start Application

pm2 start ecosystem.config.js
3

Configure Auto-restart

pm2 startup
pm2 save

PM2 Commands

# Check application status
pm2 status

# View logs
pm2 logs sistema-productos

# Monitor resources
pm2 monit

Security Hardening

1

Update CORS Settings

Update server/app.js with your production domain:
app.use(cors({
  origin: 'https://yourdomain.com',
  credentials: true
}));
2

Enable HTTPS

Update cookie settings in server/controllers/usuarios.controller.js:
res.cookie('token', token, {
  httpOnly: true,
  secure: true,  // Enable for HTTPS
  sameSite: 'strict',
  maxAge: 3600000
});
3

Set Environment

NODE_ENV=production

SSL/TLS Configuration

Using Certbot (Let’s Encrypt)

1

Install Certbot

sudo apt-get update
sudo apt-get install certbot python3-certbot-nginx
2

Obtain Certificate

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

Auto-renewal

sudo certbot renew --dry-run

Health Checks

Implement a health check endpoint for monitoring:
server/app.js
app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'healthy', 
    timestamp: new Date().toISOString() 
  });
});

Monitoring

For advanced monitoring:
pm2 link your_secret_key your_public_key
This provides:
  • Real-time metrics
  • Error tracking
  • Custom metrics
  • Notifications

Backup Strategy

Database Backups

# Create backup
pg_dump -U productos_user ejercicio_productos > backup_$(date +%Y%m%d_%H%M%S).sql

# Restore from backup
psql -U productos_user ejercicio_productos < backup_20260304_120000.sql

Troubleshooting

Check PostgreSQL is running and accepting connections:
sudo systemctl status postgresql
psql -U productos_user -d ejercicio_productos -h localhost
Find and kill the process using the port:
lsof -i :3000
kill -9 <PID>
Ensure proper file permissions:
chmod -R 755 /path/to/application
chown -R your-user:your-group /path/to/application
Always test your deployment in a staging environment before deploying to production.

Build docs developers (and LLMs) love