如何使用defer删除Docker容器?Gruntwork Docker模块测试场景
解决Gruntwork Docker模块测试后容器残留的问题
方案一:启用容器自动删除(推荐)
Gruntwork的docker.RunOptions支持Rm字段,对应Docker命令的--rm参数,开启后容器在运行结束(无论成功或失败)会自动删除,无需手动清理。修改你的测试代码如下:
func TestSomethinginDockerContainer(t *testing.T) { tag := "my-docker" buildOptions := &docker.BuildOptions{ Tags: []string{tag}, } // Build the Docker image. docker.Build(t, "docker", buildOptions) // Run the Docker image with auto-remove enabled runOptions := &docker.RunOptions{ Command: []string{"validate"}, Rm: true, // 开启自动删除,对应--rm参数 } output := docker.Run(t, tag, runOptions) // assert that there are no validation errors in the config assert.NotContains(t, output, "Error") }
方案二:手动注册清理函数
如果需要更灵活的清理逻辑(比如容器是后台运行的场景),可以通过t.Cleanup()注册一个清理函数,确保测试结束(无论成功、失败或 panic)时执行容器删除操作。
首先需要获取容器ID,你可以改用docker.RunAndGetID函数(该函数会返回运行的容器ID),然后在清理函数中调用Docker CLI或Go Docker SDK来删除容器:
import ( "os/exec" "github.com/gruntwork-io/terratest/modules/docker" "github.com/stretchr/testify/assert" ) func TestSomethinginDockerContainer(t *testing.T) { tag := "my-docker" buildOptions := &docker.BuildOptions{ Tags: []string{tag}, } docker.Build(t, "docker", buildOptions) runOptions := &docker.RunOptions{ Command: []string{"validate"}, Detach: true, // 后台运行容器 } // 获取容器ID containerID := docker.RunAndGetID(t, tag, runOptions) // 注册清理函数,测试结束时执行 t.Cleanup(func() { // 停止并删除容器 exec.Command("docker", "stop", containerID).Run() exec.Command("docker", "rm", containerID).Run() }) // 获取容器输出并断言 output := docker.Run(t, tag, runOptions) assert.NotContains(t, output, "Error") }
如果不想直接调用Docker CLI,也可以使用Go官方的Docker SDK(github.com/docker/docker/client)来实现容器删除逻辑,避免依赖系统环境中的Docker命令。
内容的提问来源于stack exchange,提问作者beedi
相关产品推荐
相关产品推荐

