使用 heredoc 語法的 Dockerfile

Simon Willison 這邊看到的,在 Dockerfile 裡面使用 heredoc 語法編 Docker image:「Introduction to heredocs in Dockerfiles」,引用的文章是「Introduction to heredocs in Dockerfiles」與「Introduction to heredocs in Dockerfiles」,七月的事情了。

heredoc 指的是可以讓開發者很方便使用多行結構,在 Dockerfile 這邊常見到的 pattern:

RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y ...

但這樣會產生出很多層 image,所以先前的 best practice 是:

RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y ...

而 heredoc 的導入簡化了不少事情,這應該有機會成為新的 best practice:

RUN <<EOF
apt-get update
apt-get upgrade -y
apt-get install -y ...
EOF

要注意的是,開頭要記得加上 #syntax 的宣告,用到 docker/dockerfile:1.3-labs 這組才能使用 heredoc:

# syntax=docker/dockerfile:1.3-labs

然後用 buildkit 去編,用新版的 Docker 已經包 buildkit v0.9.0 進去了:

DOCKER_BUILDKIT=1 docker build .

Leave a Reply

Your email address will not be published. Required fields are marked *