What is ONBUILD in Dockerfile: Explanation and Usage
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.
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:
FROM your-base-image RUN ls /app
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.ONBUILD triggers to avoid surprises.