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.
Even shorter with docker top:
docker top
returns non-zero when there are no containers matching the name running, else it returns the pid, user, running time and command.Explanation:
There is a similar response already. The difference here is the
--format .
option (you can also use-f .
). This removes all the details from the inspect command. Docker uses the go template format, which in this case means that it will copy to the output anything it does not recognize.So
-f itIsThere
will returnitIsThere
if a container with that namex exits. If it doesn't, docker will return an error code and message (Error: No such object: <container-name>
).I found this one in Jenkins logs.