Reduce image size

2 snippets in Docker

DKDocker

Multi-Stage Builds

DK · Dockerfile
syntax
FROM <image> AS <stage>
...
FROM <image>
COPY --from=<stage> <src> <dest>
example
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

Note The final image only contains the layers from the last FROM stage. Build tools, dev dependencies, and source code from earlier stages are discarded, dramatically reducing image size. A Go API might go from 1.2GB (with SDK) to 15MB (static binary on scratch).

Use Multi-Stage Builds

DK · Best Practices
syntax
FROM <image> AS build
...
FROM <image>
COPY --from=build ...
example
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server .

FROM gcr.io/distroless/static-debian12
COPY --from=build /app/server /app/server
CMD ["/app/server"]

Note The Go SDK (800MB+) stays in the build stage only. The final image is just the static binary on distroless (~2MB). This pattern works for any compiled language and even for frontend builds where you need Node to compile but only serve static files.