Files
2025-12-01 19:16:38 +08:00

3.2 KiB

端口规划说明

为了方便维护和避免端口冲突,三种部署方式使用不同的端口段。

端口规划表

部署方式 后端 API 前端应用 PostgreSQL Redis Nginx 配置文件
本地开发 (start_app.sh) 5115 6115 - - - backend/.env
Docker Compose 15115 16115 15432 16379 18080 .env.prod
Kubernetes 30115 31115 30432 30379 - .env.k8s

访问地址

本地开发模式

./start_app.sh

# 访问地址
后端 API: http://localhost:5115
前端应用: http://localhost:6115
API 文档: http://localhost:5115/docs
健康检查: http://localhost:5115/api/v1/health/

Docker Compose 模式

docker-compose -f docker-compose.prod.yml --env-file .env.prod up -d

# 访问地址
后端 API: http://localhost:15115
前端应用: http://localhost:16115
API 文档: http://localhost:15115/docs
Nginx 代理: http://localhost:18080
PostgreSQL: localhost:15432
Redis: localhost:16379

Kubernetes 模式

export $(grep -v '^#' .env.k8s | xargs)
./deploy_k8s.sh

# 访问地址(NodePort 方式)
后端 API: http://localhost:30115
前端应用: http://localhost:31115
PostgreSQL: localhost:30432
Redis: localhost:30379

# 访问地址(Ingress 方式)
前端应用: http://fastapi-template.local
后端 API: http://fastapi-template.local/api

端口段说明

  • 0xxxx: 预留给系统和其他服务
  • 5xxx / 6xxx: 本地开发端口段
    • 5115: 后端 API
    • 6115: 前端应用
  • 1xxxx: Docker Compose 端口段
    • 15115: 后端 API
    • 16115: 前端应用
    • 15432: PostgreSQL
    • 16379: Redis
    • 18080: Nginx HTTP
    • 18443: Nginx HTTPS
  • 3xxxx: Kubernetes NodePort 端口段 (30000-32767)
    • 30115: 后端 API
    • 31115: 前端应用
    • 30432: PostgreSQL
    • 30379: Redis

配置文件管理

本地开发

  • 配置文件: backend/.env
  • 复制模板: cp backend/.env.example backend/.env
  • 修改端口: PORT=5115

Docker Compose

  • 配置文件: .env.prod
  • 已配置端口: 1xxxx 段
  • 启动命令: docker-compose -f docker-compose.prod.yml --env-file .env.prod up -d

Kubernetes

  • 配置文件: .env.k8s
  • 已配置端口: 2xxxx 段
  • 部署前导入: export $(grep -v '^#' .env.k8s | xargs)
  • 部署命令: ./deploy_k8s.sh

端口冲突解决

如果遇到端口被占用:

检查端口占用

# macOS
lsof -i:端口号

# Linux
netstat -tulpn | grep 端口号

停止占用进程

# 找到 PID 后
kill -9 PID号

# 或直接停止服务
./start_app.sh  # Ctrl+C 停止
docker-compose -f docker-compose.prod.yml down  # 停止 Docker
kubectl delete namespace fastapi-dev  # 停止 K8s

修改端口

编辑对应的 .env 文件,修改端口号后重新启动即可。

注意事项

  1. 生产环境安全:修改 .env.prod 和 .env.k8s 中的密码和密钥
  2. 防火墙规则:确保对应端口在防火墙中开放
  3. 并行运行:三种模式使用不同端口,可以同时运行而不冲突
  4. 健康检查:所有模式都提供 /api/v1/health/ 端点用于健康检查