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.
I use following code to determine if docker container exists:
Robust grep
^$
without undocumented behaviorThis is the most precise and flexible approach I could find:
Rationale:
docker container inspect
and that-f name
takes regular expressions of some kind.Python
A Python version for convenience since I ended up using it in a project:
You can check for non-existence of a running container by grepping for a
<name>
and fire it up later on like this: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:
I suppose
since docker container inspect call will set $? to 1 if container does not exist (cannot inspect) but to 0 if it does exist (this respects stopped containers). So the run command will just be called in case container does not exist as expected.
Just prefix the name with ^/ and suffix with $. It seems that it is a regular expression:
You can use
filter
andformat
options fordocker ps
command to avoid piping with unix utilities likegrep
,awk
etc.