Industry Dockerfile usually is far more complicated than a demo, most time, we need to build our own base image. What if you want to run some common steps in a child Dockerfile? For example, all children docker images must run a setup.sh script. Here how
ONBUILD instruction can help.
Let's define a base image.
FROM openjdk:16-alpine3.13 WORKDIR /app ONBUILD COPY ./setup.sh . ONBUILD RUN ./setup.sh ONBUILD COPY src ./src
Let build the base image
docker build -t my-base-image
Now, let see how the child image looks like.
FROM my-base-image:latest WORKDIR /app CMD ["./mvnw", "spring-boot:run"]
From the example, you can see, we have a much tiny child image. More important, we have a common pattern across all children images. For example, if child image is missing
setup.sh, the build will fail.
ONBUILD instruction is not inherited by “grand-children” builds.