Browse topics

Building an image

Version
29
Review
Draft

Summary#

docker build creates an image from a Dockerfile and a build context, usually a directory. COPY reads from that context. A .dockerignore file at its root excludes paths, and --build-arg sets a value declared with ARG.

Syntax#

sh
docker build --tag NAME:TAG .
docker build --file path/to/Dockerfile --build-arg KEY=VALUE --tag NAME:TAG CONTEXT
docker build --no-cache --pull --tag NAME:TAG .

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-build:$$"
  name="dlr-docker-commands-build-$$"
  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 '*.log\n' > "$dir/.dockerignore"
  printf 'app source\n' > "$dir/app.txt"
  printf 'local noise\n' > "$dir/debug.log"
  cat > "$dir/Dockerfile" <<'EOF'
FROM alpine:3
ARG GREETING=hello
WORKDIR /app
COPY . .
RUN echo "$GREETING" > greeting.txt
CMD ["sh", "-c", "cat greeting.txt; ls"]
EOF

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

Expected output#

Text
hi
Dockerfile
app.txt
greeting.txt

Common mistakes#

Do not pass passwords or tokens with --build-arg. The values can show up in image history and provenance data. Use a build secret with --secret and RUN --mount=type=secret.

Version applicability#

Checked with Docker Engine 29 and the docker BuildKit driver, which loads the image into the local store. If your driver leaves the result in cache, use --load for local use or --push to send it to a registry.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0