From d124197cc726a3b69cc3cde8c4d560f3f0e1af9c Mon Sep 17 00:00:00 2001 From: Antonio Murdaca Date: Sun, 22 Mar 2015 19:09:12 +0100 Subject: [PATCH] Remove container if --rm flag is passed and container cannot be started Signed-off-by: Antonio Murdaca --- api/client/commands.go | 11 +++++-- integration-cli/docker_cli_run_test.go | 43 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/api/client/commands.go b/api/client/commands.go index 2b837596e8..cb0cd24235 100644 --- a/api/client/commands.go +++ b/api/client/commands.go @@ -2499,6 +2499,14 @@ func (cli *DockerCli) CmdRun(args ...string) error { } } + defer func() { + if *flAutoRemove { + if _, _, err = readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, false)); err != nil { + log.Errorf("Error deleting container: %s", err) + } + } + }() + //start the container if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, false)); err != nil { return err @@ -2536,9 +2544,6 @@ func (cli *DockerCli) CmdRun(args ...string) error { if _, status, err = getExitCode(cli, createResponse.ID); err != nil { return err } - if _, _, err := readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, false)); err != nil { - return err - } } else { // No Autoremove: Simply retrieve the exit code if !config.Tty { diff --git a/integration-cli/docker_cli_run_test.go b/integration-cli/docker_cli_run_test.go index 636ef36e12..4f6f646a52 100644 --- a/integration-cli/docker_cli_run_test.go +++ b/integration-cli/docker_cli_run_test.go @@ -3348,3 +3348,46 @@ func TestRunVolumesFromRestartAfterRemoved(t *testing.T) { logDone("run - can restart a volumes-from container after producer is removed") } + +// run container with --rm should remove container if exit code != 0 +func TestRunContainerWithRmFlagExitCodeNotEqualToZero(t *testing.T) { + defer deleteAllContainers() + + runCmd := exec.Command(dockerBinary, "run", "--rm", "busybox", "ls", "/notexists") + out, _, err := runCommandWithOutput(runCmd) + if err == nil { + t.Fatal("Expected docker run to fail", out, err) + } + + out, err = getAllContainers() + if err != nil { + t.Fatal(out, err) + } + + if out != "" { + t.Fatal("Expected not to have containers", out) + } + + logDone("run - container is removed if run with --rm and exit code != 0") +} + +func TestRunContainerWithRmFlagCannotStartContainer(t *testing.T) { + defer deleteAllContainers() + + runCmd := exec.Command(dockerBinary, "run", "--rm", "busybox", "commandNotFound") + out, _, err := runCommandWithOutput(runCmd) + if err == nil { + t.Fatal("Expected docker run to fail", out, err) + } + + out, err = getAllContainers() + if err != nil { + t.Fatal(out, err) + } + + if out != "" { + t.Fatal("Expected not to have containers", out) + } + + logDone("run - container is removed if run with --rm and cannot start") +}