我试图在部署时实现以下目标:
- [如果找到旧容器]重命名并停止
- 从最新映像运行新容器
我用这种方式尝试(这是我的gitlab ci.yml的代码(
# these two work, so docker is running and reachable
- ssh deploy@$URL_STAGE docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY
- ssh deploy@$URL_STAGE docker pull $CI_REGISTRY_IMAGE/$AMC_BACKEND_DOCKER_IMAGE_NAME:latest
# rename and stop ('docker inspect' to ensure the container exists, see https://stackoverflow.com/a/45171589)
- ssh deploy@$URL_STAGE docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME > /dev/null 2>&1 && docker rename $AMC_BACKEND_DOCKER_IMAGE_NAME $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp
- ssh deploy@$URL_STAGE docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp > /dev/null 2>&1 && docker stop -t 5 $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp # sends SIGTERM and after t seconds SIGKILL
日志的最后几行是
$ ssh deploy@$URL_STAGE docker pull $CI_REGISTRY_IMAGE/$AMC_BACKEND_DOCKER_IMAGE_NAME:latest
...
Status: Downloaded newer image for ...:latest
$ ssh deploy@$URL_STAGE docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME > /dev/null 2>&1 && docker rename $AMC_BACKEND_DOCKER_IMAGE_NAME $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp
/bin/sh: eval: line 155: docker: not found
- 我将相同的命令复制到服务器(替换变量(,它在那里工作
- 也适用于
ssh localhost docker ...
- 删除
> /dev/null 2>&1
时也不起作用
不知何故,&;似乎在运行";其他地方";(在不存在命令docker的情况下(
知道吗?
我现在这样做(使用多行命令只连接一次(
- |
ssh deploy@$URL_STAGE "
# -x Makes the server print the executed commands to stdout.
# -e Makes the execution stop when one of the commands fails.
set -x -e
### keep the last two containers for easy roleback ###
# if there is a bkp2 container -> remove it
docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp2 > /dev/null 2>&1 && docker rm $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp2
# if there is a bkp container -> rename it to bkp2
docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp > /dev/null 2>&1 && docker rename $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp2
# if there is a former app container -> stop it and rename it to bkp
docker container inspect $AMC_BACKEND_DOCKER_IMAGE_NAME > /dev/null 2>&1 && docker stop -t 5 $AMC_BACKEND_DOCKER_IMAGE_NAME
&& docker rename $AMC_BACKEND_DOCKER_IMAGE_NAME $AMC_BACKEND_DOCKER_IMAGE_NAME-bkp
### run the new app container ###
docker run
--name $AMC_BACKEND_DOCKER_IMAGE_NAME
-d
-p $AMC_BACKEND_LISTEN_ADRESS:3000
-e DOTENV_CONFIG_PATH=$ENV_FILE_PATH_IN_CONTAINER
--mount type=bind,source=$ENV_FILE_PATH_ON_SERVER,target=$ENV_FILE_PATH_IN_CONTAINER,readonly
--restart unless-stopped
$CI_REGISTRY_IMAGE/$AMC_BACKEND_DOCKER_IMAGE_NAME:latest
"