修改了构建配置

main
mula.liu 2026-11-13 16:23:00 +08:00
parent 3212ee395c
commit 4c46dfb2a1
5 changed files with 44 additions and 3 deletions

View File

@ -10,10 +10,18 @@ BACKEND_PORT=8100
FRONTEND_PORT=5174
# ---- 数据库 ----
# 注意:Docker 容器里的 127.0.0.1 是容器自己,不是宿主机。
# 数据库在宿主机:用 host.docker.internal 或宿主机局域网 IP;
# 数据库是 Compose 服务:用服务名(如 postgres)。
DATABASE_URL=postgresql+asyncpg://postgres:sagacity@127.0.0.1:5432/nex_buddy
# Docker + 宿主机数据库示例:
# DATABASE_URL=postgresql+asyncpg://postgres:口令@host.docker.internal:5432/nex_buddy
# ---- 缓存 ----
# 同上:容器内不要写 127.0.0.1,除非 Redis 就在同一个容器里。
REDIS_URL=redis://127.0.0.1:6379/9
# Docker + 宿主机缓存示例:
# REDIS_URL=redis://host.docker.internal:6379/9
# ---- 和风天气 ----
# Key 直接可用;Host 是账号专属的,登录控制台 → 设置 复制(形如 abc1234xyz.re.qweatherapi.com)

View File

@ -6,6 +6,8 @@
services:
api:
# host.docker.internal 已在 docker-compose.yml 里默认配置;
# 数据库在宿主机时,把 .env 的 DATABASE_URL / REDIS_URL 改成 host.docker.internal 即可。
build:
args:
# 基础镜像:可改成服务器本地已有镜像或私有仓库地址

View File

@ -13,6 +13,10 @@ services:
PYTHON_IMAGE: "${PYTHON_IMAGE:-python:3.12-slim}"
image: nex-buddy-api:latest
init: true
# 让容器通过 host.docker.internal 访问宿主机上的 PostgreSQL/Redis。
# 数据库在别的机器时,这条配置不会产生影响。
extra_hosts:
- "host.docker.internal:host-gateway"
env_file:
- .env
environment:

View File

@ -111,3 +111,17 @@ HTTP_PORT=8080 ./scripts/docker-deploy.sh
```bash
POSTGRES_PASSWORD='强口令' ./scripts/docker-deploy.sh --full --init
```
## 数据库地址怎么写
容器里的 `127.0.0.1` / `localhost` 永远指容器自己,不是宿主机。
| 数据库位置 | `DATABASE_URL` 主机 | 额外配置 |
|---|---|---|
| Compose 的 `postgres` 服务 | `postgres` | 用 `--full` 启动 |
| 宿主机上的 PostgreSQL | `host.docker.internal` | 已默认配置 `extra_hosts` |
| 宿主机局域网 IP | `192.168.x.x` | PostgreSQL 监听 `0.0.0.0`,放行防火墙 |
| 另一个 Docker 容器 | 容器名或服务名 | 两个容器在同一 Docker 网络 |
`REDIS_URL` 同理。宿主机上的 PostgreSQL/Redis 必须监听容器能访问的地址,
只监听 `127.0.0.1` 时,即使写 `host.docker.internal` 也会 `Connection refused`。

View File

@ -1,8 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
#!/bin/sh
set -eu
DATA_DIR="${DATA_DIR:-/app/data}"
mkdir -p "$DATA_DIR/media" "$DATA_DIR/firmware"
echo ">> data dir: $DATA_DIR"
warn_localhost() {
case "$1" in
*@127.0.0.1:*|*@localhost:*|redis://127.0.0.1:*|redis://localhost:*)
echo "!! $2 指向 127.0.0.1/localhost;容器内这是容器自己,不是宿主机。" >&2
echo " 宿主机服务请用 host.docker.internal(需 extra_hosts)或宿主机局域网 IP;" >&2
echo " Compose 服务请用服务名(如 postgres / redis)。" >&2
;;
esac
}
warn_localhost "${DATABASE_URL:-}" DATABASE_URL
warn_localhost "${REDIS_URL:-}" REDIS_URL
# 首次使用空目录挂载时,把镜像内置的码表种子放进去。
if [ ! -f "$DATA_DIR/regions.json" ] && [ -f /app/seed/regions.json ]; then
@ -12,7 +25,7 @@ fi
cd /app/server
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
echo ">> alembic upgrade head"
echo ">> alembic upgrade head(失败时先检查 .env 的 DATABASE_URL)"
python -m alembic upgrade head
fi