小さいイメージのalpine(A minimal Docker image based on Alpine Linux)を使ったマルチステージビルドってのを使うらしい
-以下2つのファイルを用意(2021/06/18 -tags netgo 追記)
./test/dockerfile
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" ]
./test/main.go
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