You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从单Dockerfile构建多镜像时环境变量不符合预期的问题排查

问题原因与解决方法

你的问题出在Docker Compose的构建配置上:当你只指定build: .时,Compose默认会构建Dockerfile里的最后一个阶段,而不是你期望的和镜像名对应的阶段。你的Dockerfile最后一个阶段是image2,所以不管你在service1还是service2里指定image字段,实际构建出来的都是image2阶段的镜像,这就导致两个镜像都带有ENV KEY2=VALUE2。

要解决这个问题,需要在每个服务的build配置里明确指定要构建的Dockerfile阶段(通过target参数):

修改后的compose.yaml:

services:
  service1:
    container_name: container1
    build:
      context: .
      target: image1
    image: image1
  service2:
    container_name: container2
    build:
      context: .
      target: image2
    image: image2

这样配置后,service1会构建Dockerfile中标记为AS image1的阶段,生成包含ENV KEY1=VALUE1的镜像;service2则构建AS image2的阶段,生成包含ENV KEY2=VALUE2的镜像。

内容的提问来源于stack exchange,提问作者Graznarak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:42:02