用于golang的Docker多阶段构建可创建大形象
I want to use the multi stage build for my gaoling project, when I build the project locally for linux/windows/Mac I got 12.6 mb of size , I’ve currently small gaoling CLI program.
Now I want to build it with to build from it lightwhigt docker image with the scratch
option and build as
I use the following, but when I check the image, I see that the size it 366MB
, any idea what am I missing here?
It should be less then 20MB…
#build stage
FROM golang:alpine as builder
WORKDIR /go/src/tzf
ADD . /go/src/tzf
RUN CGO_ENABLED=0 go build -ldflags '-extldflags "-static"' -o ova tzf
RUN apk add --no-cache git
FROM golang:alpine
RUN mkdir /build
ADD . /build/
WORKDIR /build
RUN CGO_ENABLED=0 go build -ldflags '-extldflags "-static"' -o ova tzf
FROM scratch
COPY --from=builder /build/main /app/
WORKDIR /app
CMD [“./ova -v"]
当我在本地为linux / windows /构建项目时,我想对我的gailing项目使用多阶段构建 Mac
我的大小为 12.6 mb strong>,我目前有一个小的高空CLI程序。 p>
现在,我想用它来构建它,并使用lightwhigt docker image来构建它 使用 构建 scratch code>选项并以
as code> p>
as我使用以下内容,但是当我检查图像时,我看到它的大小
366MB code>,知道我在这里缺少什么吗?
应该小于20MB… p>
#build stage
FROM golang:alpine作为生成器\ nWORKDIR / go / src / tzf
ADD。 / go / src / tzf
RUN CGO_ENABLED = 0 go build -ldflags'-extldflags“ -static”'-o ova tzf
RUN apk add --no-cache git
FROM golang:alpine
RUN mkdir / build
ADD。 / build /
WORKDIR / build
RUN CGO_ENABLED = 0 go build -ldflags'-extldflags“ -static”'-o ova tzf
FROM scratch
COPY --from = builder / build / main / app /
WORKDIR / app \ nCMD [“ ./ova -v“]
code> pre>
div>
When you build your final image, be careful to copy only the exact files you want to end up in the image. It makes sense here to make your binary be the ENTRYPOINT of the image, since there's literally nothing else you can do with it.
I might make a two-stage pipeline like so:
# size of this stage doesn't matter; use the standard image
FROM golang AS builder
WORKDIR /go/src/tzf
ADD . ./
RUN CGO_ENABLED=0 go build -ldflags '-extldflags "-static"' -o /ova tzf
FROM scratch
# only copy the one file, may as well put it in /
COPY --from=builder /ova /ova
ENTRYPOINT ["/ova"]
# if you want to launch it with default options, you can
# CMD ["-v"]
You should use first a golang:alpine
container to build the app, then an alpine
to run the compiled app.
Something like this:
# builder
FROM golang:alpine AS builder
WORKDIR /go/src/tzf
ADD . /go/src/tzf
RUN CGO_ENABLED=0 go build -ldflags '-extldflags "-static"' -o ova tzf
# runner
FROM alpine
WORKDIR /app
COPY --from=builder /build/main /app/
CMD [“./ova -v"]
should result in a small footprint container.