refactor: v2

backend & frontend
This commit is contained in:
2026-01-01 18:38:21 +08:00
parent 3d201bc497
commit fdc725b893
109 changed files with 22918 additions and 1135 deletions
+474
View File
@@ -0,0 +1,474 @@
# CheckIn App V2 - Deployment Guide
This guide explains how to deploy CheckIn App V2 to a production server using Nginx and systemd.
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Server Setup](#server-setup)
3. [Application Setup](#application-setup)
4. [Nginx Configuration](#nginx-configuration)
5. [Systemd Service Setup](#systemd-service-setup)
6. [SSL/TLS Certificate](#ssltls-certificate)
7. [Monitoring and Logs](#monitoring-and-logs)
8. [Troubleshooting](#troubleshooting)
---
## Prerequisites
- **Operating System**: Ubuntu 20.04+ or similar Linux distribution
- **Python**: 3.9 or higher
- **Node.js**: 16+ (for building frontend)
- **Nginx**: 1.18 or higher
- **Domain name** (optional but recommended for SSL)
### Install Required Packages
```bash
# Update system
sudo apt update && sudo apt upgrade -y
# Install Python and tools
sudo apt install -y python3 python3-pip python3-venv
# Install Node.js (using NodeSource)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# Install Nginx
sudo apt install -y nginx
# Install other dependencies
sudo apt install -y git curl wget
```
---
## Server Setup
### 1. Create Application User
```bash
# Create a dedicated user for the application
sudo useradd -r -m -s /bin/bash checkin
sudo usermod -aG www-data checkin
```
### 2. Create Application Directory
```bash
# Create directory structure
sudo mkdir -p /opt/checkin-app
sudo chown -R checkin:www-data /opt/checkin-app
# Create required subdirectories
sudo -u checkin mkdir -p /opt/checkin-app/{data,logs,sessions}
```
---
## Application Setup
### 1. Clone Repository
```bash
# Switch to application user
sudo su - checkin
# Clone the repository
cd /opt/checkin-app
git clone https://github.com/your-repo/checkin-app.git .
# Or upload your files using scp/rsync
```
### 2. Setup Backend
```bash
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# Install Python dependencies
pip install -r backend/requirements.txt
# Create .env file
cp .env.example .env
# Edit .env and configure your settings
nano .env
```
**Important Environment Variables:**
```env
# Database
DATABASE_URL=sqlite:///./data/checkin.db
# Security
SECRET_KEY=your-secret-key-here-change-this
ALLOWED_ORIGINS=https://your-domain.com
# QQ Login (if applicable)
QQ_APPID=your-qq-appid
QQ_APPSECRET=your-qq-appsecret
# Email notifications (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
ADMIN_EMAIL=admin@your-domain.com
```
### 3. Initialize Database
```bash
# Run database migrations if needed
# Example:
# alembic upgrade head
# Or run initialization script
python backend/scripts/create_admin.py
```
### 4. Build Frontend
```bash
# Install frontend dependencies
cd frontend
npm install
# Build for production
npm run build
# Verify build output
ls -lh dist/
```
### 5. Set Permissions
```bash
# Exit from checkin user
exit
# Set proper permissions
sudo chown -R checkin:www-data /opt/checkin-app
sudo chmod -R 755 /opt/checkin-app
sudo chmod -R 775 /opt/checkin-app/{data,logs,sessions}
```
---
## Nginx Configuration
### 1. Copy Configuration
```bash
# Copy example configuration
sudo cp /opt/checkin-app/deployment/nginx.conf.example /etc/nginx/sites-available/checkin-app
# Edit configuration
sudo nano /etc/nginx/sites-available/checkin-app
```
### 2. Update Configuration
Replace the following placeholders:
- `your-domain.com` → Your actual domain name
- `/opt/checkin-app` → Your installation path (if different)
### 3. Enable Site
```bash
# Create symbolic link
sudo ln -s /etc/nginx/sites-available/checkin-app /etc/nginx/sites-enabled/
# Remove default site (optional)
sudo rm /etc/nginx/sites-enabled/default
# Test Nginx configuration
sudo nginx -t
# Reload Nginx
sudo systemctl reload nginx
```
---
## Systemd Service Setup
### 1. Copy Service File
```bash
# Copy example service file
sudo cp /opt/checkin-app/deployment/checkin-app.service.example /etc/systemd/system/checkin-app.service
# Edit service file
sudo nano /etc/systemd/system/checkin-app.service
```
### 2. Update Service File
Replace placeholders:
- `User=www-data``User=checkin` (if using dedicated user)
- `WorkingDirectory=/opt/checkin-app` → Your installation path
- Adjust paths in `ExecStart` if needed
### 3. Enable and Start Service
```bash
# Reload systemd
sudo systemctl daemon-reload
# Enable service (start on boot)
sudo systemctl enable checkin-app.service
# Start service
sudo systemctl start checkin-app.service
# Check status
sudo systemctl status checkin-app.service
# View logs
sudo journalctl -u checkin-app -f
```
---
## SSL/TLS Certificate
### Using Let's Encrypt (Recommended)
```bash
# Install Certbot
sudo apt install -y certbot python3-certbot-nginx
# Obtain certificate
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
# Follow the prompts to configure SSL
# Test auto-renewal
sudo certbot renew --dry-run
```
The Certbot will automatically update your Nginx configuration with SSL settings.
### Manual Certificate Setup
If you have your own SSL certificate:
```bash
# Copy certificate files
sudo mkdir -p /etc/nginx/ssl
sudo cp your-cert.crt /etc/nginx/ssl/
sudo cp your-key.key /etc/nginx/ssl/
# Set permissions
sudo chmod 600 /etc/nginx/ssl/your-key.key
# Update Nginx configuration with certificate paths
```
---
## Monitoring and Logs
### Service Logs
```bash
# View service logs
sudo journalctl -u checkin-app -f
# View last 100 lines
sudo journalctl -u checkin-app -n 100
# View logs since yesterday
sudo journalctl -u checkin-app --since yesterday
```
### Application Logs
```bash
# Backend logs
tail -f /opt/checkin-app/logs/backend.log
# Nginx access logs
sudo tail -f /var/log/nginx/checkin-app-access.log
# Nginx error logs
sudo tail -f /var/log/nginx/checkin-app-error.log
```
### Service Status
```bash
# Check service status
sudo systemctl status checkin-app
# Check if port is listening
sudo netstat -tlnp | grep :8000
# Check process
ps aux | grep python
```
---
## Troubleshooting
### Service Won't Start
```bash
# Check service logs
sudo journalctl -u checkin-app -xe
# Check if port is already in use
sudo lsof -i :8000
# Verify permissions
ls -la /opt/checkin-app/
# Test manual start
sudo -u checkin /opt/checkin-app/venv/bin/python /opt/checkin-app/run_daemon.py
```
### Nginx Errors
```bash
# Test Nginx configuration
sudo nginx -t
# Check error logs
sudo tail -f /var/log/nginx/error.log
# Verify backend is running
curl http://localhost:8000/health
```
### Database Issues
```bash
# Check database file permissions
ls -la /opt/checkin-app/data/
# Check if database is locked
fuser /opt/checkin-app/data/checkin.db
# Backup database
cp /opt/checkin-app/data/checkin.db /opt/checkin-app/data/checkin.db.backup
```
### Frontend Not Loading
```bash
# Verify build exists
ls -la /opt/checkin-app/frontend/dist/
# Check Nginx configuration for root path
grep -n "root" /etc/nginx/sites-available/checkin-app
# Clear browser cache or test with curl
curl -I https://your-domain.com/
```
---
## Updating the Application
### Update Backend
```bash
# Switch to application user
sudo su - checkin
cd /opt/checkin-app
# Pull latest changes
git pull
# Activate virtual environment
source venv/bin/activate
# Update dependencies
pip install -r backend/requirements.txt
# Run migrations if needed
# alembic upgrade head
# Exit and restart service
exit
sudo systemctl restart checkin-app
```
### Update Frontend
```bash
sudo su - checkin
cd /opt/checkin-app/frontend
# Pull latest changes
git pull
# Install dependencies
npm install
# Build
npm run build
# Exit
exit
# No need to restart - Nginx serves static files
```
---
## Security Recommendations
1. **Firewall**: Use `ufw` to restrict access
```bash
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw enable
```
2. **Regular Updates**: Keep system and packages updated
```bash
sudo apt update && sudo apt upgrade
```
3. **Backup**: Regular backups of database and configuration
```bash
# Create backup script
sudo nano /opt/checkin-app/backup.sh
```
4. **Monitoring**: Consider using monitoring tools like Prometheus, Grafana, or Uptime Kuma
5. **Rate Limiting**: Configure Nginx rate limiting for API endpoints
---
## Additional Resources
- [Nginx Documentation](https://nginx.org/en/docs/)
- [Systemd Documentation](https://www.freedesktop.org/software/systemd/man/)
- [Let's Encrypt](https://letsencrypt.org/)
- [FastAPI Deployment](https://fastapi.tiangolo.com/deployment/)
---
## Support
For issues or questions, please:
- Check the logs first
- Review this guide carefully
- Open an issue on GitHub
- Contact system administrator
+307
View File
@@ -0,0 +1,307 @@
# Deployment Files
This directory contains configuration files and scripts for deploying CheckIn App V2 to a production server.
## Files
- **`nginx.conf.example`** - Nginx reverse proxy configuration
- **`checkin-app.service.example`** - Systemd service file
- **`deploy.sh`** - Automated deployment script
- **`DEPLOYMENT.md`** - Comprehensive deployment guide
## Quick Start
### Option 1: Automated Deployment (Recommended)
```bash
# Make script executable
chmod +x deployment/deploy.sh
# Run installation
sudo deployment/deploy.sh install
```
### Option 2: Manual Deployment
Follow the step-by-step guide in [DEPLOYMENT.md](./DEPLOYMENT.md).
## Deployment Script Usage
The `deploy.sh` script provides three main commands:
### 1. Install (First-time deployment)
```bash
sudo deployment/deploy.sh install
```
This will:
- Check system dependencies
- Create application user
- Setup virtual environment
- Install Python dependencies
- Build frontend
- Configure systemd service
- Configure Nginx
- Start all services
### 2. Update (Update existing installation)
```bash
sudo deployment/deploy.sh update
```
This will:
- Backup database
- Pull latest changes (if using git)
- Update Python dependencies
- Rebuild frontend
- Restart services
### 3. Rollback (Revert to previous version)
```bash
sudo deployment/deploy.sh rollback
```
This will:
- Stop services
- Restore database from latest backup
- Restart services
## Configuration Files
### Nginx Configuration
Edit `/etc/nginx/sites-available/checkin-app` and update:
- `server_name` - Your domain name
- `ssl_certificate` and `ssl_certificate_key` - SSL certificate paths
- `root` - Frontend build directory path (usually `/opt/checkin-app/frontend/dist`)
### Systemd Service
Edit `/etc/systemd/system/checkin-app.service` and update:
- `User` and `Group` - Application user (default: `checkin`)
- `WorkingDirectory` - Application directory (default: `/opt/checkin-app`)
- `ExecStart` - Path to Python executable and run script
### Environment Variables
Create and configure `.env` file in the application root:
```bash
sudo nano /opt/checkin-app/.env
```
Required variables:
```env
# Database
DATABASE_URL=sqlite:///./data/checkin.db
# Security
SECRET_KEY=your-secret-key-here
ALLOWED_ORIGINS=https://your-domain.com
# QQ Login
QQ_APPID=your-appid
QQ_APPSECRET=your-appsecret
```
## SSL Certificate Setup
### Using Let's Encrypt (Recommended)
```bash
# Install Certbot
sudo apt install certbot python3-certbot-nginx
# Obtain certificate
sudo certbot --nginx -d your-domain.com
# Auto-renewal is configured automatically
```
### Manual Certificate
If you have your own SSL certificate:
1. Copy certificate files to `/etc/nginx/ssl/`
2. Update Nginx configuration with correct paths
3. Reload Nginx: `sudo systemctl reload nginx`
## Service Management
### Start Service
```bash
sudo systemctl start checkin-app
```
### Stop Service
```bash
sudo systemctl stop checkin-app
```
### Restart Service
```bash
sudo systemctl restart checkin-app
```
### Check Status
```bash
sudo systemctl status checkin-app
```
### View Logs
```bash
# Application logs
sudo journalctl -u checkin-app -f
# Nginx access logs
sudo tail -f /var/log/nginx/checkin-app-access.log
# Nginx error logs
sudo tail -f /var/log/nginx/checkin-app-error.log
```
## Directory Structure
After deployment, the application structure should look like:
```
/opt/checkin-app/
├── backend/ # Backend Python code
│ ├── api/
│ ├── models/
│ ├── services/
│ └── ...
├── frontend/ # Frontend source code
│ ├── src/
│ ├── dist/ # Built static files (served by Nginx)
│ └── ...
├── venv/ # Python virtual environment
├── data/ # SQLite database
├── logs/ # Application logs
├── sessions/ # Session data
├── deployment/ # Deployment files (this directory)
├── .env # Environment variables
└── run_daemon.py # Application entry point
```
## Troubleshooting
### Service won't start
```bash
# Check logs
sudo journalctl -u checkin-app -xe
# Verify configuration
sudo -u checkin /opt/checkin-app/venv/bin/python /opt/checkin-app/run_daemon.py
```
### Nginx configuration errors
```bash
# Test configuration
sudo nginx -t
# Check error logs
sudo tail -f /var/log/nginx/error.log
```
### Database locked
```bash
# Check what's using the database
sudo fuser /opt/checkin-app/data/checkin.db
# Kill the process if needed
sudo fuser -k /opt/checkin-app/data/checkin.db
```
### Permission issues
```bash
# Fix ownership
sudo chown -R checkin:www-data /opt/checkin-app
# Fix permissions
sudo chmod -R 755 /opt/checkin-app
sudo chmod -R 775 /opt/checkin-app/{data,logs,sessions}
```
## Security Best Practices
1. **Keep system updated**
```bash
sudo apt update && sudo apt upgrade
```
2. **Use firewall**
```bash
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw enable
```
3. **Regular backups**
```bash
# Backup database
sudo -u checkin cp /opt/checkin-app/data/checkin.db /backup/checkin-$(date +%Y%m%d).db
```
4. **Monitor logs**
```bash
# Setup log rotation
sudo nano /etc/logrotate.d/checkin-app
```
5. **Use strong passwords** and **secure SECRET_KEY**
## Performance Tuning
### Nginx
- Enable gzip compression (already configured)
- Configure caching headers (already configured)
- Adjust worker processes based on CPU cores
### Backend
- Increase uvicorn workers in service file:
```
ExecStart=/opt/checkin-app/venv/bin/uvicorn backend.main:app --workers 4
```
- Consider using Gunicorn with uvicorn workers for production
### Database
- For high traffic, consider switching to PostgreSQL
- Regular VACUUM for SQLite
## Monitoring
Consider setting up monitoring tools:
- **Uptime monitoring**: Uptime Kuma, UptimeRobot
- **Log aggregation**: Loki, ELK Stack
- **Metrics**: Prometheus + Grafana
- **Error tracking**: Sentry
## Support
For detailed deployment instructions, see [DEPLOYMENT.md](./DEPLOYMENT.md).
For issues or questions:
- Check application logs
- Review troubleshooting section
- Open an issue on GitHub
+100
View File
@@ -0,0 +1,100 @@
# ==============================================================================
# CheckIn App V2 - Systemd Service File Example
# ==============================================================================
#
# This file defines a systemd service for running the CheckIn App backend
#
# Installation:
# 1. Copy this file: sudo cp checkin-app.service.example /etc/systemd/system/checkin-app.service
# 2. Edit the file and replace placeholders with your actual values
# 3. Reload systemd: sudo systemctl daemon-reload
# 4. Enable service: sudo systemctl enable checkin-app.service
# 5. Start service: sudo systemctl start checkin-app.service
# 6. Check status: sudo systemctl status checkin-app.service
#
# Management Commands:
# Start: sudo systemctl start checkin-app
# Stop: sudo systemctl stop checkin-app
# Restart: sudo systemctl restart checkin-app
# Status: sudo systemctl status checkin-app
# Logs: sudo journalctl -u checkin-app -f
#
# ==============================================================================
[Unit]
# Service description
Description=CheckIn App V2 - Backend API Service
Documentation=https://github.com/your-repo/checkin-app
# Start after network and database are available
After=network.target
Wants=network-online.target
[Service]
# Service type
Type=simple
# User and Group
# IMPORTANT: Replace 'www-data' with your actual user
# Create a dedicated user: sudo useradd -r -s /bin/false checkin
User=www-data
Group=www-data
# Working directory
# IMPORTANT: Replace with your actual installation path
WorkingDirectory=/opt/checkin-app
# Environment variables
Environment="PATH=/opt/checkin-app/venv/bin:/usr/local/bin:/usr/bin:/bin"
Environment="PYTHONPATH=/opt/checkin-app"
# Load environment variables from .env file (optional)
EnvironmentFile=-/opt/checkin-app/.env
# Command to start the service
# Using uvicorn directly for production
ExecStart=/opt/checkin-app/venv/bin/python /opt/checkin-app/run_daemon.py
# Alternative: Using uvicorn directly with more control
# ExecStart=/opt/checkin-app/venv/bin/uvicorn backend.main:app \
# --host 0.0.0.0 \
# --port 8000 \
# --workers 4 \
# --log-level info \
# --access-log \
# --proxy-headers
# Restart policy
Restart=always
RestartSec=10
# Kill signal
KillSignal=SIGTERM
KillMode=mixed
# Timeout settings
TimeoutStartSec=60
TimeoutStopSec=30
# Resource limits (optional)
LimitNOFILE=65535
# LimitNPROC=4096
# MemoryLimit=2G
# CPUQuota=200%
# Security settings (optional but recommended)
# Restrict access to the filesystem
# ReadWritePaths=/opt/checkin-app/data /opt/checkin-app/logs /opt/checkin-app/sessions
# ReadOnlyPaths=/opt/checkin-app
# Prevent privilege escalation
NoNewPrivileges=true
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=checkin-app
[Install]
# Start on boot
WantedBy=multi-user.target
+358
View File
@@ -0,0 +1,358 @@
#!/bin/bash
# ==============================================================================
# CheckIn App V2 - Quick Deployment Script
# ==============================================================================
#
# This script automates the deployment process for CheckIn App V2
#
# Usage:
# sudo ./deploy.sh [install|update|rollback]
#
# ==============================================================================
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Configuration
APP_NAME="checkin-app"
APP_USER="checkin"
APP_DIR="/opt/checkin-app"
SERVICE_NAME="checkin-app.service"
NGINX_CONFIG="checkin-app"
# Functions
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
check_root() {
if [ "$EUID" -ne 0 ]; then
log_error "This script must be run as root (use sudo)"
exit 1
fi
}
check_dependencies() {
log_info "Checking dependencies..."
local missing_deps=()
# Check Python
if ! command -v python3 &> /dev/null; then
missing_deps+=("python3")
fi
# Check Node.js
if ! command -v node &> /dev/null; then
missing_deps+=("nodejs")
fi
# Check Nginx
if ! command -v nginx &> /dev/null; then
missing_deps+=("nginx")
fi
if [ ${#missing_deps[@]} -ne 0 ]; then
log_error "Missing dependencies: ${missing_deps[*]}"
log_info "Please install them first:"
log_info " sudo apt install -y python3 python3-pip python3-venv nodejs nginx"
exit 1
fi
log_info "All dependencies are installed"
}
create_user() {
if id "$APP_USER" &>/dev/null; then
log_info "User $APP_USER already exists"
else
log_info "Creating user $APP_USER..."
useradd -r -m -s /bin/bash "$APP_USER"
usermod -aG www-data "$APP_USER"
log_info "User $APP_USER created"
fi
}
create_directories() {
log_info "Creating application directories..."
mkdir -p "$APP_DIR"
chown -R "$APP_USER:www-data" "$APP_DIR"
sudo -u "$APP_USER" mkdir -p "$APP_DIR"/{data,logs,sessions}
log_info "Directories created"
}
setup_backend() {
log_info "Setting up backend..."
cd "$APP_DIR"
# Create virtual environment
if [ ! -d "venv" ]; then
log_info "Creating virtual environment..."
sudo -u "$APP_USER" python3 -m venv venv
fi
# Install dependencies
log_info "Installing Python dependencies..."
sudo -u "$APP_USER" bash -c "source venv/bin/activate && pip install --upgrade pip && pip install -r backend/requirements.txt"
# Create .env if not exists
if [ ! -f ".env" ]; then
log_warn ".env file not found, please create one from .env.example"
if [ -f ".env.example" ]; then
sudo -u "$APP_USER" cp .env.example .env
log_info "Created .env from .env.example - please configure it"
fi
fi
log_info "Backend setup complete"
}
build_frontend() {
log_info "Building frontend..."
cd "$APP_DIR/frontend"
# Install dependencies
if [ ! -d "node_modules" ]; then
log_info "Installing Node.js dependencies..."
sudo -u "$APP_USER" npm install
fi
# Build
log_info "Building frontend for production..."
sudo -u "$APP_USER" npm run build
if [ -d "dist" ]; then
log_info "Frontend built successfully"
else
log_error "Frontend build failed - dist directory not found"
exit 1
fi
}
setup_systemd() {
log_info "Setting up systemd service..."
if [ -f "$APP_DIR/deployment/checkin-app.service.example" ]; then
# Copy service file
cp "$APP_DIR/deployment/checkin-app.service.example" "/etc/systemd/system/$SERVICE_NAME"
# Reload systemd
systemctl daemon-reload
# Enable service
systemctl enable "$SERVICE_NAME"
log_info "Systemd service configured"
else
log_error "Service file not found: $APP_DIR/deployment/checkin-app.service.example"
exit 1
fi
}
setup_nginx() {
log_info "Setting up Nginx configuration..."
if [ -f "$APP_DIR/deployment/nginx.conf.example" ]; then
# Copy Nginx config
cp "$APP_DIR/deployment/nginx.conf.example" "/etc/nginx/sites-available/$NGINX_CONFIG"
# Create symlink
if [ ! -L "/etc/nginx/sites-enabled/$NGINX_CONFIG" ]; then
ln -s "/etc/nginx/sites-available/$NGINX_CONFIG" "/etc/nginx/sites-enabled/$NGINX_CONFIG"
fi
# Test Nginx config
if nginx -t; then
log_info "Nginx configuration is valid"
else
log_error "Nginx configuration test failed"
exit 1
fi
log_warn "Please edit /etc/nginx/sites-available/$NGINX_CONFIG and configure your domain"
else
log_error "Nginx config file not found: $APP_DIR/deployment/nginx.conf.example"
exit 1
fi
}
start_services() {
log_info "Starting services..."
# Start application
systemctl start "$SERVICE_NAME"
# Reload Nginx
systemctl reload nginx
# Check status
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
log_info "Application service started successfully"
else
log_error "Application service failed to start"
systemctl status "$SERVICE_NAME"
exit 1
fi
log_info "All services started"
}
install() {
log_info "Starting installation..."
check_root
check_dependencies
create_user
create_directories
setup_backend
build_frontend
setup_systemd
setup_nginx
# Set permissions
chown -R "$APP_USER:www-data" "$APP_DIR"
chmod -R 755 "$APP_DIR"
chmod -R 775 "$APP_DIR"/{data,logs,sessions}
start_services
echo ""
log_info "================================================"
log_info "Installation complete!"
log_info "================================================"
echo ""
log_info "Next steps:"
log_info "1. Configure .env file: sudo nano $APP_DIR/.env"
log_info "2. Configure Nginx: sudo nano /etc/nginx/sites-available/$NGINX_CONFIG"
log_info "3. Set up SSL certificate: sudo certbot --nginx -d your-domain.com"
log_info "4. Restart services: sudo systemctl restart $SERVICE_NAME nginx"
echo ""
log_info "Useful commands:"
log_info " Status: sudo systemctl status $SERVICE_NAME"
log_info " Logs: sudo journalctl -u $SERVICE_NAME -f"
log_info " Restart: sudo systemctl restart $SERVICE_NAME"
echo ""
}
update() {
log_info "Updating application..."
check_root
cd "$APP_DIR"
# Backup database
if [ -f "data/checkin.db" ]; then
log_info "Backing up database..."
sudo -u "$APP_USER" cp data/checkin.db "data/checkin.db.backup.$(date +%Y%m%d_%H%M%S)"
fi
# Pull latest changes (if using git)
if [ -d ".git" ]; then
log_info "Pulling latest changes..."
sudo -u "$APP_USER" git pull
fi
# Update backend
log_info "Updating backend dependencies..."
sudo -u "$APP_USER" bash -c "source venv/bin/activate && pip install -r backend/requirements.txt"
# Rebuild frontend
build_frontend
# Restart service
log_info "Restarting service..."
systemctl restart "$SERVICE_NAME"
# Check status
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
log_info "Update completed successfully"
else
log_error "Service failed to start after update"
systemctl status "$SERVICE_NAME"
exit 1
fi
}
rollback() {
log_info "Rolling back to previous version..."
check_root
cd "$APP_DIR"
# Find latest backup
LATEST_BACKUP=$(ls -t data/checkin.db.backup.* 2>/dev/null | head -n 1)
if [ -z "$LATEST_BACKUP" ]; then
log_error "No database backup found"
exit 1
fi
log_info "Found backup: $LATEST_BACKUP"
# Stop service
systemctl stop "$SERVICE_NAME"
# Restore database
log_info "Restoring database..."
sudo -u "$APP_USER" cp "$LATEST_BACKUP" data/checkin.db
# Rollback git (if using git)
if [ -d ".git" ]; then
log_warn "Please manually rollback git to the desired commit"
log_info "Example: git reset --hard <commit-hash>"
fi
# Start service
systemctl start "$SERVICE_NAME"
log_info "Rollback completed"
}
# Main
case "${1:-}" in
install)
install
;;
update)
update
;;
rollback)
rollback
;;
*)
echo "CheckIn App V2 - Deployment Script"
echo ""
echo "Usage: $0 {install|update|rollback}"
echo ""
echo "Commands:"
echo " install - Full installation (first time)"
echo " update - Update existing installation"
echo " rollback - Rollback to previous version"
echo ""
exit 1
;;
esac
exit 0
+216
View File
@@ -0,0 +1,216 @@
# ==============================================================================
# CheckIn App V2 - Nginx Configuration Example
# ==============================================================================
#
# Usage:
# 1. Copy this file: sudo cp nginx.conf.example /etc/nginx/sites-available/checkin-app
# 2. Edit the file and replace placeholders with your actual values
# 3. Create symlink: sudo ln -s /etc/nginx/sites-available/checkin-app /etc/nginx/sites-enabled/
# 4. Test config: sudo nginx -t
# 5. Reload Nginx: sudo systemctl reload nginx
#
# ==============================================================================
# Upstream backend API server
upstream checkin_backend {
# Backend FastAPI server running on port 8000
server 127.0.0.1:8000;
# Optional: Add more backend servers for load balancing
# server 127.0.0.1:8001;
# server 127.0.0.1:8002;
# Keep alive connections
keepalive 32;
}
# HTTP Server - Redirect to HTTPS (optional)
server {
listen 80;
listen [::]:80;
server_name your-domain.com www.your-domain.com;
# Redirect all HTTP traffic to HTTPS
return 301 https://$server_name$request_uri;
}
# HTTPS Server
server {
# SSL Configuration
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name your-domain.com www.your-domain.com;
# SSL Certificate (Let's Encrypt recommended)
ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
# SSL Configuration (Modern)
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;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Security Headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Root directory for frontend static files
root /opt/checkin-app/frontend/dist;
index index.html;
# Access and Error Logs
access_log /var/log/nginx/checkin-app-access.log;
error_log /var/log/nginx/checkin-app-error.log;
# Gzip Compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json application/javascript;
# Client body size (for file uploads)
client_max_body_size 10M;
# ==========================================
# API Proxy Configuration
# ==========================================
location /api/ {
# Proxy to backend
proxy_pass http://checkin_backend;
# Proxy headers
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 (if needed)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Buffering
proxy_buffering off;
proxy_request_buffering off;
}
# API Documentation
location /docs {
proxy_pass http://checkin_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;
}
location /redoc {
proxy_pass http://checkin_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;
}
location /openapi.json {
proxy_pass http://checkin_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;
}
# ==========================================
# Frontend Static Files
# ==========================================
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# Frontend routes (SPA)
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# Favicon
location = /favicon.ico {
log_not_found off;
access_log off;
}
# Robots.txt
location = /robots.txt {
log_not_found off;
access_log off;
}
# Health check endpoint
location /health {
proxy_pass http://checkin_backend;
access_log off;
}
}
# ==============================================================================
# Alternative: HTTP-only configuration (for development/internal use)
# ==============================================================================
# Uncomment below if you don't need HTTPS
# server {
# listen 80;
# listen [::]:80;
# server_name your-domain.com;
#
# root /opt/checkin-app/frontend/dist;
# index index.html;
#
# access_log /var/log/nginx/checkin-app-access.log;
# error_log /var/log/nginx/checkin-app-error.log;
#
# gzip on;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
#
# client_max_body_size 10M;
#
# # API Proxy
# location /api/ {
# proxy_pass http://127.0.0.1:8000;
# 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_http_version 1.1;
# proxy_buffering off;
# }
#
# # API Documentation
# location ~ ^/(docs|redoc|openapi.json) {
# proxy_pass http://127.0.0.1:8000;
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# }
#
# # Static files
# location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
# expires 1y;
# add_header Cache-Control "public";
# }
#
# # Frontend routes
# location / {
# try_files $uri $uri/ /index.html;
# }
# }