Dockerfile and Heredocs

I recently did a quick research on how to better write down multiline statements like this:

# Dockerfile
RUN export DEBIAN_FRONTEND=noninteractive \
  && apt-get update \
  && apt-get dist-upgrade -y \
  && apt-get install --no-install-recommends --no-install-suggests -y \
    ca-certificates \
    curl \
    unzip

It turns out, there is! Buildkit, the tool behind docker build added support for heredoc strings in May 2021 Show archive.org snapshot .
Now we could refactor the code above like this:

# Dockerfile
RUN <<-EOF
  export DEBIAN_FRONTEND=noninteractive
  apt-get update
  apt-get dist-upgrade -y
  apt-get install --no-install-recommends --no-install-suggests -y \
    ca-certificates \
    curl \
    unzip
EOF

Nested multiline commands still require trailing backslashes to work properly.

Note

I needed to install the Buildkit plugin buildx Show archive.org snapshot to get the desired result. If you add heredocs to your Dockerfile, you might break compatiblity with older clients!

Current Verdict

Not recommended for internal use. It's not very clear if each line statement is chained with && or executed no matter if the previous statement fails or not.

Michael Leimstädtner 4 months ago