# 使用现有服务的部署指南 本指南适用于已有 PostgreSQL 和 Redis 服务的情况。 ## 📋 前提条件 确保你的服务器上已经安装并运行: - **PostgreSQL** (推荐版本 14+) - **Redis** (推荐版本 6+) ## ⚙️ 配置步骤 ### 1. 环境变量配置 复制环境变量模板: ```bash cp .env.example .env ``` 编辑 `.env` 文件,配置你的现有服务: ```bash # 数据库配置 DB_HOST=localhost # 或你的 PostgreSQL 服务器地址 DB_PORT=5432 # PostgreSQL 端口 DB_NAME=photography # 数据库名称 DB_USER=postgres # 数据库用户 DB_PASSWORD=your_actual_password # 数据库密码 # Redis 配置 REDIS_HOST=localhost # 或你的 Redis 服务器地址 REDIS_PORT=6379 # Redis 端口 REDIS_PASSWORD=your_redis_password # Redis 密码 (如果有) # JWT 配置 JWT_SECRET=your_jwt_secret_at_least_32_characters_long JWT_EXPIRES_IN=24h ``` ### 2. 数据库准备 连接到你的 PostgreSQL,创建数据库: ```sql -- 创建数据库 CREATE DATABASE photography; -- 创建用户 (如果需要) CREATE USER photography_user WITH ENCRYPTED PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE photography TO photography_user; -- 使用数据库 \c photography; -- 创建必要的扩展 CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS "pg_trgm"; ``` ### 3. 后端服务部署 #### 方式一:Docker 部署 (推荐) ```bash # 构建并启动后端服务 docker-compose up -d backend # 查看日志 docker-compose logs -f backend # 检查健康状态 curl http://localhost:8080/health ``` #### 方式二:直接运行 ```bash # 进入后端目录 cd backend # 安装依赖 go mod download # 运行数据库迁移 go run cmd/server/main.go migrate # 启动服务 go run cmd/server/main.go ``` ### 4. 数据库迁移 如果你的后端支持自动迁移,服务启动时会自动创建表结构。 如果需要手动迁移: ```bash # 使用 Docker docker-compose exec backend ./main migrate # 或者直接运行 cd backend && go run cmd/server/main.go migrate ``` ### 5. 验证部署 ```bash # 检查后端健康状态 curl http://localhost:8080/health # 检查数据库连接 curl http://localhost:8080/api/v1/health # 检查 Redis 连接 (如果有相关接口) curl http://localhost:8080/api/v1/cache/health ``` ## 🔧 常见问题 ### 数据库连接失败 1. **检查数据库是否运行**: ```bash sudo systemctl status postgresql ``` 2. **检查连接权限**: ```bash psql -h localhost -U postgres -d photography ``` 3. **检查防火墙**: ```bash sudo ufw status ``` ### Redis 连接失败 1. **检查 Redis 状态**: ```bash sudo systemctl status redis ``` 2. **测试 Redis 连接**: ```bash redis-cli ping ``` ### 容器网络问题 如果容器无法访问宿主机服务,尝试: 1. **使用 host 网络模式** (已配置) 2. **检查服务绑定地址**: - PostgreSQL: 确保监听 `0.0.0.0:5432` 或 `localhost:5432` - Redis: 确保监听 `0.0.0.0:6379` 或 `localhost:6379` ## 📊 监控和维护 ### 日志查看 ```bash # 后端日志 docker-compose logs -f backend # 系统日志 journalctl -u your-service-name -f ``` ### 性能监控 ```bash # 运行监控脚本 ./scripts/monitor.sh # 手动检查资源使用 docker stats photography_backend ``` ### 备份 ```bash # 手动备份数据库 ./scripts/backup.sh # 或者使用 Docker 备份服务 docker-compose --profile backup up backup ``` ## 🚀 自动化部署 如果你使用 CI/CD,确保在部署环境中设置正确的环境变量: ```yaml # .github/workflows 或 .gitea/workflows env: DB_HOST: your-db-host DB_PASSWORD: ${{ secrets.DB_PASSWORD }} REDIS_HOST: your-redis-host REDIS_PASSWORD: ${{ secrets.REDIS_PASSWORD }} ``` ## 🔒 安全建议 1. **使用强密码** 2. **限制数据库访问**:只允许必要的 IP 连接 3. **启用 SSL/TLS**:用于数据库和 Redis 连接 4. **定期更新**:保持服务和依赖的最新版本 5. **监控日志**:定期检查异常访问 --- 这种配置更加轻量和实用,避免了重复安装已有服务的资源浪费。