先 COPY go.mod
執行 go mod download
,再 COPY 源碼執行 build。linux
利用 docker image 分層構建的特性,每行命令爲一層。若是底層不變,則可以使用 cache,無需重複構建。git
源碼比 go.mod 修改更頻繁。github
FROM golang:1.15-alpine AS builder WORKDIR /workspace ENV GO111MODULE=on \ GOPROXY=https://goproxy.cn,direct # cache deps before building and copying source so that we don't need to re-download as much # and so that source changes don't invalidate our downloaded layer COPY go.mod go.mod COPY go.sum go.sum RUN go mod download # src code COPY . . RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main ./cmd/server FROM alpine:3.12 COPY --from=builder /workspace/main /main RUN chmod +x /main ENV TZ=Asia/Shanghai ENTRYPOINT ["/main"]
.dockerignore
只 COPY go build 須要的文件。golang
# More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file # Ignore all files which are not go type !**/*.go !**/*.mod !**/*.sum
open ./local/pkg/foo/go.mod no such file
。須要把全部 go.mod 都 COPY 進去。go:embed
相似功能內嵌文件,相關文件須要在 .dockerignore
中去除忽略。