Skip to content

Commit 0f0c271

Browse files
committed
fix(deploy): 数据迁 named volume 并去掉写死 container_name,杜绝 bind mount 损坏库
macOS Docker(colima vmType vz + mountType virtiofs)把宿主目录 bind mount 进 容器后,SQLite 的 flock/mmap/fsync/原子 rename 跨 VM 边界不成立,WAL 被写坏—— 实测反复 database disk image is malformed,最严重时主库文件头被整段清零。 - docker-compose.yml:DATA_DIR 改用 named volume coding2api-data(VM 本地 ext4), 不再 bind mount ./data;并去掉写死的 container_name,让容器名带项目前缀, 避免 worktree/旧 checkout 用同名服务顶掉生产容器。 - doctor 新增 check_data_dir_filesystem:DATA_DIR 落在 virtiofs/fuse/9p 直接 FAIL 拦启动门禁(NFS/CIFS 只 WARN),把这条铁律从文档约定变成自动拦截。 - scripts/migrate-data-to-volume.sh:历史 bind mount 数据迁到 named volume。 - CI docker logs 改按服务名(未写死容器名);README 补部署铁律。
1 parent 4019bc6 commit 0f0c271

8 files changed

Lines changed: 266 additions & 6 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ jobs:
194194
if curl -fsS http://127.0.0.1:8000/health >/dev/null; then break; fi
195195
sleep 2
196196
done
197-
# 失败排查线索:容器日志(含启动 Traceback)
198-
docker logs coding2api --tail 80
197+
# 失败排查线索:容器日志(含启动 Traceback)。按服务名取(未写死
198+
# container_name,容器名带项目前缀),`docker compose logs` 稳定可用。
199+
docker compose logs --tail 80 coding2api
199200
curl -fsS http://127.0.0.1:8000/health
200201
APP_SECRET=ci-placeholder-secret docker compose down

‎README.en.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ docker compose up -d --build
7272
docker compose exec coding2api python scripts/create_user.py admin --role admin
7373
```
7474

75+
> **macOS / Docker users**: `docker-compose.yml` puts data in the **named volume `coding2api-data`** (the VM's local ext4) by default. **Do not switch it back to a `./data:/app/data` bind mount** — SQLite on macOS's virtiofs shared mount corrupts the database (repeated `database disk image is malformed`; worst case the main DB header is zeroed out). See "Deployment notes".
76+
7577
Pull the image: `docker compose pull` (or `docker pull ghcr.io/robbsluo/coding2api:v0.15.1`). Pushing a `v*` tag to main runs `.github/workflows/publish.yml` → publishes `<tag>` + `:latest`. For https on a VPS with a public IP see "[Public deployment](#public-deployment-docker--caddy-automatic-https)".
7678

7779
## Users and roles
@@ -549,7 +551,7 @@ The authoritative list is `src/config.py`; every item is passed through `docker-
549551
| `ADMIN_USERNAMES` | empty | Bootstrap only (while no active admin exists): promoted to `admin` on first start |
550552
| `USERS_FILE` | `secrets/users.txt` | Bootstrap only: legacy user file, imported once |
551553
| `PUBLIC_BASE_URL` | `http://127.0.0.1:8000` | Browser-reachable base; TRAE login callback; HSTS over https. Does not control session cookie `Secure`. Loopback / `0.0.0.0` → callback base falls back to the request origin |
552-
| `DATA_DIR` | `./data` | SQLite and runtime data directory |
554+
| `DATA_DIR` | `./data` | SQLite and runtime data directory. **Bare-metal** uses `./data`; **Docker deploys use the named volume `coding2api-data`** (mounted at `/app/data` in the container) — do not bind-mount the host directory; see "Deployment notes" (SQLite on virtiofs corrupts the database) |
553555
| `DEFAULT_MODEL` | `deepseek-v4.1-flash` | Used when the model is empty / `auto` |
554556
| `QUOTA_PROBE_MINUTES` | `60` | Quota probe period (min 1) |
555557
| `REFRESH_INTERVAL_MINUTES` | `30` | Token pre-refresh period (min 5) |
@@ -706,6 +708,8 @@ The table above marks only common hot-reloadable items; **89 items** in total (`
706708

707709
- **Platform: Linux / macOS only.** The single-instance lock (`src/instance_lock.py`) relies on `flock`; on Windows it exits with a readable Chinese message — use WSL2 / Docker. The `data/` `0700` trust boundary is enforced on Windows via `icacls` in `src/security/private_files.py`.
708710
- **One writer per `DATA_DIR`**: never run a host process (`python -m src.main` / launchd) and a Docker container against the same `./data` at the same time. On macOS virtiofs, `flock` does not cross the host/container boundary: the container acquires the lock even while the host holds it, so the single-instance guard is void and two writers corrupt SQLite (observed as `database disk image is malformed`). When switching deployment modes, stop one side first (`launchctl bootout` or `docker compose stop`) and confirm the other is not running. Do not delete/modify `-wal`/`-shm` from the host while the container is running — that yields `disk I/O error`; stop the container for maintenance.
711+
- **Docker deploys: `DATA_DIR` must be a named volume — never bind-mount the host directory** (`./data:/app/data`). `docker-compose.yml` already defaults to the named volume `coding2api-data`; **do not switch it back to `./data`**. Why: on macOS, Docker (Docker Desktop / colima, `vmType: vz` + `mountType: virtiofs`) exposes a bind-mounted host directory to the container as a **virtiofs/FUSE shared filesystem** — the `flock`/POSIX-lock, `mmap`, `fsync`, and atomic-rename semantics SQLite relies on do not hold across the VM boundary, so WAL writes get corrupted. Observed symptoms: repeated `database disk image is malformed`, `integrity_check` reporting missing index rows, and in the worst case **the main database header zeroed out entirely** (`0000...`, the file will not open) — recoverable only from a backup. A named volume lives on the VM's local ext4, where the locking semantics are sound. Verify with `docker exec coding2api stat -f -c '%T' /app/data`: it should print a local fs such as `ext2/ext3`; **`fuse` / `virtiofs` means it is wrong**. To migrate historical data see `scripts/migrate-data-to-volume.sh`.
712+
- **Don't let multiple checkouts / worktrees fight over the same container name**: `container_name: coding2api` is globally unique. If you keep several git worktrees / older checkouts that each ship a compose file, running `docker compose up` from a **non-primary** directory uses *that* copy (which may still have the old bind-mount config) and **replaces the running production container**. Always deploy from the primary checkout; don't `up` the same-named service from an old worktree until it has been upgraded to the named-volume compose.
709713
- **Mount ownership**: the container runs as uid 1001 (`appuser`) → `mkdir -p data secrets && sudo chown -R 1001:1001 data secrets`.
710714
- **Time zone**: the image defaults to `TZ=Asia/Shanghai`; `TZ` from `.env` passes through. Check-in and quota periods key off "9am today", so it must match the host.
711715
- **TRAE callback**: `PUBLIC_BASE_URL` is local-only by default; remote / container deployments must set a browser-reachable address. Forgetting it fails loudly: a loopback / `0.0.0.0` base falls back to the request origin and the *Add credential* dialog shows the effective address. If the callback is unreachable from the browser (common NAS / remote "network error"), paste the whole link from the address bar into the TRAE box — login works without the browser reaching this service.

‎README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ docker compose up -d --build
7272
docker compose exec coding2api python scripts/create_user.py admin --role admin
7373
```
7474

75+
> **macOS / Docker 用户注意**:`docker-compose.yml` 默认把数据放进 **named volume `coding2api-data`**(VM 本地 ext4)。**别改回 `./data:/app/data` bind mount**——macOS 的 virtiofs 共享挂载上放 SQLite 会损坏库(反复 `database disk image is malformed`,最严重时主库头被清零)。详见「[部署注意](#部署注意)」。
76+
7577
拉镜像:`docker compose pull`(或 `docker pull ghcr.io/robbsluo/coding2api:v0.15.1`)。tag `v*` 推 main → `.github/workflows/publish.yml` → 发 `<tag>` + `:latest`。有公网 IP 的 VPS 要 https → 见「[公网部署](#公网部署docker--caddy-自动-https)」。
7678

7779
## 用户与角色
@@ -555,7 +557,7 @@ python3 scripts/restore_db.py data/backups/coding2api-20261014-030000.sqlite3 --
555557
| `ADMIN_USERNAMES` | 空 | 仅引导期(库里还没有活跃 admin):首次启动提权 `admin`。**代码默认空,但 `.env.example` 与 `docker-compose.yml` 给 `admin`**——bootstrap 要求至少一个活跃 admin,模板留空会让首次启动直接失败 |
556558
| `USERS_FILE` | `secrets/users.txt` | 仅引导期:老式用户文件,启动导入一次 |
557559
| `PUBLIC_BASE_URL` | `http://127.0.0.1:8000` | 浏览器可达地址;TRAE 登录回调用;https 下发 HSTS。不决定会话 Cookie 的 `Secure`。配回环 / `0.0.0.0` → 回调基址取当前请求 origin |
558-
| `DATA_DIR` | `./data` | SQLite 与运行数据目录 |
560+
| `DATA_DIR` | `./data` | SQLite 与运行数据目录。**裸机跑**才是 `./data`;**Docker 部署用 named volume `coding2api-data`**(容器内仍挂 `/app/data`),禁止 bind mount 宿主目录——见「[部署注意](#部署注意)」,virtiofs 上放 SQLite 会损坏库 |
559561
| `DEFAULT_MODEL` | `deepseek-v4.1-flash` | 模型为空 / `auto` 时默认 |
560562
| `QUOTA_PROBE_MINUTES` | `60` | 额度探测周期(下限 1) |
561563
| `REFRESH_INTERVAL_MINUTES` | `30` | token 预刷新轮询周期(下限 5) |
@@ -713,6 +715,8 @@ python3 scripts/restore_db.py data/backups/coding2api-20261014-030000.sqlite3 --
713715

714716
- **平台范围:仅 Linux / macOS**。单实例锁(`src/instance_lock.py`)依赖 `flock`,Windows 直接跑会以可读中文退出;请用 WSL2 / Docker。`data/` 的 `0700` 信任边界在 Windows 下由 `src/security/private_files.py` 改用 `icacls` 收紧 ACL。
715717
- **同一 `DATA_DIR` 只能一个写者**:宿主进程(`python -m src.main` / launchd)与 Docker 容器若共用 `./data`,**不要同时运行**。macOS virtiofs 挂载下 `flock` 不跨宿主/容器:宿主已持锁时容器照样拿到锁,单实例保护失效,两个进程双写 SQLite 会损坏库(实测 `database disk image is malformed`)。切换部署形态时先停一侧(`launchctl bootout` 或 `docker compose stop`),确认另一侧未运行再启动。容器运行时也不要在宿主删改 `-wal`/`-shm`,否则容器报 `disk I/O error`;维护前先停容器。
718+
- **Docker 部署:`DATA_DIR` 必须用 named volume,禁止 bind mount 宿主目录**(`./data:/app/data`)。`docker-compose.yml` 默认已是 named volume `coding2api-data`,**别改回 `./data`**。原因:macOS 上 Docker(Docker Desktop / colima,`vmType: vz` + `mountType: virtiofs`)把宿主目录 bind mount 进容器后,容器看到的是 **virtiofs/FUSE 共享文件系统**——SQLite 依赖的 `flock`/POSIX 锁、`mmap`、`fsync`、原子 rename 跨 VM 边界不成立,WAL 写入会被写坏。实测症状:反复 `database disk image is malformed`、`integrity_check` 报索引行缺失,最严重时**主库文件头被整段清零**(`0000...`,库直接打不开),只能从备份抢救。named volume 落在 VM 本地 ext4,锁语义可靠。校验:`docker exec coding2api stat -f -c '%T' /app/data` 应输出 `ext2/ext3` 一类本地 fs,**出现 `fuse` / `virtiofs` 就是错的**。历史数据迁移见 `scripts/migrate-data-to-volume.sh`。
719+
- **多 checkout / worktree 别抢同名容器**:`container_name: coding2api` 是全局唯一名。若你有多个 git worktree / 旧 checkout 各自带 compose,在**非主仓**目录 `docker compose up` 会用那份(可能还是旧 bind mount 配置)**顶掉正在运行的生产容器**。只在主仓目录做部署;旧 worktree 升级到含 named volume 的 compose 前,不要在那里 `up` 同名服务。
716720
- **挂载属主**:容器内 uid 1001(`appuser`)→ `mkdir -p data secrets && sudo chown -R 1001:1001 data secrets`。
717721
- **时区**:镜像默认 `TZ=Asia/Shanghai`;签到 / 额度周期按「今天 9 点」判断 → 必须与宿主一致。
718722
- **TRAE 回调地址**:`PUBLIC_BASE_URL` 默认只在本机可用,远程 / 容器部署改成浏览器能开的地址。忘改也不会静默失败:基址落回环 / `0.0.0.0` → 回调改用当前请求 origin;「添加凭证」显示实际地址。浏览器侧打不开回调时(NAS / 远程常见「网络错误」),把地址栏整条链接粘回 TRAE 粘贴框即可完成登录。

‎docker-compose.yml‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@ services:
22
coding2api:
33
build: .
44
image: ghcr.io/robbsluo/coding2api:latest
5-
container_name: coding2api
5+
# 不写死 container_name:让 Compose 用「项目名_服务名」生成(如
6+
# coding2api-coding2api-1)。写死 `coding2api` 会让任何 git worktree /
7+
# 旧 checkout 里的同名服务与本实例抢这个全局唯一名——谁后 `up` 谁把对方
8+
# 顶掉(实测生产容器被 PR worktree 替换,挂错数据目录)。去名后各 checkout
9+
# 用各自项目前缀,可并存。Caddy 反代走 service name(`coding2api:PORT`),
10+
# 不受影响;运维命令改用 `docker compose logs/exec coding2api`(按服务名)。
611
restart: unless-stopped
712
# 让容器能通过 host.docker.internal 访问宿主(Docker Desktop 自带,
813
# Linux / Colima 需显式加这条)。用于 PROVIDER_PROXIES 指向宿主代理,
@@ -340,7 +345,13 @@ services:
340345
stop_grace_period: 95s
341346
volumes:
342347
# 凭证与统计(SQLite)与用户文件分开挂载
343-
- ./data:/app/data
348+
# SQLite 数据走 **named volume**,不能 bind mount 宿主目录:compose 默认把
349+
# ./data 挂进来时,容器看到的是 virtiofs/FUSE 共享文件系统(colima vz),
350+
# SQLite 依赖的 flock/POSIX 锁、mmap、fsync 语义跨 VM 边界不成立——WAL 写入
351+
# 会被写坏(2026-12-01 实测反复 `database disk image is malformed`,主库头被
352+
# 清零)。named volume 落在 VM 本地 ext4,锁语义可靠。迁移历史数据见
353+
# scripts/migrate-data-to-volume.sh。
354+
- coding2api-data:/app/data
344355
- ./secrets:/app/secrets:ro
345356
healthcheck:
346357
# 端口必须与上面的 PORT 同步:健康检查打的是容器内监听端口,写死 8000
@@ -358,3 +369,8 @@ services:
358369
options:
359370
max-size: "10m"
360371
max-file: "5"
372+
373+
# 顶层卷声明:SQLite 数据落在 Docker 管理的 named volume(VM 本地 ext4),
374+
# 而非 bind mount 的宿主 virtiofs 共享目录。原因见 services.coding2api.volumes 注释。
375+
volumes:
376+
coding2api-data:

‎scripts/doctor.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ def collect(settings: Settings, *, port: int | None = None,
8888
doctor.check_generic_channels(settings),
8989
doctor.check_data_dir(settings),
9090
doctor.check_data_permissions(settings),
91+
doctor.check_data_dir_filesystem(settings),
9192
doctor.check_host_config(settings),
9293
doctor.check_trusted_proxies(settings),
9394
doctor.check_database(settings),

‎scripts/migrate-data-to-volume.sh‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env bash
2+
# 把宿主 ./data(bind mount)里的运行数据迁进 Docker named volume。
3+
#
4+
# 为什么需要:SQLite 放在 bind mount 的宿主目录上时,容器经 colima 的 virtiofs
5+
# 共享文件系统访问它,flock/POSIX 锁、mmap、fsync 语义跨 VM 边界不成立,WAL 会
6+
# 被写坏(2026-12-01 实测反复 `database disk image is malformed`,主库头被清零)。
7+
# 改用 named volume(VM 本地 ext4)后锁语义可靠。
8+
#
9+
# 用法:
10+
# docker compose down # 先停掉写者
11+
# scripts/migrate-data-to-volume.sh
12+
# docker compose up -d
13+
#
14+
# 幂等:volume 里已有非空库时跳过覆盖(不会拿宿主旧数据盖掉 volume 新数据)。
15+
set -euo pipefail
16+
17+
cd "$(dirname "$0")/.."
18+
19+
DATA_VOLUME="${DATA_VOLUME:-coding2api-data}"
20+
SRC_DIR="${SRC_DIR:-./data}"
21+
DB_NAME="coding2api.sqlite3"
22+
23+
echo "== 定位 compose 实际挂载的 volume 名"
24+
# compose 会给卷加项目前缀(`<project>_coding2api-data`),脚本自己 `docker volume
25+
# create coding2api-data` 建出来的裸名卷 compose 不认——会另建一个空卷,应用在新卷上
26+
# 重建库、凭证全丢(2026-12-01 实测)。所以必须以 compose 的实际挂载为准,绝不自己
27+
# create。要求先 `docker compose create`(或 up 过一次)让卷存在。
28+
COMPOSE_VOLUME=$(docker compose ps --format json 2>/dev/null | python3 -c '
29+
import json,sys
30+
names=set()
31+
for line in sys.stdin:
32+
line=line.strip()
33+
if not line: continue
34+
try: names.add(json.loads(line).get("Name",""))
35+
except Exception: pass
36+
print(";".join(sorted(names)))
37+
') || COMPOSE_VOLUME=""
38+
if [ -z "$COMPOSE_VOLUME" ]; then
39+
echo "!! 取不到 compose 卷名。请先跑过一次 docker compose up -d(哪怕失败),"
40+
echo " 让 compose 建出 ${PROJECT:-coding2api}_coding2api-data 卷,再重跑本脚本。"
41+
exit 1
42+
fi
43+
DATA_VOLUME="$COMPOSE_VOLUME"
44+
echo "== 目标 volume(compose 实际挂载): $DATA_VOLUME"
45+
docker volume inspect "$DATA_VOLUME" >/dev/null 2>&1 || {
46+
echo "!! volume $DATA_VOLUME 不存在,compose 还没建过它。先 docker compose up -d 一次。"
47+
exit 1
48+
}
49+
50+
# 用一个临时挂载了 volume 的容器做搬运(宿主无需 docker cp 到卷的额外步骤)。
51+
MIGRATOR="coding2api-data-migrator"
52+
docker rm -f "$MIGRATOR" >/dev/null 2>&1 || true
53+
54+
echo "== 检查 volume 里是否已有数据"
55+
EXISTING=$(docker run --rm -v "$DATA_VOLUME:/mnt" alpine \
56+
sh -c "[ -f /mnt/$DB_NAME ] && stat -c%s /mnt/$DB_NAME || echo 0")
57+
if [ "${EXISTING:-0}" -gt 4096 ]; then
58+
echo " volume 里已有 ${EXISTING} 字节的库,跳过覆盖。"
59+
echo " 若确认要覆盖,请先 docker volume rm $DATA_VOLUME 再重跑。"
60+
docker rm -f "$MIGRATOR" >/dev/null 2>&1 || true
61+
exit 0
62+
fi
63+
64+
echo "== 把 $SRC_DIR 拷进 volume(含 WAL/SHM/备份/模型快照)"
65+
# 必须 chown 成应用运行用户(容器内 uid 1001):应用启动会收紧数据文件权限,
66+
# 属主不是自己时 `secure_file` 直接抛 PrivateAccessError 拒启(2026-12-01 实测)。
67+
docker run --name "$MIGRATOR" -v "$DATA_VOLUME:/mnt" -v "$(pwd)/$SRC_DIR:/src:ro" alpine \
68+
sh -c 'cp -a /src/. /mnt/ && rm -f /mnt/'"$DB_NAME"'-wal /mnt/'"$DB_NAME"'-shm && \
69+
chown -R 1001:1001 /mnt && chmod 600 /mnt/'"$DB_NAME"' && \
70+
echo " 拷贝完成(属主已设为 1001,WAL/SHM 已清)" && ls -la /mnt | head'
71+
72+
docker rm -f "$MIGRATOR" >/dev/null
73+
74+
echo "== 校验 volume 内主库完整性"
75+
docker run --rm -v "$DATA_VOLUME:/mnt" alpine sh -c '
76+
if command -v sqlite3 >/dev/null 2>&1; then
77+
sqlite3 /mnt/'"$DB_NAME"' "pragma integrity_check;"
78+
else
79+
echo "(alpine 无 sqlite3,跳过;容器启动后应用侧会校验)"
80+
fi'
81+
82+
echo "== 完成。现在可以 docker compose up -d 启动服务。"

0 commit comments

Comments
 (0)