Search code examples
regexbashdocker

How to execute a Bash command only if a Docker container with a given name does not exist?


On a Jenkins machine I would like to create a docker container with a specified name only if it does not already exist (in a shell script). I thought I might run the command to create the container regardless and ignore the failure if there was one, but this causes my jenkins job to fail.

Hence, I would like to know how I can check if a docker container exists or not using bash.


Solution

  • You can check for non-existence of a running container by grepping for a <name> and fire it up later on like this:

    [ ! "$(docker ps -a | grep <name>)" ] && docker run -d --name <name> <image>
    

    Better:

    Make use of https://docs.docker.com/engine/reference/commandline/ps/ and check if an exited container blocks, so you can remove it first prior to run the container:

    if [ ! "$(docker ps -a -q -f name=<name>)" ]; then
        if [ "$(docker ps -aq -f status=exited -f name=<name>)" ]; then
            # cleanup
            docker rm <name>
        fi
        # run your container
        docker run -d --name <name> my-docker-image
    fi