Browse Source

Remove container if --rm flag is passed and container cannot be started

Signed-off-by: Antonio Murdaca <me@runcom.ninja>
Antonio Murdaca 10 years ago
parent
commit
d124197cc7
2 changed files with 51 additions and 3 deletions
  1. 8 3
      api/client/commands.go
  2. 43 0
      integration-cli/docker_cli_run_test.go

+ 8 - 3
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 {

+ 43 - 0
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")
+}