متقدم
البحث فيالمعامل
طريقة البحث
  • ابحث عن مهمة أو أداة (lvm، selinux، ‎@podman)؛ وصفِّ حسب المستوى والكتاب أو الدورة.
  • مع مربع بحث فارغ، الفلتر وحده يعرض المعامل — مثلًا كل المعامل الصعبة لدورة واحدة.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

معمل 5.1الحاويات, الفصل 5

Shrink an image from 900 MB to under 20 MB with a multi-stage build

المستوى
متوسط
40 دقيقة
الأجهزة
Linux, macOS or Windows with Docker (or Podman with the docker alias)
الحالة
لم يبدأ

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

الهدف

Build the same small Go web service twice: first the "easy" way in one stage, then the professional way with a multi-stage build, a pinned base image, a non-root user, labels and a health check. You measure the size, the number of packages and the CVEs of both images, so you can show the difference in numbers.

قبل أن تبدأ

  • docker version works. Optional: install Trivy (trivy --version) for the scan in task 6.
  • Make the folder ~/img-lab with two files:
    main.go
    package main
     
    import (
    	"fmt"
    	"net/http"
    	"os"
    )
     
    func main() {
    	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello from", os.Getenv("HOSTNAME")) })
    	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })
    	http.ListenAndServe(":8080", nil)
    }
    go.mod
    module imglab
     
    go 1.23

المهام

  1. Write Dockerfile.fat: one stage FROM golang:1.23, copy the code, go build, run the binary. Build it as imglab:fat.
  2. Write Dockerfile: a build stage (golang:1.23-alpine) that makes a static binary (CGO_ENABLED=0, -ldflags="-s -w"), and a final stage FROM gcr.io/distroless/static-debian12:nonroot that copies only the binary. Build it as imglab:slim.
  3. Pin the final base image by digest, add OCI labels (org.opencontainers.image.source, .version) and USER nonroot:nonroot.
  4. Compare the sizes of both images.
  5. Run the slim image with a read-only file system, no capabilities and no new privileges. Test /healthz.
  6. Scan both images with Trivy and compare the number of HIGH and CRITICAL findings.
  7. Add a .dockerignore so .git and local files never go into the build context.

تحقّق من عملك

docker images imglab
docker inspect imglab:slim --format '{{.Config.User}} {{index .Config.Labels "org.opencontainers.image.version"}}'
curl -s localhost:8080/healthz; echo
docker run --rm --entrypoint sh imglab:slim
  • imglab:fat is about 850–900 MB; imglab:slim is under 20 MB.
  • The user is nonroot:nonroot and the version label is shown.
  • /healthz answers ok.
  • The last command fails: there is no shell in the slim image (smaller attack surface).
  • Trivy shows many findings for fat and (almost) none for slim.

تلميحات

اعرض التلميحات
  • COPY --from=build /out/app /app copies only from the build stage.
  • Get a digest: docker buildx imagetools inspect gcr.io/distroless/static-debian12:nonroot.
  • Distroless images have no shell, so a HEALTHCHECK with curl does not work there; check health from outside (Docker Compose, Kubernetes probes) or build a tiny check into the app.
  • Safe run flags: --read-only --cap-drop ALL --security-opt no-new-privileges.

الحل

اعرض الحل
  1. The fat image.
    Dockerfile.fat
    FROM golang:1.23
    WORKDIR /src
    COPY . .
    RUN go build -o /app .
    CMD ["/app"]
    docker build -f Dockerfile.fat -t imglab:fat .
  2. The multi-stage image (replace the digest with the one you got).
    Dockerfile
    # syntax=docker/dockerfile:1
    FROM golang:1.23-alpine AS build
    WORKDIR /src
    COPY go.mod ./
    RUN go mod download
    COPY . .
    RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/app .
     
    FROM gcr.io/distroless/static-debian12:nonroot@sha256:<digest>
    LABEL org.opencontainers.image.source="https://github.com/s0sta/img-lab" \
          org.opencontainers.image.version="1.0.0"
    COPY --from=build /out/app /app
    USER nonroot:nonroot
    EXPOSE 8080
    ENTRYPOINT ["/app"]
    .dockerignore
    .git
    *.md
    Dockerfile*
    docker build -t imglab:slim .
  3. Compare.
    docker images imglab --format 'table {{.Tag}}\t{{.Size}}'
    TAG    SIZE
    slim   9.8MB
    fat    889MB
  4. Run it locked down and test.
    docker run -d --name web -p 8080:8080 --read-only --cap-drop ALL --security-opt no-new-privileges imglab:slim
    curl -s localhost:8080/healthz; echo
    ok
  5. Scan both.
    trivy image --severity HIGH,CRITICAL --quiet imglab:fat | tail -3
    trivy image --severity HIGH,CRITICAL --quiet imglab:slim | tail -3
    docker rm -f web

ملاحظاتي

لا توجد ملاحظات بعد.

دروس هذا المعمل

الأوامر في هذا المعمل