Difficulty: Advanced
What is the ONBUILD instruction in a Dockerfile, when does it run, and why is it rarely used today?
ONBUILD registers an instruction that does not run when you build the current image. Instead it is stored in the image metadata as a trigger, and it runs automatically in any later build that uses this image in its FROM line, immediately after that FROM. It lets a base image author define steps every child image must perform, such as copying source code and installing dependencies.
ONBUILD COPY package*.json ./ and ONBUILD RUN npm ci.Config.OnBuild.FROM company/node-base:1.0 in their app Dockerfile.FROM, using the child build's context, then continues with the child's own instructions.You can see an image's triggers with docker inspect --format '{{json .Config.OnBuild}}' <image>.
ONBUILD ONBUILD is not allowed.ONBUILD FROM and ONBUILD MAINTAINER are not allowed.FROM line, which is confusing to debug.Official images used to ship -onbuild variants (node:onbuild, python:onbuild). Docker deprecated and stopped publishing them years ago, for good reasons:
FROM and cannot tell that files are being copied and commands run.ONBUILD COPY . . runs before the child can copy just package.json first, so every code change busts the dependency cache.ONBUILD is Docker-specific metadata; some non-Docker builders or OCI-format builds may drop it.ONBUILD still has a niche: internal platform teams that want every service built on their base to, say, copy a mandatory CA certificate bundle or run a compliance scan step. If you use it, document it loudly in the base image README.
# ---- base/Dockerfile ----
FROM node:22-alpine
WORKDIR /app
ONBUILD COPY package*.json ./
ONBUILD RUN npm ci --omit=dev
ONBUILD COPY . .
CMD ["node", "server.js"]
# docker build -t acme/node-base:1.0 base/
# -> the three ONBUILD lines do not run here
# ---- orders-service/Dockerfile ----
FROM acme/node-base:1.0
# Triggers run now: copy package files, npm ci, copy source
EXPOSE 3000
The child Dockerfile is two lines, but three hidden steps run during its build, which is both the convenience and the problem of ONBUILD.
docker inspect acme/node-base:1.0 --format '{{json .Config.OnBuild}}'
Always check this before using an unfamiliar base image so its triggers do not surprise you.
ONBUILD, Build Triggers, Base Images, Dockerfile Inheritance