Çok aşamalı yapı kullanımının amacı, uygulamanın son docker imajını olabildiğince küçük tutmaktır, burada yapacağımız şey budur. Ayrıca size vendor olan ve olmayan sürüm yapısını da göstereceğim. İçinden birini seçmek size kalmış, ancak Go paket yönetiminde iyi olduğu için, ben şahsen hiçbir zaman vendor sürümünü kullanmaya gerek duymadım.


Yapı


.
├── cmd
│   └── football
│   └── main.go
├── docker
│   └── dev
│   ├── docker-compose.yaml
│   └── go
│   └── Dockerfile
├── .env.dist
├── go.mod
├── go.sum
└── Makefile

docker-compose.yaml


version: "3.4"

services:

football-go:
container_name: "football-go"
hostname: "football-go"
build:
context: "../.."
dockerfile: "docker/dev/go/Dockerfile"
restart: "unless-stopped"
volumes:
- "../../.env.dist:/.env"

Vendor olmayan versiyon


Dockerfile


#
# STAGE 1: prepare
#
FROM golang:1.13.1-alpine3.10 as prepare

WORKDIR /source

COPY go.mod .
COPY go.sum .

RUN go mod download

#
# STAGE 2: build
#
FROM prepare AS build

COPY . .

RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/football cmd/football/main.go

#
# STAGE 3: run
#
FROM scratch as run

COPY --from=build /source/bin/football /football

ENTRYPOINT ["/football"]

Kısa versiyon

#
# STAGE 1: build
#
FROM golang:1.13.1-alpine3.10 as build

WORKDIR /source
COPY . .

RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/football cmd/football/main.go

#
# STAGE 2: run
#
FROM alpine:3.10 as run

COPY --from=build /source/bin/football /football

ENTRYPOINT ["/football"]

Kur ve çalıştır


Bu komutların Makefile dosyanızın bir parçası olduğunu varsayıyorum.


// Prune unused packages and dependencies from go.mod file.
$ go mod tidy -v

// Compile packages and dependencies then run the app.
$ go build -race -ldflags "-s -w" -o bin/football cmd/football/main.go
$ bin/football

Vendor olan versiyon


Dockerfile


Bu durumda, uygulama kökünde vendor klasörü olmalıdır. Bununla birlikte, değişkenlerin tümünün kopyalanabilmesi için aşağıda belirtildiği gibi iki ek komut çalıştırmanız gerekir.


#
# STAGE 1: prepare
#
FROM golang:1.13.1-alpine3.10 as prepare

WORKDIR /source

COPY vendor .

#
# STAGE 2: build
#
FROM prepare AS build

COPY . .

RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/football cmd/football/main.go

#
# STAGE 3: run
#
FROM scratch as run

COPY --from=build /source/bin/football /football

ENTRYPOINT ["/football"]

Kur ve çalıştır


Bu komutların Makefile dosyanızın bir parçası olduğunu varsayıyorum.


// Prune unused packages and dependencies from go.mod file.
$ go mod tidy -v

// Reset vendor directory to include all dependencies and rebuild.
$ go mod vendor
$ go build -mod vendor ./...

// Compile packages and dependencies then run the app.
$ go build -race -ldflags "-s -w" -o bin/football cmd/football/main.go
$ bin/football