0
0
DockerConceptBeginner · 4 min read

What is ONBUILD in Dockerfile: Explanation and Usage

The ONBUILD instruction in a Dockerfile sets up a trigger that runs specified commands when the image is used as a base for another build. It helps automate steps in child images by deferring commands until the next build stage.
⚙️

How It Works

The ONBUILD instruction acts like a reminder or a trigger inside a Docker image. When you build an image with ONBUILD commands, those commands do not run immediately. Instead, they wait until someone uses that image as a base for a new Dockerfile.

Think of it like preparing a cake mix that includes instructions for the next baker. The mix itself doesn't bake the cake, but when the next baker uses it, the instructions automatically run to finish the cake. Similarly, ONBUILD commands run only during the child image build, not the original image build.

💻

Example

This example shows a base image Dockerfile that uses ONBUILD to copy files and run a command when used later.

dockerfile
FROM alpine:3.18
ONBUILD COPY . /app
ONBUILD RUN echo "Files copied to /app in child image"
💻

Example (Child Image Build Output)

When you build a child image using the above base image, the ONBUILD commands run automatically:

dockerfile
FROM your-base-image
RUN ls /app
Output
/app file1.txt file2.txt
🎯

When to Use

Use ONBUILD when you create base images meant to be extended by others. It helps automate common setup steps for child images, like copying source code or running setup scripts.

For example, if you build a language runtime image, you can use ONBUILD to copy the application code and install dependencies automatically when someone builds their app image on top.

This saves time and keeps child Dockerfiles simpler by moving repetitive tasks into the base image.

Key Points

  • ONBUILD defers commands to child image builds.
  • It triggers only when the image is used as a base.
  • Useful for base images that require common setup steps.
  • Helps keep child Dockerfiles clean and simple.
  • Be cautious: unexpected triggers can cause build surprises.

Key Takeaways

ONBUILD sets commands to run only in child image builds.
It automates common setup steps for images built on top of a base image.
Use it to simplify Dockerfiles that extend your base image.
Triggers run during the next build, not the original image build.
Be careful to document ONBUILD triggers to avoid surprises.