如何在使用Docker Compose的Azure发布管道中回滚到旧版本
问题描述
我已完成镜像构建并推送到Azure容器注册表(ACR),目前有多个带构建标签的镜像,比如api-image:23、api-image:24、api-image:25等。当前生产环境运行的是标签25(同时标记为latest)的镜像,现在想通过Azure发布管道历史回滚到api-image:23。但我的docker-compose文件中image字段值为api-image,会自动拉取latest标签的镜像,有三个疑问:
- 如何让docker-compose文件动态获取指定的镜像标签?
- 回滚到过往版本时,compose文件如何知晓要使用的版本?
- 目标镜像已存在于ACR中,是否无需重新构建项目,直接复用该镜像即可?
备注:主机是本地Debian 11系统。
附上当前配置文件内容:
docker-compose.yml
version: '3.3' services: reverse-proxy: image: xx.azurecr.io/nginx container_name: mars_proxy build: context: . dockerfile: reverse-proxy/Dockerfile ports: - 80:80 restart: always slider: image: xx.azurecr.io/mars-slider container_name: slider build: context: . dockerfile: Mars.Slider/Presentation/Dockerfile ports: - "8081:5100" restart: always
azure-pipelines.yml
trigger: - develop steps: - task: DockerCompose@0 displayName: "Container registry login" inputs: containerregistrytype: "Azure Container Registry" #azureSubscription = Azure resource manager service connection name azureSubscription: "subname" azureContainerRegistry: '{"loginServer":"xx.azurecr.io", "id" : ""}' dockerComposeFile: '**/docker-compose.yml' additionalImageTags: $(Build.BuildId) action: 'Build services' - task: DockerCompose@0 inputs: containerregistrytype: "Azure Container Registry" azureSubscription: "subname" azureContainerRegistry: '{"loginServer":"xx.azurecr.io", "id" : ""}' dockerComposeFile: '**/docker-compose.yml' additionalImageTags: $(Build.BuildId) action: 'Push services'
解决方案
1. 让docker-compose动态获取指定镜像标签
推荐两种实用方式:
方式一:环境变量占位符
修改docker-compose.yml,给image字段添加环境变量占位符,默认值设为latest兼容原有逻辑:
version: '3.3' services: reverse-proxy: image: xx.azurecr.io/nginx:${IMAGE_TAG:-latest} container_name: mars_proxy # 生产部署时建议删除build块,避免误触发构建;如需保留,部署时加--no-build参数 # build: # context: . # dockerfile: reverse-proxy/Dockerfile ports: - 80:80 restart: always slider: image: xx.azurecr.io/mars-slider:${IMAGE_TAG:-latest} container_name: slider # build: # context: . # dockerfile: Mars.Slider/Presentation/Dockerfile ports: - "8081:5100" restart: always
部署时通过环境变量指定标签即可:
IMAGE_TAG=23 docker-compose up -d
方式二:模板文件+变量替换
创建docker-compose.template.yml作为模板(内容和上面环境变量版一致),部署时用Debian自带的envsubst工具生成最终配置文件:
envsubst < docker-compose.template.yml > docker-compose.yml
2. 回滚时让compose知晓目标版本
回滚的核心是把历史构建的BuildId(即你的镜像标签23、24)传递给部署环节:
- 在Azure发布管道的回滚操作中,选择对应历史构建的BuildId;
- 把该BuildId赋值给
IMAGE_TAG环境变量,注入到部署步骤; - docker-compose会通过环境变量自动拉取对应标签的镜像。
建议在管道中添加部署记录步骤,把每次使用的镜像标签存入日志,方便快速定位回滚版本。
3. 已存在镜像无需重新构建
只要目标镜像(比如api-image:23)已经推送到ACR,完全不需要重新构建项目,直接复用即可:
- 确保本地Debian主机已登录ACR:
az acr login --name xx
- 指定标签启动容器:
IMAGE_TAG=23 docker-compose up -d --no-build
(加--no-build是防止docker-compose误触发构建,如果你已经删除了build块可以省略)
内容的提问来源于stack exchange,提问作者godzkaya
相关产品推荐
相关产品推荐

