Course contentsShow
← Cloud and Infrastructure
Lesson 1014 of 2,98920. Docker in DepthFree lesson

ONBUILD: Triggered Instructions

Master ONBUILD instruction for creating base images with deferred instructions for downstream builds.

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.json and runs npm 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

  1. Parent image build: ONBUILD instructions are registered but not executed
  2. Child image build: Child specifies FROM your-base-image
  3. Automatic trigger: All ONBUILD instructions execute immediately after FROM
  4. 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 FROM or MAINTAINER

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.