最簡單的Go Dockerfile編寫姿式,沒有之一!

1. Dockerfile一些額外注意點

  • 選擇最簡單的鏡像

    好比alpine,整個鏡像5M左右linux

  • 設置鏡像時區git

    RUN apk add --no-cache tzdata
    ENV TZ Asia/Shanghai

2. 多階段構建

  • 第一階段構建不然構建出可執行文件,確保構建過程獨立於宿主機
  • 第二階段將第一階段的輸出做爲輸入,構建出最終的極簡鏡像

3. 完整Dockerfile編寫過程

  • 首先安裝 goctl 工具

    GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/tal-tech/go-zero/tools/goctlgithub

  • greet 項目下建立一個 hello 服務golang

    goctl api new hellodocker

    文件結構以下:shell

    greet
    ├── go.mod
    ├── go.sum
    └── service
        └── hello
            ├── Dockerfile
            ├── etc
            │   └── hello-api.yaml
            ├── hello.api
            ├── hello.go
            └── internal
                ├── config
                │   └── config.go
                ├── handler
                │   ├── hellohandler.go
                │   └── routes.go
                ├── logic
                │   └── hellologic.go
                ├── svc
                │   └── servicecontext.go
                └── types
                    └── types.go
  • hello 目錄下一鍵生成 Dockerfile

    goctl docker -go greet.gojson

    Dockerfile 內容以下:api

FROM golang:alpine AS builder

LABEL stage=gobuilder

ENV CGO_ENABLED 0
ENV GOOS linux
ENV GOPROXY https://goproxy.cn,direct

WORKDIR /build/zero

ADD go.mod .
ADD go.sum .
RUN go mod download
COPY . .
COPY service/hello/etc /app/etc
RUN go build -ldflags="-s -w" -o /app/hello service/hello/hello.go


FROM alpine

RUN apk update --no-cache && apk add --no-cache ca-certificates tzdata
ENV TZ Asia/Shanghai

WORKDIR /app
COPY --from=builder /app/hello /app/hello
COPY --from=builder /app/etc /app/etc

CMD ["./hello", "-f", "etc/hello-api.yaml"]
  • greet 目錄下 build 鏡像

    docker build -t hello:v1 -f service/hello/Dockerfile .app

  • 查看鏡像

    hello v1 5455f2eaea6b 7 minutes ago 18.1MBcurl

    能夠看出鏡像大小約爲18M。

  • 啓動服務

    docker run --rm -it -p 8888:8888 hello:v1

  • 測試服務

    $ curl -i http://localhost:8888/from/you
    HTTP/1.1 200 OK
    Content-Type: application/json
    Date: Thu, 10 Dec 2020 06:03:02 GMT
    Content-Length: 14
    
    {"message":""}

4. 總結

goctl 工具極大簡化了 Dockerfile 文件的編寫,提供了開箱即用的最佳實踐,而且支持了模板自定義。

若是以爲工具備幫助,歡迎 star 🤝

5. 項目地址

https://github.com/tal-tech/go-zero

項目地址:
https://github.com/tal-tech/go-zero
相關文章
相關標籤/搜索