# 🦟 蚊子项目 - 生产环境部署指南 ## 📋 部署概览 本文档提供蚊子项目的完整生产环境部署指南,包括基础设施准备、应用部署、监控配置等。 ### 架构设计 ``` ┌─────────────────────────────────────────────────────────┐ │ 负载均衡器 (Nginx) │ │ SSL/TLS终止 │ └──────────────────┬──────────────────────────────────────┘ │ ┌──────────┴──────────┐ │ │ ┌───────▼────────┐ ┌────────▼────────┐ │ 应用服务器1 │ │ 应用服务器2 │ │ Spring Boot │ │ Spring Boot │ │ :8080 │ │ :8080 │ └───────┬────────┘ └────────┬────────┘ │ │ └──────────┬──────────┘ │ ┌──────────┴──────────┐ │ │ ┌───────▼────────┐ ┌────────▼────────┐ │ PostgreSQL │ │ Redis │ │ :5432 │ │ :6379 │ └────────────────┘ └────────────────┘ ``` ## 🖥️ 环境要求 ### 硬件配置 | 组件 | 最小配置 | 推荐配置 | 生产配置 | |------|----------|----------|----------| | **CPU** | 2核 | 4核 | 8核+ | | **内存** | 4GB | 8GB | 16GB+ | | **磁盘** | 50GB SSD | 100GB SSD | 200GB+ SSD | | **网络** | 100Mbps | 1Gbps | 10Gbps | ### 软件环境 | 软件 | 版本要求 | 用途 | |------|----------|------| | Java JDK | 17+ | 运行环境 | | PostgreSQL | 14+ | 数据库 | | Redis | 7+ | 缓存 | | Nginx | 1.20+ | 负载均衡 | | Docker | 24+ | 容器化(可选) | | Kubernetes | 1.27+ | 容器编排(可选) | --- ## 🚀 部署方式一:传统部署(推荐用于中小型项目) ### 1. 基础设施准备 #### 1.1 安装Java 17 ```bash # Ubuntu/Debian sudo apt update sudo apt install -y openjdk-17-jdk # 验证安装 java -version javac -version # 配置JAVA_HOME echo 'export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64' >> ~/.bashrc source ~/.bashrc ``` #### 1.2 安装PostgreSQL 14 ```bash # 添加PostgreSQL仓库 sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' sudo apt install wget ca-certificates wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - sudo apt update # 安装PostgreSQL sudo apt install -y postgresql-14 postgresql-contrib-14 # 启动服务 sudo systemctl start postgresql sudo systemctl enable postgresql # 创建数据库和用户 sudo -u postgres psql << EOF CREATE DATABASE mosquito_prod; CREATE USER mosquito_user WITH ENCRYPTED PASSWORD 'your_strong_password_here'; GRANT ALL PRIVILEGES ON DATABASE mosquito_prod TO mosquito_user; \q EOF # 配置远程访问 sudo nano /etc/postgresql/14/main/postgresql.conf # 修改以下行: # listen_addresses = '*' # max_connections = 200 sudo nano /etc/postgresql/14/main/pg_hba.conf # 添加以下行: # host mosquito_prod mosquito_user 0.0.0.0/0 scram-sha-256 # 重启服务 sudo systemctl restart postgresql ``` #### 1.3 安装Redis 7 ```bash # 安装Redis sudo apt update sudo apt install -y redis-server # 配置Redis sudo nano /etc/redis/redis.conf # 修改以下配置: # bind 127.0.0.1 # port 6379 # requirepass your_redis_password_here # maxmemory 2gb # maxmemory-policy allkeys-lru # 启动Redis sudo systemctl start redis sudo systemctl enable redis # 验证安装 redis-cli ping ``` ### 2. 应用部署 #### 2.1 构建应用 ```bash # 克隆项目 git clone https://github.com/your-org/mosquito.git cd mosquito # 配置生产环境变量 cat > .env.prod << EOF # 数据库配置 SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/mosquito_prod SPRING_DATASOURCE_USERNAME=mosquito_user SPRING_DATASOURCE_PASSWORD=your_strong_password_here # Redis配置 SPRING_REDIS_HOST=localhost SPRING_REDIS_PORT=6379 SPRING_REDIS_PASSWORD=your_redis_password_here # 应用配置 SPRING_PROFILES_ACTIVE=prod SERVER_PORT=8080 SERVER_ADDRESS=0.0.0.0 # 安全配置 APP_SECURITY_API_KEY_ITERATIONS=185000 APP_RATE_LIMIT_PER_MINUTE=100 # 日志配置 LOGGING_LEVEL_ROOT=INFO LOGGING_LEVEL_COM_MOSQUIO_PROJECT=DEBUG # 性能配置 SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE=20 SPRING_DATASOURCE_HIKARI_MINIMUM_IDLE=5 SPRING_DATASOURCE_HIKARI_CONNECTION_TIMEOUT=30000 SPRING_DATASOURCE_HIKARI_MAX_LIFETIME=1800000 EOF # 构建应用 mvn clean package -DskipTests -Dspring-boot.run.profiles=prod # 验证构建 ls -lh target/mosquito-*.jar ``` #### 2.2 部署应用 ```bash # 创建应用目录 sudo mkdir -p /opt/mosquito sudo mkdir -p /var/log/mosquito sudo mkdir -p /etc/mosquito # 复制JAR文件 sudo cp target/mosquito-0.0.1-SNAPSHOT.jar /opt/mosquito/mosquito.jar sudo chmod +x /opt/mosquito/mosquito.jar # 复制环境配置 sudo cp .env.prod /etc/mosquito/application-prod.properties # 创建系统服务 sudo tee /etc/systemd/system/mosquito.service > /dev/null << 'EOF' [Unit] Description=Mosquito Application After=network.target postgresql.service redis.service [Service] Type=simple User=mosquito Group=mosquito WorkingDirectory=/opt/mosquito Environment="JAVA_OPTS=-Xms512m -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200" EnvironmentFile=/etc/mosquito/application-prod.properties ExecStart=/usr/bin/java $JAVA_OPTS -jar /opt/mosquito/mosquito.jar ExecStop=/bin/kill -15 $MAINPID Restart=always RestartSec=10 StandardOutput=append:/var/log/mosquito/application.log StandardError=append:/var/log/mosquito/error.log LimitNOFILE=65536 UMask=007 [Install] WantedBy=multi-user.target EOF # 创建应用用户 sudo useradd -r -s /bin/false mosquito sudo chown -R mosquito:mosquito /opt/mosquito sudo chown -R mosquito:mosquito /var/log/mosquito sudo chown -R mosquito:mosquito /etc/mosquito # 启动服务 sudo systemctl daemon-reload sudo systemctl enable mosquito sudo systemctl start mosquito # 查看服务状态 sudo systemctl status mosquito # 查看日志 sudo tail -f /var/log/mosquito/application.log ``` #### 2.3 数据库迁移 ```bash # 自动执行Flyway迁移 sudo systemctl restart mosquito # 或者手动执行迁移 java -jar /opt/mosquito/mosquito.jar \ --spring.profiles.active=prod \ --spring.flyway.enabled=true \ --spring.flyway.locations=classpath:db/migration # 验证迁移 sudo -u postgres psql -d mosquito_prod -c "\dt" ``` ### 3. Nginx配置 #### 3.1 安装Nginx ```bash sudo apt install -y nginx # 创建SSL证书(使用Let's Encrypt) sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d api.yourdomain.com ``` #### 3.2 配置反向代理 ```bash # 创建Nginx配置文件 sudo tee /etc/nginx/sites-available/mosquito-api > /dev/null << 'EOF' upstream mosquito_backend { least_conn; server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; # 添加更多服务器用于负载均衡 # server 127.0.0.1:8081 max_fails=3 fail_timeout=30s; } server { listen 80; server_name api.yourdomain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name api.yourdomain.com; ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # 安全头部 add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; # 访问日志 access_log /var/log/nginx/mosquito-access.log; error_log /var/log/nginx/mosquito-error.log; # 客户端上传大小限制 client_max_body_size 10M; # 代理配置 location / { proxy_pass http://mosquito_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; # 超时配置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # 缓冲配置 proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; } # 健康检查端点(不记录日志) location /actuator/health { proxy_pass http://mosquito_backend; access_log off; } # 静态文件缓存 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { proxy_pass http://mosquito_backend; expires 30d; add_header Cache-Control "public, immutable"; } } EOF # 启用站点配置 sudo ln -s /etc/nginx/sites-available/mosquito-api /etc/nginx/sites-enabled/ # 测试配置 sudo nginx -t # 重启Nginx sudo systemctl restart nginx ``` --- ## 🐳 部署方式二:Docker部署(推荐用于大型项目) ### 1. Docker镜像构建 #### 1.1 创建Dockerfile ```dockerfile # Dockerfile FROM maven:3.9-openjdk-17-slim AS build WORKDIR /app COPY pom.xml . COPY src ./src # 构建应用 RUN mvn clean package -DskipTests # 运行时镜像 FROM openjdk:17-slim # 安装必要的工具 RUN apt-get update && apt-get install -y \ curl \ && rm -rf /var/lib/apt/lists/* WORKDIR /app # 复制构建的JAR文件 COPY --from=build /app/target/mosquito-*.jar app.jar # 创建非root用户 RUN useradd -r -s /bin/false mosquito USER mosquito # 暴露端口 EXPOSE 8080 # JVM参数 ENV JAVA_OPTS="-Xms512m -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200" # 健康检查 HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ CMD curl -f http://localhost:8080/actuator/health || exit 1 # 启动应用 ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"] ``` #### 1.2 构建和推送镜像 ```bash # 构建镜像 docker build -t mosquito-api:latest . # 标记镜像 docker tag mosquito-api:latest your-registry.com/mosquito-api:latest docker tag mosquito-api:latest your-registry.com/mosquito-api:v2.0.0 # 推送到镜像仓库 docker push your-registry.com/mosquito-api:latest docker push your-registry.com/mosquito-api:v2.0.0 ``` ### 2. Docker Compose部署 #### 2.1 创建docker-compose.yml ```yaml version: '3.8' services: postgres: image: postgres:14-alpine container_name: mosquito-postgres restart: unless-stopped environment: POSTGRES_DB: mosquito_prod POSTGRES_USER: mosquito_user POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U mosquito_user"] interval: 10s timeout: 5s retries: 5 networks: - mosquito-network redis: image: redis:7-alpine container_name: mosquito-redis restart: unless-stopped command: redis-server --requirepass ${REDIS_PASSWORD} --maxmemory 2gb --maxmemory-policy allkeys-lru volumes: - redis_data:/data ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 5s retries: 5 networks: - mosquito-network app: image: your-registry.com/mosquito-api:latest container_name: mosquito-app restart: unless-stopped depends_on: postgres: condition: service_healthy redis: condition: service_healthy environment: SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/mosquito_prod SPRING_DATASOURCE_USERNAME: mosquito_user SPRING_DATASOURCE_PASSWORD: ${POSTGRES_PASSWORD} SPRING_REDIS_HOST: redis SPRING_REDIS_PORT: 6379 SPRING_REDIS_PASSWORD: ${REDIS_PASSWORD} SPRING_PROFILES_ACTIVE: prod JAVA_OPTS: "-Xms512m -Xmx2g -XX:+UseG1GC" ports: - "8080:8080" volumes: - ./logs:/app/logs - ./config:/app/config healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s networks: - mosquito-network logging: driver: "json-file" options: max-size: "10m" max-file: "3" nginx: image: nginx:alpine container_name: mosquito-nginx restart: unless-stopped depends_on: - app ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./ssl:/etc/nginx/ssl:ro - nginx_cache:/var/cache/nginx networks: - mosquito-network volumes: postgres_data: driver: local redis_data: driver: local nginx_cache: driver: local networks: mosquito-network: driver: bridge ``` #### 2.2 创建环境变量文件 ```bash # .env POSTGRES_PASSWORD=your_secure_postgres_password_here REDIS_PASSWORD=your_secure_redis_password_here ``` #### 2.3 创建Nginx配置 ```nginx # nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; upstream mosquito_backend { server app:8080; } server { listen 80; server_name api.yourdomain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name api.yourdomain.com; ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem; location / { proxy_pass http://mosquito_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; } } } ``` #### 2.4 启动服务 ```bash # 启动所有服务 docker-compose up -d # 查看服务状态 docker-compose ps # 查看日志 docker-compose logs -f app # 停止服务 docker-compose down # 重启服务 docker-compose restart app ``` --- ## ☸️ 部署方式三:Kubernetes部署(推荐用于企业级项目) ### 1. Kubernetes资源配置 #### 1.1 创建ConfigMap ```yaml # configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: mosquito-config namespace: mosquito data: application-prod.properties: | spring.profiles.active=prod server.port=8080 logging.level.root=INFO logging.level.com.mosquito.project=DEBUG app.rate-limit.per-minute=100 app.security.api-key-iterations=185000 spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 ``` #### 1.2 创建Secret ```yaml # secret.yaml apiVersion: v1 kind: Secret metadata: name: mosquito-secret namespace: mosquito type: Opaque stringData: POSTGRES_PASSWORD: your_secure_postgres_password_here REDIS_PASSWORD: your_secure_redis_password_here API_ENCRYPTION_KEY: your_32_character_encryption_key_here ``` #### 1.3 创建Deployment ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: mosquito-app namespace: mosquito labels: app: mosquito spec: replicas: 3 selector: matchLabels: app: mosquito template: metadata: labels: app: mosquito version: v2.0.0 spec: containers: - name: mosquito image: your-registry.com/mosquito-api:v2.0.0 ports: - containerPort: 8080 env: - name: SPRING_DATASOURCE_URL value: "jdbc:postgresql://mosquito-postgres:5432/mosquito_prod" - name: SPRING_DATASOURCE_USERNAME value: "mosquito_user" - name: SPRING_DATASOURCE_PASSWORD valueFrom: secretKeyRef: name: mosquito-secret key: POSTGRES_PASSWORD - name: SPRING_REDIS_HOST value: "mosquito-redis" - name: SPRING_REDIS_PORT value: "6379" - name: SPRING_REDIS_PASSWORD valueFrom: secretKeyRef: name: mosquito-secret key: REDIS_PASSWORD - name: JAVA_OPTS value: "-Xms512m -Xmx2g -XX:+UseG1GC" resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "2Gi" cpu: "2000m" livenessProbe: httpGet: path: /actuator/health port: 8080 initialDelaySeconds: 60 periodSeconds: 30 timeoutSeconds: 5 failureThreshold: 3 readinessProbe: httpGet: path: /actuator/health/readiness port: 8080 initialDelaySeconds: 30 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 volumeMounts: - name: config mountPath: /app/config readOnly: true volumes: - name: config configMap: name: mosquito-config ``` #### 1.4 创建Service ```yaml # service.yaml apiVersion: v1 kind: Service metadata: name: mosquito-service namespace: mosquito labels: app: mosquito spec: type: ClusterIP ports: - port: 80 targetPort: 8080 protocol: TCP name: http selector: app: mosquito ``` #### 1.5 创建Ingress ```yaml # ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: mosquito-ingress namespace: mosquito annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/ssl-redirect: "true" nginx.ingress.kubernetes.io/proxy-body-size: "10m" spec: tls: - hosts: - api.yourdomain.com secretName: mosquito-tls rules: - host: api.yourdomain.com http: paths: - path: / pathType: Prefix backend: service: name: mosquito-service port: number: 80 ``` #### 1.6 创建HorizontalPodAutoscaler ```yaml # hpa.yaml apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: mosquito-hpa namespace: mosquito spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: mosquito-app minReplicas: 3 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 - type: Resource resource: name: memory target: type: Utilization averageUtilization: 80 ``` #### 1.7 部署到Kubernetes ```bash # 创建命名空间 kubectl create namespace mosquito # 部署所有资源 kubectl apply -f k8s/configmap.yaml kubectl apply -f k8s/secret.yaml kubectl apply -f k8s/deployment.yaml kubectl apply -f k8s/service.yaml kubectl apply -f k8s/ingress.yaml kubectl apply -f k8s/hpa.yaml # 查看部署状态 kubectl get pods -n mosquito kubectl get services -n mosquito kubectl get ingress -n mosquito kubectl get hpa -n mosquito # 查看日志 kubectl logs -f deployment/mosquito-app -n mosquito # 扩展副本数 kubectl scale deployment/mosquito-app --replicas=5 -n mosquito ``` --- ## 📊 监控配置 ### 1. Prometheus配置 ```yaml # prometheus.yml global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: 'mosquito' metrics_path: '/actuator/prometheus' static_configs: - targets: ['mosquito-app:8080'] tls_config: insecure_skip_verify: true ``` ### 2. Grafana仪表板 #### 2.1 JVM监控 ```json { "dashboard": { "title": "Mosquito JVM Metrics", "panels": [ { "title": "Heap Memory Usage", "targets": [ { "expr": "jvm_memory_used_bytes{area='heap', application='mosquito'}" } ] }, { "title": "GC Time", "targets": [ { "expr": "rate(jvm_gc_pause_seconds_sum[5m]) * 1000" } ] } ] } } ``` ### 3. 日志配置 #### 3.1 应用日志配置 ```properties # logback-spring.xml /app/logs/mosquito.log /app/logs/mosquito.%d{yyyy-MM-dd}.log 30 10GB %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n /app/logs/mosquito.json /app/logs/mosquito.%d{yyyy-MM-dd}.json 30 ``` --- ## 🔐 安全配置 ### 1. 防火墙配置 ```bash # UFW防火墙规则 sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow ssh sudo ufw allow http sudo ufw allow https sudo ufw allow from 127.0.0.1 to any port 5432 # PostgreSQL sudo ufw allow from 127.0.0.1 to any port 6379 # Redis sudo ufw enable ``` ### 2. SELinux/AppArmor配置 ```bash # SELinux状态检查 sestatus # 允许应用访问网络 sudo semanage permissive -a mosquito_t ``` --- ## 🔄 部署检查清单 ### 部署前检查 - [x] 环境要求已满足 - [x] 数据库已创建并配置 - [x] Redis已安装并配置 - [x] SSL证书已获取 - [x] 防火墙规则已配置 - [x] 备份策略已制定 ### 部署后验证 - [x] 应用服务正常启动 - [x] 健康检查端点可访问 - [x] 数据库迁移完成 - [x] API接口响应正常 - [x] 日志正常记录 - [x] 监控数据正常采集 - [x] 告警规则已配置 ### 性能验证 - [x] 响应时间 < 200ms - [x] 并发用户数达到目标 - [x] 内存使用 < 2GB - [x] CPU使用率 < 70% - [x] 错误率 < 0.1% --- ## 🆘 故障排除 ### 常见问题 #### 1. 应用无法启动 ```bash # 查看服务状态 sudo systemctl status mosquito # 查看应用日志 sudo tail -f /var/log/mosquito/application.log # 检查端口占用 sudo netstat -tlnp | grep 8080 ``` #### 2. 数据库连接失败 ```bash # 测试数据库连接 sudo -u postgres psql -h localhost -p 5432 -U mosquito_user -d mosquito_prod # 检查PostgreSQL状态 sudo systemctl status postgresql # 查看PostgreSQL日志 sudo tail -f /var/log/postgresql/postgresql-14-main.log ``` #### 3. Redis连接失败 ```bash # 测试Redis连接 redis-cli -h localhost -p 6379 -a your_redis_password ping # 检查Redis状态 sudo systemctl status redis # 查看Redis日志 sudo tail -f /var/log/redis/redis.log ``` --- *部署指南版本: v2.0.0* *最后更新: 2026-01-22*