Browse topics

Dockerfile instructions

Version
29
Review
Draft

Summary#

A Dockerfile lists the steps and defaults for an image. FROM selects the base, RUN executes during the build, and COPY adds files. With an exec-form ENTRYPOINT, CMD supplies default arguments that docker run can replace.

Syntax#

dockerfile
FROM IMAGE
WORKDIR /path
COPY --chmod=0644 source destination
RUN command
ENV KEY=value
USER name
ENTRYPOINT ["program", "fixed-argument"]
CMD ["default-argument"]

Example#

Use a disposable Docker daemon for this example. Discard its storage afterward to clear the build cache.

sh
(
  set -eu
  tag="dlr-docker-commands-dockerfile:$$"
  name="dlr-docker-commands-dockerfile-$$"
  dir=$(mktemp -d)
  trap 'docker rm -f "$name" >/dev/null 2>&1 || true; docker image rm "$tag" >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT

  printf 'echo "$GREETING, $1 (user: $(id -un))"\n' > "$dir/greet.sh"
  cat > "$dir/Dockerfile" <<'EOF'
FROM alpine:3
WORKDIR /app
COPY --chmod=0644 greet.sh .
RUN adduser -D app
ENV GREETING=Hello
USER app
ENTRYPOINT ["sh", "/app/greet.sh"]
CMD ["world"]
EOF

  docker build --quiet --label "dlr-docker-commands-dockerfile=$$" \
    --tag "$tag" "$dir" >/dev/null
  docker run --pull never --rm --name "$name" "$tag"
  docker run --pull never --rm --name "$name" "$tag" Docker
  docker run --pull never --rm --name "$name" --env GREETING=Hi "$tag"
)

Expected output#

Text
Hello, world (user: app)
Hello, Docker (user: app)
Hi, world (user: app)

Common mistakes#

A shell-form ENTRYPOINT program runs through /bin/sh -c, ignores CMD and the arguments given to docker run, and can leave the shell as the main process unless you write exec program. Prefer the JSON array form.

Version applicability#

Checked with Docker Engine 29. COPY --chmod is not supported when building Windows containers. Setting ENTRYPOINT resets a CMD inherited from the base image, so declare CMD again if you need default arguments.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0