如何为开发和生产使用相同的dockerfile [英] How to use the same dockerfile for dev and prod
问题描述
我有2个Dockerfile,1个用于dev,1个用于prod:
I have 2 Dockerfile, 1 for dev, and 1 for prod:
PROD:
FROM golang AS builder
WORKDIR /go/src/gitlab.com/company/project
COPY . .
RUN go build -o ./release/api .
FROM scratch
EXPOSE 9999
COPY --from=builder /go/src/gitlab.com/company/project/release/api .
CMD ["./api"]
和DEV:
FROM golang
WORKDIR /go/src/gitlab.com/company/PROJECT
COPY . .
RUN go build -o ./release/api .
CMD ["./release/api"]
我想将两者合并维护2个Dockerfile是一个单一的坏习惯
I would like to merge those two into a single one, as maintaining 2 Dockerfile is a bad practice
主要区别在于,在dev中,我处理的是 golang
图像,这很实用,而在产品中,我使用的是 scratch
图像,它减少了我的二进制文件的大小。
The main difference is that in dev, I work on golang
image, which is practical, and in prod, I work with scratch
image, which reduce a lot the size of my binary.
似乎我可以使用Dockerfile中的多个阶段,并在构建时指定阶段名称:
It seems that I can use multiple stages in a Dockerfile, and specify stage name at build time:
docker build . --target=builder
但是如果我这样做,我将不知道如何有条件地运行我的第一阶段的应用程序= [如果我是开发人员,请在第一阶段运行该应用程序,否则,在第二阶段运行该应用程序]
But If I do this, I don't know how to conditionnaly run my app in the first stage = [ If I am in dev, run the app in the first stage, otherwise, run the app in the second stage]
我该怎么办
推荐答案
怎么办?我没有测试它,也没有深入思考您的示例,但是也许在您需要的地方/可以帮助您找到最终的解决方案?
What about something like this? I didn't test it and didn't think through your example deeply, but maybe is somewhere close to what you need/helps you finding out the final solution?
FROM golang:alpine AS base
WORKDIR /go/src/gitlab.com/company/project
COPY . .
RUN go build -o ./release/api .
FROM base AS dev
CMD ["./release/api"]
FROM scratch AS prod
EXPOSE 9999
COPY --from=base /go/src/gitlab.com/company/project/release/api .
CMD ["./api"]
取决于目标<$中指定的值c $ c> docker build --target = prod 或 docker build --target = dev
,将生成其他图像。
Depending on the value specified in target docker build --target=prod
or docker build --target=dev
, a different image will get built.
这篇关于如何为开发和生产使用相同的dockerfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!