diff --git a/daemon/create.go b/daemon/create.go index 385618c7b4..521e6d5d75 100644 --- a/daemon/create.go +++ b/daemon/create.go @@ -40,7 +40,7 @@ func (daemon *Daemon) ContainerCreate(name string, config *runconfig.Config, hos } // Create creates a new container from the given configuration with a given name. -func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (*Container, []string, error) { +func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (retC *Container, retS []string, retErr error) { var ( container *Container warnings []string @@ -75,6 +75,14 @@ func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos if container, err = daemon.newContainer(name, config, imgID); err != nil { return nil, nil, err } + defer func() { + if retErr != nil { + if err := daemon.rm(container, false); err != nil { + logrus.Errorf("Clean up Error! Cannot destroy container %s: %v", container.ID, err) + } + } + }() + if err := daemon.Register(container); err != nil { return nil, nil, err } diff --git a/integration-cli/docker_cli_run_test.go b/integration-cli/docker_cli_run_test.go index 040bcdaae4..35af1aba30 100644 --- a/integration-cli/docker_cli_run_test.go +++ b/integration-cli/docker_cli_run_test.go @@ -2816,3 +2816,13 @@ func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) { dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") } + +// run create container failed should clean up the container +func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) { + name := "unique_name" + _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox") + c.Assert(err, check.Not(check.IsNil), check.Commentf("Expected docker run to fail!")) + + containerID, err := inspectField(name, "Id") + c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID)) +}