CodeBlanks Logo Icon CodeBlanks

Summary - Docker

Combine multi-stage and scratch to write a minimal image.

Docker summary

The recipe for a good Go image: a multi-stage build, copying go.mod first to keep the cache, a static binary with CGO_ENABLED=0, a scratch or distroless base, version info with ARG + ldflags, metadata with LABEL, and Compose for the local development setup.

docker build --build-arg VERSION=1.0.0 -t app:1.0.0 .
docker run -p 8080:8080 app:1.0.0

The shutdown signal

docker stop sends SIGTERM to the process and kills it with SIGKILL after 10 seconds. The Go service should catch this signal and finish in-flight requests:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
go srv.ListenAndServe()
<-ctx.Done()
srv.Shutdown(context.Background())

Also use the exec form (ENTRYPOINT ["/app"]); with the shell form the signal may not reach the program.

Practice Shutdown on signal

Create ctx, cancel := context.WithCancel(context.Background()) and call cancel() in a goroutine to imitate the signal. Wait with <-ctx.Done(), then print fmt.Println("kapanıyor").

Starter code

main.go
package main

import (
    "context"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "context"
    "fmt"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go cancel()
    <-ctx.Done()
    fmt.Println("kapanıyor")
}

Expected output

kapanıyor

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which instruction runs the container as a non-root user?

  • EXPOSE
  • USER Correct answer
  • RUN
  • ARG

Explanation: USER runs following commands and the container process as the given user; distroless provides a ready "nonroot" user.

2 Non-root user

Question
FROM gcr.io/distroless/static
COPY --from=builder /out/app /app
____ nonroot
ENTRYPOINT ["/app"]
Answer
FROM gcr.io/distroless/static
COPY --from=builder /out/app /app
USER nonroot
ENTRYPOINT ["/app"]

Explanation: USER nonroot keeps the container from running with root privileges.

3 Group summary

Term Meaning
Multi-stage Small image
CGO_ENABLED=0 Static binary
SIGTERM Graceful shutdown
USER nonroot Safer

All lessons in Advanced