Cloud Native 12 min read

Master Dockerfile: Complete Guide to All Instructions and Best Practices

This article provides a comprehensive, step‑by‑step explanation of every Dockerfile instruction—including variables, FROM, RUN, CMD, LABEL, EXPOSE, ENV, ARG, ADD, COPY, ENTRYPOINT, VOLUME, STOPSIGNAL, HEALTHCHECK, SHELL, WORKDIR, and USER—along with syntax details, usage tips, and practical code examples for building efficient container images.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Dockerfile: Complete Guide to All Instructions and Best Practices

Variable syntax

Variables are referenced as $variable_name or ${variable_name}. The forms ${variable:-word} use word when the variable is unset, while ${variable:+word} expands to word only if the variable is set. Escape a variable with a backslash (e.g., \$foo or \${foo}) to treat it as a literal string.

FROM instruction

Initializes a new build stage and sets the base image. Syntax examples:

FROM [--platform=<platform>] <image> [AS <name>]

Multiple FROM lines can appear to create multi‑stage builds. The optional AS <name> names a stage for later COPY --from=<name> references. Tags or digests are optional; if omitted, latest is used, and a missing tag causes a build error. The --platform flag selects the target architecture (e.g., linux/amd64, linux/arm64).

RUN instruction

Executes a command in a new layer during docker build. Two forms exist:

Shell form: RUN <command> runs via /bin/sh -c (Linux) or cmd /S /C (Windows).

Exec form: RUN ["executable", "param1", "param2"].

Use a backslash ( \) to continue a RUN line. By default, RUN layers are cached; --no-cache disables caching. Combine commands with && to create a single layer and avoid image bloat.

CMD instruction

Specifies the default command to run when the container starts (executed at docker run time). Three formats are supported:

Exec form: CMD ["executable","param1","param2"] (recommended).

Shell form: CMD command param1 param2 (runs in /bin/sh).

Parameter form: CMD ["param1","param2"] provides default arguments to an ENTRYPOINT.

Only one CMD is allowed; later ones overwrite earlier ones. If the user supplies a command in docker run, it overrides CMD.

LABEL instruction

Adds metadata to the image, e.g.:

LABEL multi.label1="value1" \
      multi.label2="value2" \
      other="value3"

EXPOSE instruction

Declares that the container listens on the specified network ports. Default protocol is TCP; UDP can be specified (e.g., EXPOSE 80/udp). EXPOSE does not publish ports; use docker run -P to publish them.

ENV instruction

Sets persistent environment variables inside the image. They can be inspected with docker inspect and overridden at runtime with docker run --env KEY=VALUE. For build‑time only variables, consider using ARG instead.

ENV <key>=<value> ...

ARG instruction

Defines build‑time arguments that are not persisted in the final image. Syntax: ARG <name>[=<default value>] Common predefined proxy variables include HTTP_PROXY, HTTPS_PROXY, FTP_PROXY, and NO_PROXY. Pass them with

docker build --build-arg HTTPS_PROXY=https://my-proxy.example.com .

ADD instruction

Copies files, directories, or remote URLs into the image. Supports wildcards using Go’s filepath.Match rules. Example: ADD hom* /mydir/ Remote URLs are allowed, and tar archives are automatically extracted.

COPY instruction

Similar to ADD but only copies from the build context and does not support remote URLs. Recommended for most use‑cases; ADD is better for extracting local tar files.

ENTRYPOINT instruction

Defines the container’s entry point. Two formats:

ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2

If both ENTRYPOINT and CMD are present, the CMD arguments are passed to the ENTRYPOINT. The entry point can be overridden with docker run --entrypoint.

VOLUME instruction

Creates a mount point with an optional name, e.g.:

VOLUME ["/var/log/"]
VOLUME /var/log

Benefits include persisting data across container restarts and preventing the container’s writable layer from growing indefinitely.

STOPSIGNAL instruction

Sets the signal sent to the container on stop. Accepts numeric signals (e.g., 9) or names (e.g., SIGKILL). The default is SIGTERM, which Docker sends during docker stop. Use --stop-signal to customize graceful shutdown behavior.

STOPSIGNAL signal

HEALTHCHECK instruction

Specifies a command to monitor container health. Two forms: HEALTHCHECK [OPTIONS] CMD command – runs the command inside the container. HEALTHCHECK NONE – disables inherited health checks.

SHELL instruction

Overrides the default shell used for shell‑form commands. Default shells are ["/bin/sh", "-c"] on Linux and ["cmd", "/S", "/C"] on Windows. Syntax: SHELL ["executable", "parameters"] Multiple SHELL lines can appear; each replaces the previous one.

WORKDIR instruction

Sets the working directory for subsequent instructions. If the directory does not exist, it is created. Multiple WORKDIR lines can be chained, and relative paths are resolved against the previous WORKDIR:

WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd   # outputs /a/b/c

Environment variables can be used in WORKDIR:

ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd   # outputs /path/$DIRNAME

USER instruction

Specifies the user (or UID) and optionally the group (or GID) under which the container runs:

USER <user>[:<group>]
USER <UID>[:<GID>]
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Dockercloud-nativeOperationsContainerDockerfileImage Build
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.