Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a Docker container to be removed

Tags:

docker

I have a task that I run in a docker container. I only want one instance of it running, so I name the container. Occasionally I need to modify the code or configuration so I rebuild the image, and then stop and re-start the container with the new image. I'd been doing a docker stop followed by a docker run.

Recently, I tried to combine these into a single step:

docker stop myTask &&
    docker run --rm -d myTask myImage:$VERSION

However, this fails with:

docker: Error response from daemon: Conflict. The container name "/myTask" is already in use by container "49d806e25655a5e6f5309cc5509b54a10b4f0c84e60fad39856777881c99e9ce". You have to remove (or rename) that container to be able to reuse that name.

I then tried adding a docker wait in there:

docker stop myTask &&
    (docker wait myTask || true) &&
    docker run --rm -d myTask myImage:$VERSION

I still get this behavior. It seems docker wait only waits for the container to stop, but does not wait for it to be removed. I then tried using docker rm, thinking that it must surely wait for the container to be removed before returning:

docker stop myTask &&
    (docker rm myTask || true) &&
    docker run --rm -d myTask myImage:$VERSION

This still fails with a "The container name "/myTask" is already in use" error.

How can I block until there is no container with a given name?

like image 598
Laurence Gonsalves Avatar asked Dec 14 '25 13:12

Laurence Gonsalves


1 Answers

Stopping the container is not the same as removing it. You have a race condition after the container stops between the server side remove operation (enabled with the --rm) and the docker run command.

You can explicitly remove the container instead of just stopping it:

docker rm -f myTask &&
  docker run --rm -d myTask myImage:$VERSION

Or you can poll for it to be removed:

docker stop myTask &&
    while docker container inspect myTask >/dev/null 2>&1; do sleep 1; done &&
    docker run --rm -d myTask myImage:$VERSION
like image 159
BMitch Avatar answered Dec 16 '25 23:12

BMitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!