使用 docker-go 启动容器必须显式设置 HostConfig,否则容器会立即退出;ContainerStop 是异步操作,需轮询 ContainerInspect 确认状态变为 "exited" 再执行删除。

用 docker-go 启动容器时必须显式设置 HostConfig
Go 调用 Docker API 启动容器,不填 HostConfig 会导致容器启动后立刻退出(状态为 Exited (0))。这是因为默认配置下容器没有绑定任何终端、没指定重启策略、也没分配资源限制,Docker 守护进程认为它“完成任务”就结束了。
-
HostConfig至少要包含AutoRemove: false和RestartPolicy(如需自动重启) - 若运行的是交互式命令(如
/bin/sh),必须同时设AttachStdin: true、AttachStdout: true、Tty: true - 使用
docker-go的ContainerCreate时,HostConfig是独立参数,不能塞进Config里
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: "alpine:latest",
Cmd: []string{"/bin/sh", "-c", "sleep 30"},
}, &container.HostConfig{
AutoRemove: false,
RestartPolicy: container.RestartPolicy{
Name: "no",
},
}, nil, nil, "my-container")停止容器别只调 ContainerStop,得等状态真正变更
ContainerStop 是异步触发,调完立即返回,不代表容器已停。直接跟 ContainerRemove 连用大概率报错 conflict: unable to remove filesystem for xxx: device or resource busy。
- 必须轮询
ContainerInspect查State.Status是否变成"exited" - 建议加超时(比如 15 秒),避免卡死;
time.Sleep固定延时不可靠,容器负载高时可能还没停完 - 注意:
State.Status是字符串,不是布尔值,别写成if state.Status == true
err := cli.ContainerStop(ctx, containerID, container.StopOptions{Timeout: 10})
if err != nil {
return err
}
// 等待真正停止
for i := 0; i < 30; i++ {
inspect, _ := cli.ContainerInspect(ctx, containerID)
if inspect.State.Status == "exited" {
break
}
time.Sleep(500 * time.Millisecond)
}删除容器前先确认是否在运行,否则 ContainerRemove 会失败
即使容器已退出,ContainerRemove 默认不删,除非显式传 Force: true 或 RemoveVolumes: true。但更稳妥的做法是先 Inspect 再判断——尤其在批量清理场景下,避免误删还在跑的同名容器。
-
ContainerRemove的Force参数相当于docker rm -f,会强制终止再删,慎用 - 如果容器挂载了匿名卷,且你希望一并清理,必须设
RemoveVolumes: true,否则卷残留 - 错误信息典型是:
Error response from daemon: conflict: unable to remove repository reference ... (must force)
inspect, _ := cli.ContainerInspect(ctx, containerID)
if inspect.State.Running {
// 可选:先 stop,或直接 force remove
}
_, err := cli.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
Force: true,
RemoveVolumes: true,
})容器日志读取要用 ContainerLogs 流式处理,别一次性读完
容器日志量大时,ContainerLogs 返回的 io.ReadCloser 如果直接 io.ReadAll,容易 OOM。尤其日志没做轮转、容器跑了几天的情况。
立即学习“go语言免费学习笔记(深入)”;
- 用
bufio.Scanner按行读,或io.Copy流式导出到文件 - 注意设置
stdout/stderr选项,否则可能拿不到任何输出(默认两者都关) - 日志时间戳默认不带纳秒级精度,如需对齐业务时间,得自己加
Since/Until参数过滤
logs, _ := cli.ContainerLogs(ctx, containerID, types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Timestamps: true,
})
scanner := bufio.NewScanner(logs)
for scanner.Scan() {
fmt.Println(scanner.Text())
}Docker 容器生命周期控制的坑,多数出在「假设 API 是同步的」或「忽略状态检查」。Go 客户端不会替你等容器停稳,也不会帮你判断该不该强删——这些逻辑得自己写清楚,尤其在自动化脚本或 operator 场景里。










