ONBUILD: Triggered Instructions
You'll learn: How to create base images that automatically execute instructions when used by downstream images, perfect for standardized build patterns.
What is ONBUILD?
ONBUILD is a special Dockerfile instruction that plants "time-delayed" commands into an image. These commands don't execute when you build the image—they trigger automatically when someone else uses your image as their base (via FROM).
Think of it like leaving a note for the next person: "When you use this kitchen (base image), please preheat the oven to 350°F before cooking." The preheating doesn't happen when you set up the kitchen, but automatically when the next chef arrives.
Why Use ONBUILD?
Perfect for creating base images for teams or projects with consistent patterns:
- A Node.js base that automatically copies
package.jsonand runsnpm install - A Python base that sets up a virtual environment and installs dependencies
- A build toolchain that enforces directory structure
Basic Syntax
FROM ubuntu:22.04
ONBUILD COPY . /app
ONBUILD WORKDIR /app
ONBUILD RUN make build
When another Dockerfile uses FROM your-base-image, those three instructions execute before any of their own instructions run.
How It Works
- Parent image build:
ONBUILDinstructions are registered but not executed - Child image build: Child specifies
FROM your-base-image - Automatic trigger: All
ONBUILDinstructions execute immediately afterFROM - Child instructions continue: Child's own instructions then proceed normally
Limitations
- Cannot chain
ONBUILD ONBUILD(prevented to avoid complexity) - Only triggers one level deep (grandchildren don't inherit)
- Not compatible with
FROMorMAINTAINER
Key Takeaway: ONBUILD lets you build "smart" base images that automatically prepare downstream builds with deferred instructions, perfect for enforcing team-wide build standards without manual steps.