DEV Community

jguo
jguo

Posted on

Build a template Dockerfile with ONBUILD

Why?

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.

How

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
Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode

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.

Note

ONBUILD instruction is not inherited by “grand-children” builds.

Reference

https://docs.docker.com/engine/reference/builder/#onbuild

Top comments (0)