修复迁移时,数据库未指定的情况下数据库脚本混乱的问题

This commit is contained in:
2025-12-06 22:03:57 +08:00
parent 6547e7bca8
commit b66f345281
7 changed files with 194 additions and 77 deletions

View File

@@ -105,14 +105,10 @@ go build -o bin/migrate cmd/migrate/main.go
}
```
#### 方式2环境变量推荐生产环境
#### 方式2环境变量指定配置文件路径(推荐生产环境)
```bash
# 使用 DATABASE_URL最简单
export DATABASE_URL="mysql://root:password@localhost:3306/mydb"
./bin/migrate up
# 覆盖配置路径
# 使用环境变量指定配置文件路径
export CONFIG_FILE="/etc/app/config.json"
export MIGRATIONS_DIR="/opt/app/migrations"
./bin/migrate up
@@ -122,8 +118,7 @@ export MIGRATIONS_DIR="/opt/app/migrations"
1. 命令行参数 `-config``-dir`(最高)
2. 环境变量 `CONFIG_FILE``MIGRATIONS_DIR`
3. 环境变量 `DATABASE_URL`
4. 默认值 `config.json``migrations`
3. 默认值 `config.json``migrations`
---
@@ -185,20 +180,20 @@ services:
docker-compose exec app ./migrate up
```
### 方式3使用环境变量
### 方式3使用环境变量指定配置文件路径
无需配置文件(适用于简单场景)
适用于多环境部署,通过环境变量指定不同环境的配置文件
```yaml
services:
app:
build: .
environment:
DATABASE_URL: mysql://root:password@db:3306/mydb
CONFIG_FILE: /app/config.prod.json
MIGRATIONS_DIR: /app/migrations
volumes:
- ./config.prod.json:/app/config.prod.json:ro
command: sh -c "./migrate up && ./server"
# 注意DATABASE_URL 的值应该指向你的数据库服务
# 例如mysql://user:pass@your-db-host:3306/dbname
```
### Dockerfile
@@ -336,10 +331,12 @@ jobs:
go build -o bin/migrate cmd/migrate/main.go
go build -o bin/server cmd/server/main.go
- name: Create Config File
run: |
echo '${{ secrets.CONFIG_JSON }}' > config.json
- name: Run Migrations
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
run: ./bin/migrate up
run: ./bin/migrate up -config config.json
- name: Deploy
run: ./bin/server
@@ -500,11 +497,11 @@ go build -o bin/migrate cmd/migrate/main.go
### 3. 生产环境
- 编译后部署,先执行迁移再启动应用
- 使用环境变量管理敏感信息
- 使用配置文件管理敏感信息
```bash
go build -o bin/migrate cmd/migrate/main.go
DATABASE_URL="mysql://..." ./bin/migrate up
./bin/migrate up -config config.json
./bin/server
```