# build stage FROM golang:alpine AS build-env ADD . /src RUN cd /src && go build -o app # final stage FROM alpine WORKDIR /app COPY --from=build-env /src/app /app/ ENTRYPOINT ./app
AS 及 --from 互相溝通,以往需要寫兩個 Dockerfile,現在只要一個就可以。最後執行編譯指令:
1 2
docker build -t yu/go-app . docker run --rm yu/go-app
最後大小為 6.35 MB,比較小了
參考範例: cmd/server/server.go 需要被更改成你的檔案
1 2 3 4 5 6 7 8 9 10 11 12 13
FROM golang:1.13 as builder
WORKDIR /app COPY . /app RUN CGO_ENABLED=0 GOOS=linux GOPROXY=https://proxy.golang.org go build -o app cmd/server/server.go
FROM alpine:latest # mailcap adds mime detection and ca-certificates help with TLS (basic stuff) RUN apk --no-cache add ca-certificates mailcap && addgroup -S app && adduser -S app -G app USER app WORKDIR /app COPY --from=builder /app/app . ENTRYPOINT ["./app"]