阻止Jenkins中Docker容器的最佳方法

4 jenkins docker

我有一个CI服务器(jenkins)正在构建新的Docker镜像.现在我想在构建成功时运行一个新的Docker容器.但是因此我必须停止以前运行的容器.

执行此操作的最佳方式是什么? localhost:5000/test/myapp:"${BUILD_ID}是我的新图像的名称.所以我使用build-id作为标记.首先我想要表演:

docker stop localhost:5000/dbm/my-php-app:${BUILD_ID-1}
Run Code Online (Sandbox Code Playgroud)

但这不是一个正确的解决方案,因为当构建失败时,这将是错误的.

Build 1: succes -> run container 1 
Build 2: failed -> run container 1
Build 3: succes -> stop container (3-1) =2 --> wrong (isn't running)
Run Code Online (Sandbox Code Playgroud)

什么可以解决方案?我也不得不改变标签的建议

Tho*_*eil 6

docker stop命令将docker容器名称作为参数,而不是docker镜像ID.

您必须在运行时为容器命名:

# build the new image
docker build -t localhost:5000/test/myapp:"${BUILD_ID}" .

# remove the existing container
docker rm -f myjob && echo "container myjob removed" || echo "container myjob does not exist"

# create and run a new container
docker run -d --name myjob localhost:5000/test/myapp:"${BUILD_ID}"
Run Code Online (Sandbox Code Playgroud)

只需myjob在此示例中替换为更合适的名称即可.


小智 5

感谢@Thomasleveil,我在我的问题上找到了答案:

# build the new image
docker build -t localhost:5000/test/myapp:"${BUILD_ID}" .


# remove old container
SUCCESS_BUILD=`wget -qO- http://jenkins_url:8080/job/jobname/lastSuccessfulBuild/buildNumber`

docker rm -f "${SUCCESS_BUILD}" && echo "container ${SUCCESS_BUILD} removed" || echo "container ${SUCCESS_BUILD} does not exist"

# run new container
docker run -d -p 80:80 --name "${BUILD_ID}" localhost:5000/test/myapp:${version}
Run Code Online (Sandbox Code Playgroud)