brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ONBUILD in a Dockerfile runs steps when someone builds on your image

Docker
~/tips/tip-dockerfile-onbuild

ONBUILD RUN /usr/local/bin/python-build --dir /app/src

Registers a trigger that runs inside the next image build that uses yours as its base.

I like the idea of a base image that already knows what to do with the code of whoever uses it. The Dockerfile instruction for that is ONBUILD, and it is odd enough that I’d read the rules once before using it.

ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src

These two lines come from the Dockerfile reference. They do nothing while you build the base image. They only store a trigger in it. When another Dockerfile starts with FROM your base image, the triggers run as if they had been written right after that FROM line, in the order you registered them.

That is why a language base image can say “copy the project and build it” and the child Dockerfile only needs a FROM. The files are taken from the build context of the child build, not from the folder where the base image was made.

  • You cannot trigger FROM or MAINTAINER, and ONBUILD ONBUILD is not allowed.
  • Triggers are only inherited by the direct child build, not by grandchildren.
  • You can see the stored triggers with docker inspect on the base image.

The caveat is that a failing trigger aborts the FROM instruction and with it the whole build. If you share the base image with others, say in its README which files it expects in the build context. For my own images a plain explicit COPY in the child Dockerfile is usually easier to read, so I’d keep ONBUILD for base images that really have many users.

Further reading: Dockerfile reference: ONBUILD

More Docker tips SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events docker compose volumes All Docker tips (192) All topics

Link