Docker Parser Directives
→ 日本語版を読むParser directive
Parser directives are special comments written at the top of a Dockerfile that affect how subsequent lines in the Dockerfile are processed.
There are two types of parser directives: syntax and escape.
syntax
In fact, the syntax used inside a Dockerfile is interchangeable, and syntax allows you to specify how the syntax is processed. For example, by writing # syntax=docker/dockerfile:1 at the top line as shown below, you can use heredocs inside the Dockerfile.
# syntax=docker/dockerfile:1
FROM golang:1.21 as build
WORKDIR /src
COPY <<-EOF /src/main.go
package main
import "fmt"
func main() {
fmt.Println("hello, world")
}
EOF
RUN go build -o /bin/hello ./main.go
The docker/dockerfile image allows you to build images using BuildKit. BuildKit is a daemon for building containers.
BuildKit is a toolkit for building containers, consisting of a daemon called
buildkitdand thebuildctlcommand. Compared to Docker's standard build, building with BuildKit offers the following advantages:
- Parallel builds of each stage in a multi-stage Dockerfile
- Build cache can be externally stored/reused on Docker Hub, etc.
- Fetch remote files via SSH connection
- Mount files such as private keys so they are not left inside the image
Additionally, some BuildKit features have been integrated into Docker Engine 18.06 and later, allowing some BuildKit features to be used with Docker alone.
syntax is also called the Dockerfile Frontend. By specifying an external Dockerfile frontend (the dockerfile Docker image) via syntax, you can change how the syntax is processed. You can use the latest Dockerfile frontend without upgrading BuildKit or Docker Engine.
BuildKit detects unused build stages and skips them. For example, with the following Dockerfile, the final image will be stage2. stage2 is built from the base stage, while stage1 is an unused stage. BuildKit will only process base and stage2, skipping stage1 which has no dependency. In contrast, the legacy builder processes all stages including stage1.
# syntax=docker/dockerfile:1
FROM ubuntu AS base
RUN echo "base"
FROM base AS stage1
RUN echo "stage1"
FROM base AS stage2
RUN echo "stage2"
escape
escape is a parser directive used to specify the escape character. The default escape character is the backslash \, and this directive is used when you want to change it, though there are not many use cases.
# escape=\