“ONBUILD” — Dockerfile command

Bhargav Shah
3 min readJun 2, 2019

--

Dockerfile instruction — ONBUILD

Why use “ONBUILD”?

For example, if your image is reusable application boilerplate or you have customized as per your need application environment image. Which you want to share across application development teams.

Now, One way to do this is to share a Dockerfile with your application development teams and they will include it in their application. But, as you may have already realized that this is prone to error and difficult to maintain and update, As application specific details are mixed in with the boilerplate Dockerfile.

In this situation we can use “ONBUILD” instruction in our dockerfile.

How “ONBUILD” works?

The ONBUILD instruction adds to the image a trigger instruction to be executed at a later time when the image is used as the base for another build. The trigger will be executed in the context of the downstream build as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.

When ONBUILD instruction is encountered in Dockerfile, instruction is added to run later. We can inspect commands in image manifest file under OnBuild key. All the command registered in OnBuild will be executed in the sequence they appeared in Dockerfile.

TIP: Chaining ONBUILDinstructions using ONBUILD ONBUILDisn’t allowed. The ONBUILDinstruction may not trigger FROMor MAINTAINERinstructions.

Let’s see in Action:

First, create our boilerplate Dockerfile

Then create image from it and inspect built image

$ docker build -t demo-app:latest .

$ docker run -d — name app -p 8001:80 demo-app:latest

As you can see, “index.html” is not copied in base image.

Inspect OnBuild Key

Now, Lets new build using the above base image and inspect it.

$ docker container stop app

$ docker build -t demo-app:v1.0 .

$ docker container run -d — name nginx-app -p 8002:80 demo-app:v1.0

Here we go, our latest index.html file is copied in a new build. Thus, we have successfully implemented ONBUILD command.

Thank You for reading.

--

--

Bhargav Shah
Bhargav Shah

Written by Bhargav Shah

Cloud Solution Architect at Walmart Japan

No responses yet