CoAI LogoCoAI.Dev

Traditional Server Deployment

Deploy CoAI.Dev on traditional servers with manual compilation and system service configuration

Traditional Server Deployment

Traditional server deployment involves installing CoAI.Dev directly on your server infrastructure without containerization. This approach provides maximum control over the environment and is ideal for organizations with specific compliance requirements or existing infrastructure constraints.

When to Use Traditional Deployment

Choose traditional deployment when you need full control over the runtime environment, have specific compliance requirements, or need to integrate with existing monitoring and management tools.

Overview

Traditional Deployment Benefits:

  • 🔧 Full Control: Complete control over the runtime environment
  • 🏢 Compliance Ready: Easier to meet specific regulatory requirements
  • 📊 Legacy Integration: Works with existing monitoring and backup systems
  • Performance: Direct hardware access for optimal performance
  • 🔒 Security: Custom security configurations and hardening

Best For:

  • Enterprise environments with strict compliance requirements
  • Existing infrastructure with specific monitoring tools
  • High-performance requirements with dedicated hardware
  • Organizations preferring traditional system administration

Prerequisites

System Requirements

Minimum Requirements:

  • CPU: 4 cores (2.0GHz+)
  • RAM: 8GB
  • Storage: 50GB available space
  • OS: Linux (Ubuntu 20.04+, CentOS 8+, RHEL 8+)

Recommended for Production:

  • CPU: 8+ cores (3.0GHz+)
  • RAM: 16GB+
  • Storage: 100GB+ SSD
  • Network: 1Gbps+ connection

Required Software

Core Dependencies:

  • Node.js: v18+ and npm/pnpm
  • Go: v1.19+
  • MySQL: v8.0+
  • Redis: v6.0+
  • Nginx: v1.18+ (for reverse proxy)

System Tools:

  • Git: For source code management
  • Systemd: For service management
  • SSL Certificate: For HTTPS (Let's Encrypt or commercial)

Installation Process

Install Dependencies

# Update system
sudo apt update && sudo apt upgrade -y
 
# Install basic tools
sudo apt install -y curl wget git build-essential
 
# Install Node.js (v18+)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
 
# Install pnpm
npm install -g pnpm
 
# Install Go (latest version)
wget https://go.dev/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
 
# Install MySQL
sudo apt install -y mysql-server mysql-client
sudo mysql_secure_installation
 
# Install Redis
sudo apt install -y redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server
 
# Install Nginx
sudo apt install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx

Database Setup

Configure MySQL

Create Database and User:

# Connect to MySQL as root
sudo mysql -u root -p
 
# Create database
CREATE DATABASE chatnio CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
 
# Create user with proper permissions
CREATE USER 'chatnio'@'localhost' IDENTIFIED BY 'your-secure-password';
GRANT ALL PRIVILEGES ON chatnio.* TO 'chatnio'@'localhost';
FLUSH PRIVILEGES;
 
# Exit MySQL
EXIT;

Configure MySQL Settings (/etc/mysql/mysql.conf.d/mysqld.cnf):

[mysqld]
# Basic settings
bind-address = 127.0.0.1
port = 3306
 
# Performance tuning
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
max_connections = 200
query_cache_size = 64M
 
# Security settings
local_infile = 0
skip_show_database
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO
 
# Character set
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

Restart MySQL:

sudo systemctl restart mysql

Configure Redis

Configure Redis Settings (/etc/redis/redis.conf):

# Network
bind 127.0.0.1
port 6379
protected-mode yes

# General
daemonize yes
supervised systemd
pidfile /var/run/redis/redis-server.pid

# Logging
loglevel notice
logfile /var/log/redis/redis-server.log

# Persistence
save 900 1
save 300 10
save 60 10000
dir /var/lib/redis

# Security
requirepass your-redis-password

# Memory
maxmemory 1gb
maxmemory-policy allkeys-lru

# Append only file
appendonly yes
appendfsync everysec

Restart Redis:

sudo systemctl restart redis

Build CoAI.Dev

Clone and Prepare Source

# Clone repository
cd /opt
sudo git clone https://github.com/coaidev/coai.git
sudo chown -R chatnio:chatnio /opt/chatnio
cd /opt/chatnio
 
# Switch to a stable branch/tag if needed
# sudo git checkout v1.0.0

Build Frontend

# Navigate to frontend directory
cd /opt/chatnio/app
 
# Install dependencies
sudo -u chatnio pnpm install
 
# Build production frontend
sudo -u chatnio pnpm build
 
# Verify build
ls -la dist/

Build Backend

# Navigate to backend directory
cd /opt/chatnio
 
# Set Go environment
export GOPROXY=https://goproxy.cn,direct
export GO111MODULE=on
 
# Download dependencies
sudo -u chatnio go mod download
 
# Build binary
sudo -u chatnio go build -ldflags="-s -w" -o chatnio
 
# Verify build
ls -la chatnio
file chatnio

Configuration

Create Configuration File

Create /opt/chatnio/config.yaml:

# Database Configuration
mysql:
  host: "localhost"
  port: 3306
  database: "chatnio"
  username: "chatnio"
  password: "your-secure-password"
  charset: "utf8mb4"
  max_idle_conns: 10
  max_open_conns: 100
 
# Redis Configuration
redis:
  host: "localhost"
  port: 6379
  password: "your-redis-password"
  database: 0
 
# Server Configuration
server:
  host: "0.0.0.0"
  port: 8094
  secret: "your-super-secret-jwt-key"
  serve_static: true
  static_dir: "./app/dist"
 
# CORS Configuration
cors:
  allow_origins: ["*"]
  allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
  allow_headers: ["*"]
 
# File Upload Configuration
upload:
  max_size: 100
  allowed_types: ["image/*", "text/*", "application/pdf"]
  storage_path: "./storage"
 
# Logging Configuration
logging:
  level: "info"
  file: "/var/log/chatnio/app.log"
  max_size: 100
  max_backups: 3
  max_age: 28

Set proper permissions:

sudo chown chatnio:chatnio /opt/chatnio/config.yaml
sudo chmod 600 /opt/chatnio/config.yaml

Create Log Directory

# Create log directory
sudo mkdir -p /var/log/chatnio
sudo chown chatnio:chatnio /var/log/chatnio
sudo chmod 755 /var/log/chatnio
 
# Create storage directory
sudo mkdir -p /opt/chatnio/storage
sudo chown chatnio:chatnio /opt/chatnio/storage
sudo chmod 755 /opt/chatnio/storage

Environment Variables

Create /opt/chatnio/.env:

# Database
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_DB=chatnio
MYSQL_USER=chatnio
MYSQL_PASSWORD=your-secure-password
 
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password
 
# Application
SECRET=your-super-secret-jwt-key
SERVE_STATIC=true
PORT=8094
 
# Logging
LOG_LEVEL=info

Set permissions:

sudo chown chatnio:chatnio /opt/chatnio/.env
sudo chmod 600 /opt/chatnio/.env

Service Configuration

Create Systemd Service

Create /etc/systemd/system/chatnio.service:

[Unit]
Description=CoAI.Dev AI Platform
Documentation=https://docs.chatnio.net
After=network.target mysql.service redis.service
Wants=mysql.service redis.service
 
[Service]
Type=simple
User=chatnio
Group=chatnio
WorkingDirectory=/opt/chatnio
ExecStart=/opt/chatnio/chatnio
ExecReload=/bin/kill -USR2 $MAINPID
Restart=always
RestartSec=5
StartLimitInterval=0
 
# Environment
Environment=GO_ENV=production
EnvironmentFile=/opt/chatnio/.env
 
# Security
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/chatnio/storage /var/log/chatnio
PrivateTmp=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictRealtime=true
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
 
# Resource limits
LimitNOFILE=65536
LimitNPROC=4096
 
[Install]
WantedBy=multi-user.target

Enable and start service:

# Reload systemd
sudo systemctl daemon-reload
 
# Enable service
sudo systemctl enable chatnio
 
# Start service
sudo systemctl start chatnio
 
# Check status
sudo systemctl status chatnio
 
# View logs
sudo journalctl -u chatnio -f

Nginx Reverse Proxy

Create /etc/nginx/sites-available/chatnio:

# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
 
# Upstream backend
upstream chatnio_backend {
    server 127.0.0.1:8094 max_fails=3 fail_timeout=30s;
    keepalive 32;
}
 
server {
    listen 80;
    server_name your-domain.com www.your-domain.com;
    
    # Redirect HTTP to HTTPS
    return 301 https://$server_name$request_uri;
}
 
server {
    listen 443 ssl http2;
    server_name your-domain.com www.your-domain.com;
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    
    # Modern configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    # 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 Referrer-Policy "strict-origin-when-cross-origin";
    
    # Logging
    access_log /var/log/nginx/chatnio.access.log;
    error_log /var/log/nginx/chatnio.error.log;
    
    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    # Client settings
    client_max_body_size 100M;
    client_body_timeout 60s;
    client_header_timeout 60s;
    
    # API endpoints with rate limiting
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        
        proxy_pass http://chatnio_backend;
        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;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # Buffer settings
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 16 4k;
        proxy_busy_buffers_size 8k;
    }
    
    # Login endpoint with stricter rate limiting
    location /api/auth/login {
        limit_req zone=login burst=3 nodelay;
        
        proxy_pass http://chatnio_backend;
        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;
    }
    
    # WebSocket support
    location /ws {
        proxy_pass http://chatnio_backend;
        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;
        
        # WebSocket specific timeouts
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
    
    # Static files with caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        proxy_pass http://chatnio_backend;
        proxy_set_header Host $host;
        
        # Cache static files
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # All other requests
    location / {
        proxy_pass http://chatnio_backend;
        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;
    }
    
    # Health check endpoint
    location /health {
        access_log off;
        proxy_pass http://chatnio_backend/api/health;
        proxy_set_header Host $host;
    }
}

Enable the configuration:

# Test configuration
sudo nginx -t
 
# Enable site
sudo ln -s /etc/nginx/sites-available/chatnio /etc/nginx/sites-enabled/
 
# Remove default site
sudo rm -f /etc/nginx/sites-enabled/default
 
# Restart Nginx
sudo systemctl restart nginx

SSL Certificate Setup

Using Let's Encrypt

# Install Certbot
sudo apt install -y certbot python3-certbot-nginx
 
# Obtain certificate
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
 
# Test automatic renewal
sudo certbot renew --dry-run
 
# Setup automatic renewal
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet

Monitoring and Logging

Log Management

Configure logrotate (/etc/logrotate.d/chatnio):

/var/log/chatnio/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 chatnio chatnio
    postrotate
        systemctl reload chatnio
    endscript
}

System Monitoring

Create monitoring script (/usr/local/bin/chatnio-monitor.sh):

#!/bin/bash
 
# Check if CoAI.Dev service is running
if ! systemctl is-active --quiet chatnio; then
    echo "$(date): CoAI.Dev service is down, attempting restart" >> /var/log/chatnio/monitor.log
    systemctl restart chatnio
fi
 
# Check if MySQL is running
if ! systemctl is-active --quiet mysql; then
    echo "$(date): MySQL service is down, attempting restart" >> /var/log/chatnio/monitor.log
    systemctl restart mysql
fi
 
# Check if Redis is running
if ! systemctl is-active --quiet redis; then
    echo "$(date): Redis service is down, attempting restart" >> /var/log/chatnio/monitor.log
    systemctl restart redis
fi
 
# Check disk space
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 85 ]; then
    echo "$(date): Disk usage is at ${DISK_USAGE}%" >> /var/log/chatnio/monitor.log
fi
 
# Check memory usage
MEM_USAGE=$(free | awk 'NR==2{printf "%.0f", $3/$2*100}')
if [ $MEM_USAGE -gt 90 ]; then
    echo "$(date): Memory usage is at ${MEM_USAGE}%" >> /var/log/chatnio/monitor.log
fi

Make executable and add to cron:

sudo chmod +x /usr/local/bin/chatnio-monitor.sh
sudo crontab -e
# Add: */5 * * * * /usr/local/bin/chatnio-monitor.sh

Backup and Recovery

Database Backup

Create backup script (/usr/local/bin/backup-chatnio.sh):

#!/bin/bash
 
BACKUP_DIR="/opt/backups/chatnio"
DATE=$(date +%Y%m%d_%H%M%S)
 
# Create backup directory
mkdir -p $BACKUP_DIR
 
# Backup MySQL database
mysqldump -u chatnio -p'your-secure-password' chatnio > $BACKUP_DIR/chatnio_db_$DATE.sql
 
# Backup configuration
cp -r /opt/chatnio/config.yaml $BACKUP_DIR/config_$DATE.yaml
cp -r /opt/chatnio/.env $BACKUP_DIR/env_$DATE
 
# Backup storage files
tar -czf $BACKUP_DIR/storage_$DATE.tar.gz -C /opt/chatnio storage/
 
# Backup Nginx configuration
cp /etc/nginx/sites-available/chatnio $BACKUP_DIR/nginx_$DATE.conf
 
# Remove old backups (keep 30 days)
find $BACKUP_DIR -name "*.sql" -mtime +30 -delete
find $BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete
find $BACKUP_DIR -name "config_*" -mtime +30 -delete
find $BACKUP_DIR -name "nginx_*" -mtime +30 -delete
 
echo "$(date): Backup completed successfully" >> /var/log/chatnio/backup.log

Schedule backups:

sudo chmod +x /usr/local/bin/backup-chatnio.sh
sudo crontab -e
# Add: 0 2 * * * /usr/local/bin/backup-chatnio.sh

Updates and Maintenance

Application Updates

Create update script (/usr/local/bin/update-chatnio.sh):

#!/bin/bash
 
cd /opt/chatnio
 
# Backup current version
cp chatnio chatnio.backup
 
# Pull latest changes
sudo -u chatnio git pull origin main
 
# Build frontend
cd app
sudo -u chatnio pnpm install
sudo -u chatnio pnpm build
 
# Build backend
cd ..
sudo -u chatnio go build -ldflags="-s -w" -o chatnio
 
# Restart service
systemctl restart chatnio
 
# Test service
sleep 10
if systemctl is-active --quiet chatnio; then
    echo "$(date): Update completed successfully" >> /var/log/chatnio/update.log
else
    echo "$(date): Update failed, rolling back" >> /var/log/chatnio/update.log
    cp chatnio.backup chatnio
    systemctl restart chatnio
fi

Troubleshooting

Common Issues

Service Won't Start:

# Check service status
sudo systemctl status chatnio -l
 
# Check application logs
sudo journalctl -u chatnio -f
 
# Check configuration
sudo -u chatnio /opt/chatnio/chatnio --check-config

Database Connection Issues:

# Test MySQL connection
mysql -u chatnio -p -h localhost chatnio
 
# Check MySQL logs
sudo tail -f /var/log/mysql/error.log

Performance Issues:

# Monitor resource usage
htop
iotop
nethogs
 
# Check application performance
curl -w "@curl-format.txt" -o /dev/null -s "http://localhost:8094/api/health"

Security Note

Traditional deployments require careful attention to security. Regularly update all components, monitor logs, and follow security best practices for your operating system and applications.

Traditional server deployment provides maximum control and flexibility, making it ideal for enterprise environments where specific compliance requirements or existing infrastructure constraints make containerized deployments impractical.