init.sh: apply_resolv_conf 失败 robust,不让容器整体退出

docker 在某些 kernel / version 组合下 /etc/resolv.conf 可能是 ro mount,
> redirect 失败 → set -e 触发 → 容器立即退出 → docker exec 报
"cannot exec in a stopped container"。

修法:tmp file 中转 + cat > 失败 || warn,resolv.conf 写不动也继续跑 iptables
等其他启动逻辑;此时容器仍能跑 shell/run_python,只是 DNS 解析跪 ── 比容器
直接退出可调试。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
caoqianming 2026-05-27 12:15:36 +08:00
parent ae15a36e58
commit 8743449711
1 changed files with 24 additions and 13 deletions

View File

@ -10,22 +10,33 @@ set -euo pipefail
apply_resolv_conf() {
# 覆写 /etc/resolv.conf 直接指公网 DNS,绕过 docker embedded DNS(127.0.0.11)。
# user-defined bridge network 默 resolv.conf = nameserver 127.0.0.11,embedded DNS
# 转发给 docker daemon 上游 ── 腾讯云轻量等场景 daemon 探测 systemd-resolved 失败
# → embedded DNS 自己 forward 不出去 → 全跪。docker run `--dns` flag 只改 daemon
# 上游不动 resolv.conf,在 user-defined network 上无效。
# init.sh root 跑可写 /etc/resolv.conf(docker bind mount file 而非 rootfs);
# --restart=no 容器整生命周期内不被 docker 覆盖。
if [ -n "${ZCBOT_DNS:-}" ]; then
{
# docker user-defined bridge network 默 resolv.conf = nameserver 127.0.0.11,
# embedded DNS 转发到 docker daemon 上游 ── 腾讯云轻量等场景 daemon 探测
# systemd-resolved 失败 → embedded DNS forward 不出去 → 全跪。`--dns` flag 只
# 改 daemon 上游不动 resolv.conf,在 user-defined network 上无效。
#
# 失败 robust:resolv.conf 在某些 docker / kernel 组合下是 ro mount,写不进
# 不能让 init.sh 整体退出(set -e),仅 warn 后继续跑 iptables 等其他启动逻辑;
# 此时容器仍能跑 shell / run_python,只是 DNS 解析跪 ── 比容器直接退好。
if [ -z "${ZCBOT_DNS:-}" ]; then
return 0
fi
local tmp
tmp="$(mktemp 2>/dev/null)" || tmp="/tmp/resolv.conf.tmp.$$"
: > "$tmp"
for ip in $(echo "$ZCBOT_DNS" | tr ',' ' '); do
[ -z "$ip" ] && continue
echo "nameserver $ip"
if [ -n "$ip" ]; then
echo "nameserver $ip" >> "$tmp"
fi
done
} > /etc/resolv.conf
if cat "$tmp" > /etc/resolv.conf 2>/dev/null; then
echo "[init] /etc/resolv.conf set:"
cat /etc/resolv.conf
else
echo "[init] WARN: cannot write /etc/resolv.conf (ro mount?);" \
"DNS via embedded 127.0.0.11 will be used as fallback" >&2
fi
rm -f "$tmp"
}
apply_blocklist() {