从单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
相关产品推荐
相关产品推荐

