问题描述
在Jenkins机器上,我只想创建一个具有指定名称的docker容器,前提是该容器尚不存在(在shell脚本中).我以为我可能会运行该命令来创建容器,而忽略存在该容器的失败,但这会导致我的詹金斯工作失败.
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.
因此,我想知道如何检查docker容器是否存在或不使用bash.
Hence, I would like to know how I can check if a docker container exists or not using bash.
推荐答案
您可以通过grepping <name>
来检查正在运行的容器是否不存在,然后像这样启动它:
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>
更好:
充分利用 https://docs.docker.com/engine/reference/命令行/ps/,并检查退出的容器是否阻塞,因此您可以在运行容器之前先将其删除:
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
这篇关于仅当不存在具有给定名称的Docker容器时,如何执行Bash命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!