1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golangのアプリをdockerマルチステージビルドで小さいイメージサイズにするメモ

Last updated at Posted at 2021-06-17

小さいイメージの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
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?