Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

docker

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.

like image 940
kshah Avatar asked Jul 25 '16 19:07

kshah


People also ask

How do I run a container with a specific name?

You can assign memorable names to your docker containers when you run them, using the --name flag as follows. The -d flag tells docker to run a container in detached mode, in the background and print the new container ID. To view a list of all your docker containers, run the following command.

How do I run a command against a docker container?

Running Commands in an Alternate Directory in a Docker Container. To run a command in a certain directory of your container, use the --workdir flag to specify the directory: docker exec --workdir /tmp container-name pwd.

What happens if you don't name a docker container?

You can name your own containers with --name when you use docker run . If you do not provide a name, Docker will generate a random one like the one you have.

How do you run a docker container and give it a name?

FreeKB - Docker Assign a name to a container using the docker run --name command. When creating a container using the docker run command, the --name option can be used to give the container a specific name. In this example, a container is created using the foo:latest image, and the name of the container will be foo.


1 Answers

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 -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 
like image 94
ferdy Avatar answered Sep 20 '22 19:09

ferdy