Dockerfile

COPY go.modgo mod download

利用 docker image 分层构建的特性,每行命令为一层。如果底层不变,则可使用 cache,无需重复构建。

源码比 go.mod 修改更频繁。

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 需要的文件。

# 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 filego:embed.dockerignore

Reference