How to execute a Bash command only if a Docker con

2019-03-08 13:38发布

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.

标签: bash docker
8条回答
够拽才男人
2楼-- · 2019-03-08 14:24

Even shorter with docker top:

docker top <name> || docker run --name <name> <image>

docker top returns non-zero when there are no containers matching the name running, else it returns the pid, user, running time and command.

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-08 14:26
if [[ $(sudo docker inspect --format . <container-name>) == "." ]]; then
  docker run <container-name>;
fi

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 return itIsThere 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.

查看更多
登录 后发表回答