brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: COPY with link keeps a Docker layer valid when the base image changes

Docker
~/tips/tip-dockerfile-copy-link

COPY . .

Copy files into their own independent layer so base image updates do not force a recopy.

Normally every layer depends on the ones below it, so a new base image invalidates every COPY after it. With --link, the copied files go into a layer of their own that can be reused on top of a changed base.

# syntax=docker/dockerfile:1
FROM golang:1.26 AS build
WORKDIR /src
COPY . .
RUN go build -o /out/app .

FROM alpine:3.24
COPY --link --from=build /out/app /usr/local/bin/app

When alpine:3.24 gets a security update, BuildKit can reuse the linked layer as it is and only swap the base underneath. In a multi-stage build like this, copying the final binary with --link is where I would use it first.

The docs describe how it works: the files are copied into an empty directory, and that directory becomes a layer linked on top of the previous state. That is also where the catch comes from. A linked copy cannot see the earlier layers, so it cannot follow a symlink in the destination path. If /usr/local/bin were a symlink in the base image, the result would not be what you expect. Keep plain COPY where the destination depends on what is already there.

Further reading: Dockerfile reference: COPY –link

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link