# Deployment as Ubuntu Service

## Prerequisites

- Ubuntu 18.04 or later
- Node.js 16.x or later
- MySQL 5.7 or later
- Root or sudo access

## Installation Steps

### 1. Install Node.js

```bash
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
```

### 2. Create Application Directory

```bash
sudo mkdir -p /opt/cartec_api
sudo chown $USER:$USER /opt/cartec_api
```

### 3. Copy Application Files

```bash
cp -r /path/to/cartec_api/* /opt/cartec_api/
cd /opt/cartec_api
```

### 4. Install Dependencies

```bash
npm install --production
```

### 5. Configure Environment

```bash
cp .env.example .env
nano .env
```

Update with your actual database credentials and configuration.

### 6. Import Stored Procedure

```bash
mysql -u root -p revisa < sql/prc_api_create_OT.sql
```

## Systemd Service Setup

### 1. Create Service File

```bash
sudo nano /etc/systemd/system/cartec-api.service
```

### 2. Service Configuration

```ini
[Unit]
Description=Cartec API Service
Documentation=https://github.com/yourcompany/cartec_api
After=network.target mysql.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/cartec_api
Environment="NODE_ENV=production"
EnvironmentFile=/opt/cartec_api/.env
ExecStart=/usr/bin/node /opt/cartec_api/src/index.js
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=cartec-api

# Security
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/cartec_api

[Install]
WantedBy=multi-user.target
```

### 3. Set Permissions

```bash
sudo chown -R www-data:www-data /opt/cartec_api
sudo chmod 600 /opt/cartec_api/.env
```

### 4. Reload Systemd

```bash
sudo systemctl daemon-reload
```

## Service Management

### Start Service

```bash
sudo systemctl start cartec-api
```

### Stop Service

```bash
sudo systemctl stop cartec-api
```

### Restart Service

```bash
sudo systemctl restart cartec-api
```

### Enable on Boot

```bash
sudo systemctl enable cartec-api
```

### Disable on Boot

```bash
sudo systemctl disable cartec-api
```

### Check Status

```bash
sudo systemctl status cartec-api
```

## Monitoring and Logs

### View Real-time Logs

```bash
sudo journalctl -u cartec-api -f
```

### View Last 100 Lines

```bash
sudo journalctl -u cartec-api -n 100
```

### View Logs Since Date

```bash
sudo journalctl -u cartec-api --since "2024-01-01"
```

### View Logs with Priority

```bash
sudo journalctl -u cartec-api -p err
```

## Nginx Reverse Proxy (Optional)

### 1. Install Nginx

```bash
sudo apt-get install nginx
```

### 2. Create Nginx Configuration

```bash
sudo nano /etc/nginx/sites-available/cartec-api
```

```nginx
server {
    listen 80;
    server_name api.cartec.cl;

    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;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }
}
```

### 3. Enable Site

```bash
sudo ln -s /etc/nginx/sites-available/cartec-api /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### 4. SSL with Certbot (Optional)

```bash
sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d api.cartec.cl
```

## Firewall Configuration

```bash
sudo ufw allow 3000/tcp
sudo ufw allow 'Nginx Full'
sudo ufw enable
```

## Health Check Script

Create `/opt/cartec_api/healthcheck.sh`:

```bash
#!/bin/bash
HEALTH_URL="http://localhost:3000/api/health"
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" $HEALTH_URL)

if [ $RESPONSE -eq 200 ]; then
    echo "Service is healthy"
    exit 0
else
    echo "Service is unhealthy (HTTP $RESPONSE)"
    exit 1
fi
```

```bash
chmod +x /opt/cartec_api/healthcheck.sh
```

## Cron Job for Monitoring (Optional)

```bash
sudo crontab -e
```

Add:
```
*/5 * * * * /opt/cartec_api/healthcheck.sh || systemctl restart cartec-api
```

## Troubleshooting

### Service Won't Start

```bash
# Check logs
sudo journalctl -u cartec-api -n 50

# Check permissions
ls -la /opt/cartec_api

# Test manually
cd /opt/cartec_api
node src/index.js
```

### Database Connection Issues

```bash
# Test MySQL connection
mysql -u $DB_USER -p$DB_PASSWORD -h $DB_HOST $DB_NAME

# Check MySQL service
sudo systemctl status mysql
```

### Port Already in Use

```bash
# Find process using port 3000
sudo lsof -i :3000
sudo netstat -tulpn | grep 3000

# Kill process if needed
sudo kill -9 <PID>
```

### Memory Issues

```bash
# Check memory usage
free -h
ps aux --sort=-%mem | head

# Add swap if needed
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
```

## Backup Strategy

### Database Backup Script

Create `/opt/cartec_api/backup.sh`:

```bash
#!/bin/bash
BACKUP_DIR="/opt/backups/cartec_api"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR

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

# Keep only last 7 days
find $BACKUP_DIR -type f -mtime +7 -delete

echo "Backup completed: $BACKUP_DIR/db_backup_$DATE.sql"
```

```bash
chmod +x /opt/cartec_api/backup.sh
```

Add to crontab:
```
0 2 * * * /opt/cartec_api/backup.sh
```

## Performance Tuning

### PM2 Alternative (Recommended for Production)

```bash
npm install -g pm2

# Start with PM2
pm2 start src/index.js --name cartec-api -i max

# Save PM2 config
pm2 save

# Setup startup script
pm2 startup systemd
```

## Update Procedure

```bash
# Stop service
sudo systemctl stop cartec-api

# Backup current version
sudo cp -r /opt/cartec_api /opt/cartec_api.backup

# Update files
cd /opt/cartec_api
git pull  # or copy new files

# Update dependencies
npm install --production

# Update database if needed
mysql -u root -p revisa < sql/prc_api_create_OT.sql

# Start service
sudo systemctl start cartec-api

# Check status
sudo systemctl status cartec-api
```

## Security Checklist

- [ ] Database credentials secured in `.env`
- [ ] `.env` file has 600 permissions
- [ ] Service runs as `www-data` user
- [ ] Firewall configured
- [ ] SSL certificate installed
- [ ] Regular backups configured
- [ ] Log rotation enabled
- [ ] Health checks active
- [ ] Monitoring in place

