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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With