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: a heredoc in a Dockerfile RUN replaces long lines joined with &&

Docker
~/tips/tip-dockerfile-heredoc-run

RUN <<EOF

Write multi-line shell steps in a Dockerfile without backslashes and ampersands.

Dockerfiles are full of RUN lines that chain ten commands with && \, where one missing backslash breaks the build. Heredocs let you write the commands as a small script.

# syntax=docker/dockerfile:1
FROM debian:stable-slim
RUN <<EOF
set -e
apt-get update
apt-get install -y --no-install-recommends curl ca-certificates
rm -rf /var/lib/apt/lists/*
EOF

Everything between <<EOF and EOF runs as one step and makes one layer, like the chained version. It reads like a shell script, and adding a line is just adding a line.

The set -e matters. With && a failing command stops the chain; in a heredoc the shell carries on after an error unless you tell it not to, and only the last command’s exit code counts. Without it, a failed apt-get update can leave you with a build that succeeds but lacks packages.

The same syntax works for COPY to write a small file inline, which I find handy for a short config.

Heredocs need BuildKit and a recent Dockerfile frontend, which is why the # syntax line is there. The classic builder rejects them. Variables like $HOME inside the heredoc are expanded by the shell at build time, unless you quote the marker as <<"EOF".

Further reading: Dockerfile reference: here-documents

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link