Files
tyapi-server/docs/开始指南/部署指南.md

477 lines
9.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🚀 部署指南
## Docker 部署
### 1. 构建镜像
```bash
# 构建生产镜像
make docker-build
# 或使用Docker命令
docker build -t tyapi-server:latest .
```
### 2. 运行容器
```bash
# 单容器运行
docker run -d \
--name tyapi-server \
-p 8080:8080 \
-e APP_ENV=production \
-e DB_HOST=your-db-host \
-e DB_PASSWORD=your-password \
tyapi-server:latest
# 使用Docker Compose
docker-compose up -d
```
### 3. 多环境部署
#### 开发环境
```bash
# 启动完整开发环境
docker-compose -f docker-compose.dev.yml up -d
# 仅启动依赖服务
docker-compose -f docker-compose.dev.yml up -d postgres redis
```
#### 测试环境
```bash
# 使用测试配置
docker-compose -f docker-compose.test.yml up -d
```
#### 生产环境
```bash
# 使用生产配置
docker-compose -f docker-compose.prod.yml up -d
```
## Kubernetes 部署
### 1. 配置清单文件
创建 `k8s/deployment.yaml`
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: tyapi-server
spec:
replicas: 3
selector:
matchLabels:
app: tyapi-server
template:
metadata:
labels:
app: tyapi-server
spec:
containers:
- name: tyapi-server
image: tyapi-server:latest
ports:
- containerPort: 8080
env:
- name: APP_ENV
value: "production"
- name: DB_HOST
valueFrom:
secretKeyRef:
name: tyapi-secrets
key: db-host
```
### 2. 服务配置
创建 `k8s/service.yaml`
```yaml
apiVersion: v1
kind: Service
metadata:
name: tyapi-server-service
spec:
selector:
app: tyapi-server
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
```
### 3. 配置管理
创建 `k8s/configmap.yaml`
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: tyapi-config
data:
config.yaml: |
server:
port: 8080
mode: release
database:
host: postgres-service
port: 5432
```
### 4. 密钥管理
```bash
# 创建密钥
kubectl create secret generic tyapi-secrets \
--from-literal=db-password=your-db-password \
--from-literal=jwt-secret=your-jwt-secret
```
### 5. 部署到集群
```bash
# 应用所有配置
kubectl apply -f k8s/
# 查看部署状态
kubectl get pods -l app=tyapi-server
# 查看服务状态
kubectl get services
# 查看服务日志
kubectl logs -f deployment/tyapi-server
```
## 云平台部署
### AWS ECS
#### 1. 推送镜像到 ECR
```bash
# 登录 ECR
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin <account>.dkr.ecr.us-west-2.amazonaws.com
# 标记镜像
docker tag tyapi-server:latest <account>.dkr.ecr.us-west-2.amazonaws.com/tyapi-server:latest
# 推送镜像
docker push <account>.dkr.ecr.us-west-2.amazonaws.com/tyapi-server:latest
```
#### 2. 创建任务定义
```json
{
"family": "tyapi-server",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "tyapi-server",
"image": "<account>.dkr.ecr.us-west-2.amazonaws.com/tyapi-server:latest",
"portMappings": [
{
"containerPort": 8080,
"protocol": "tcp"
}
],
"environment": [
{
"name": "APP_ENV",
"value": "production"
}
],
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:us-west-2:account:secret:db-password"
}
]
}
]
}
```
#### 3. 部署服务
```bash
# 更新ECS服务
aws ecs update-service \
--cluster tyapi-cluster \
--service tyapi-service \
--force-new-deployment
```
### Google Cloud Run
```bash
# 推送到 GCR
docker tag tyapi-server:latest gcr.io/your-project/tyapi-server:latest
docker push gcr.io/your-project/tyapi-server:latest
# 部署到 Cloud Run
gcloud run deploy tyapi-server \
--image gcr.io/your-project/tyapi-server:latest \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars APP_ENV=production \
--set-secrets DB_PASSWORD=db-password:latest
```
### Azure Container Instances
```bash
# 推送到 ACR
az acr login --name your-registry
docker tag tyapi-server:latest your-registry.azurecr.io/tyapi-server:latest
docker push your-registry.azurecr.io/tyapi-server:latest
# 部署容器实例
az container create \
--resource-group tyapi-rg \
--name tyapi-server \
--image your-registry.azurecr.io/tyapi-server:latest \
--dns-name-label tyapi-server \
--ports 8080 \
--environment-variables APP_ENV=production \
--secure-environment-variables DB_PASSWORD=your-password
```
## 负载均衡配置
### Nginx 配置
创建 `/etc/nginx/sites-available/tyapi-server`
```nginx
upstream tyapi_backend {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}
server {
listen 80;
server_name api.yourdomain.com;
location / {
proxy_pass http://tyapi_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 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# 健康检查
location /health {
proxy_pass http://tyapi_backend/api/v1/health;
access_log off;
}
}
```
### HAProxy 配置
```haproxy
global
daemon
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend tyapi_frontend
bind *:80
default_backend tyapi_backend
backend tyapi_backend
balance roundrobin
option httpchk GET /api/v1/health
server app1 127.0.0.1:8080 check
server app2 127.0.0.1:8081 check
server app3 127.0.0.1:8082 check
```
## 数据库部署
### PostgreSQL 高可用
#### 主从配置
主库配置 `/etc/postgresql/13/main/postgresql.conf`
```conf
# 复制设置
wal_level = replica
max_wal_senders = 3
wal_keep_segments = 64
```
从库配置:
```bash
# 创建从库
pg_basebackup -h master-host -D /var/lib/postgresql/13/main -U replicator -P -W
# 配置恢复
echo "standby_mode = 'on'" >> /var/lib/postgresql/13/main/recovery.conf
echo "primary_conninfo = 'host=master-host port=5432 user=replicator'" >> /var/lib/postgresql/13/main/recovery.conf
```
#### 连接池配置
使用 PgBouncer
```ini
[databases]
tyapi_prod = host=127.0.0.1 port=5432 dbname=tyapi_prod
[pgbouncer]
listen_port = 6432
listen_addr = 127.0.0.1
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25
```
### Redis 集群
```bash
# 启动 Redis 集群
redis-server redis-7000.conf
redis-server redis-7001.conf
redis-server redis-7002.conf
# 创建集群
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 0
```
## 监控部署
### Prometheus 配置
```yaml
global:
scrape_interval: 15s
scrape_configs:
- job_name: "tyapi-server"
static_configs:
- targets: ["localhost:8080"]
metrics_path: /metrics
scrape_interval: 5s
- job_name: "postgres"
static_configs:
- targets: ["localhost:9187"]
- job_name: "redis"
static_configs:
- targets: ["localhost:9121"]
```
### Grafana 仪表板
导入预配置的仪表板或创建自定义面板监控:
- 应用性能指标
- 数据库性能
- 系统资源使用
- 错误率和响应时间
## SSL/TLS 配置
### Let's Encrypt 证书
```bash
# 安装 Certbot
sudo apt-get install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d api.yourdomain.com
# 自动续期
sudo crontab -e
0 12 * * * /usr/bin/certbot renew --quiet
```
### 自签名证书(开发环境)
```bash
# 生成私钥
openssl genrsa -out server.key 2048
# 生成证书
openssl req -new -x509 -key server.key -out server.crt -days 365
```
## 部署检查清单
### 部署前检查
- [ ] 环境变量配置完整
- [ ] 数据库连接正常
- [ ] Redis 连接正常
- [ ] SSL 证书有效
- [ ] 防火墙规则配置
- [ ] 监控告警设置
### 部署后验证
- [ ] 健康检查通过
- [ ] API 响应正常
- [ ] 日志输出正常
- [ ] 监控指标采集
- [ ] 负载均衡工作
- [ ] 备份机制测试
## 回滚策略
### 蓝绿部署
```bash
# 部署新版本到绿环境
kubectl apply -f k8s/green/
# 切换流量到绿环境
kubectl patch service tyapi-service -p '{"spec":{"selector":{"version":"green"}}}'
# 验证后删除蓝环境
kubectl delete -f k8s/blue/
```
### 金丝雀发布
```bash
# 部署金丝雀版本10%流量)
kubectl apply -f k8s/canary/
# 逐步增加流量
kubectl patch virtualservice tyapi-vs -p '{"spec":{"http":[{"match":[{"headers":{"canary":{"exact":"true"}}}],"route":[{"destination":{"host":"tyapi-canary"}}]},{"route":[{"destination":{"host":"tyapi-stable"},"weight":90},{"destination":{"host":"tyapi-canary"},"weight":10}]}]}}'
```