引言

对于dockerfile而言,何为完美? 我认为应该满足以下三点:

  • 体积小
  • 构建快
  • 够安全
Docker 17.05Dockerdocker17.05Dockerfile

可联网的环境

Go 1.13

我们使用go mod 做包管理,就不需要有任何额外配置

FROM golang:1.13.5-alpine3.10 AS builder

WORKDIR /build
RUN adduser -u 10001 -D app-runner

ENV GOPROXY https://goproxy.cn
COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -o your-application .

FROM alpine:3.10 AS final

WORKDIR /app
COPY --from=builder /build/your-application /app/
#COPY --from=builder /build/config /app/config
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

USER app-runner
ENTRYPOINT ["/app/your-application"]

首先,这个dockerfile分为builder和final两部分。

golang:1.13.5-alpine3.10golang:1.13golang:1.13alpine:3.10not found
RUN adduser -u 10001 -D app-runner
app-runner-D
finalcontainerrootmedium

再下面的四行,

ENV GOPROXY https://goproxy.cn
COPY go.mod .
COPY go.sum .
RUN go mod download
go mod download

builder的最后,就是把当前目录的文件拷过去,编译代码了。

COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -o your-application .
finalalpine:3.105malpine

接下来几行没啥说的,就是把构建结果、配置文件(有的话)和用户的相关文件拷过去。

下面的这步一定不要忘记了,

USER app-runner
containerrootroot
ENTRYPOINT
shell

离线打包

# Building stage
FROM golang:1.13.5-alpine3.10 AS builder

WORKDIR /build/src/your-application
RUN adduser -u 10001 -D app-runner

ENV GO111MODULE off
ENV GOPATH /build

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o your-application  main.go
#RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o your-application main.go

# Production stage
FROM alpine:3.10 AS final

WORKDIR /app

COPY --from=builder /build/src/your-application/example/linux /app
COPY --from=builder /build/src/your-application/your-application /app
#COPY --from=builder /build/src/your-application/conf /app/conf

RUN adduser -u 10001 -D app-runner
RUN chmod -R 755 /app

ENTRYPOINT ["/app/your-application"]
go modtimeoutGO111MODULE=offGOPATH
ENV GO111MODULE off
ENV GOPATH /build
vendor
go mod init your-application
go mod vendor

vendor
|——vendor

    └──github.com
    └──golang.org
    └──gopkg.in
    └──modules.txt

GO111MODULE=offmodgoGOPATHvendorGO111MODULE=onGOPATHvendorgo.modGO111MODULE=auto$GOPATH/srcgo.mod

有可能会遇到的问题

docker镜像源速度慢

如果docker镜像拉取速度太慢,或者拉取不到,可以试试改为国内镜像源地址,参考这里

更新docker的yum源

docker

引用

手把手教你写一个完美的Golang Dockerfile
Golang1.5到Golang1.12包管理:golang vendor 到 go mod
官方golang包管理神器,值得一试!go mod | 编程三分钟