使用Docker多阶段构建将Golang应用程序缩小成小型镜像大小的备忘录
听说可以使用基于Alpine Linux的小型镜像alpine(一种最小化的Docker镜像)来进行多阶段构建。
请准备以下两个文件(2021/06/18 -tags netgo 追记)。
FROM golang:latest as build
ADD ./ ./
ENV GOOS=linux GOARCH=amd64
RUN go build -tags netgo main.go
FROM alpine:latest
COPY --from=build /go/main /app/main
EXPOSE 8080
CMD [ "/app/main" ]
package main
import (
"fmt"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "golang test")
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}
- build
% docker build -t gotest test/
- image size
% docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
gotest latest 83fe32afaf4f 5 minutes ago 11.5MB
alpine latest b0e47758dc53 40 hours ago 5.33MB
golang latest 245bf9f4c37a 13 days ago 728MB
- run
% docker run --name go_docker -d -p 80:8080 gotest
...
% docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
eecc22a60f82 gotest "/app/main" 9 minutes ago Up 9 minutes 0.0.0.0:80->8080/tcp, :::80->8080/tcp go_docker
- access
% curl -i -6 http://localhost/
HTTP/1.1 200 OK
Date: Thu, 17 Jun 2021 13:39:51 GMT
Content-Length: 11
Content-Type: text/plain; charset=utf-8
golang test