# syntax=docker/dockerfile:1FROM golang:1.19# Set destination for COPYWORKDIR /app# Download Go modulesCOPY go.mod go.sum ./RUN go mod download# Copy the source code. Note the slash at the end, as explained in# https://docker-docs.dev.org.tw/reference/dockerfile/#copyCOPY *.go ./# BuildRUNCGO_ENABLED=0GOOS=linux go build -o /docker-gs-ping# Optional:# To bind to a TCP port, runtime parameters must be supplied to the docker command.# But we can document in the Dockerfile what ports# the application is going to listen on by default.# https://docker-docs.dev.org.tw/reference/dockerfile/#exposeEXPOSE 8080# RunCMD["/docker-gs-ping"]
$ docker image tag docker-gs-ping:latest docker-gs-ping:v1.0
Docker tag 命令為映像創建一個新標記。它不會創建新映像。該標記指向同一個映像,只是引用映像的另一種方式。
現在再次運行 docker image ls 命令以查看更新的本地映像列表
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
docker-gs-ping latest 7f153fbcc0a8 6 minutes ago 1.11GB
docker-gs-ping v1.0 7f153fbcc0a8 6 minutes ago 1.11GB
...
您可以看到您有兩個以 docker-gs-ping 開頭的映像。您知道它們是同一個映像,因為如果您查看 IMAGE ID 欄,您可以看到兩個映像的值相同。此值是 Docker 在內部用於識別映像的唯一標識符。
因此,在以下示例中,您將使用完整規模的官方 Go 映像來構建您的應用程式。然後,您將應用程式二進制文件複製到另一個映像中,該映像的基礎非常精簡,不包含 Go 工具鏈或其他可選組件。
範例應用程式儲存庫中的 Dockerfile.multistage 具有以下內容
# syntax=docker/dockerfile:1# Build the application from sourceFROM golang:1.19 AS build-stageWORKDIR /appCOPY go.mod go.sum ./RUN go mod downloadCOPY *.go ./RUNCGO_ENABLED=0GOOS=linux go build -o /docker-gs-ping# Run the tests in the containerFROM build-stage AS run-test-stageRUN go test -v ./...# Deploy the application binary into a lean imageFROM gcr.io/distroless/base-debian11 AS build-release-stageWORKDIR /COPY --from=build-stage /docker-gs-ping /docker-gs-pingEXPOSE 8080USER nonroot:nonrootENTRYPOINT["/docker-gs-ping"]
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
docker-gs-ping multistage e3fdde09f172 About a minute ago 28.1MB
docker-gs-ping latest 336a3f164d0f About an hour ago 1.11GB