Master Dockerfile: Essential Commands and Best Practices Explained
This guide walks through every Dockerfile instruction—from variables and FROM to ENTRYPOINT and HEALTHCHECK—explaining syntax, usage tips, and common pitfalls, so you can build efficient, reproducible container images with confidence.
Docker builds images automatically by reading instructions in a Dockerfile, which is a plain‑text document containing all commands and metadata required to create an image.
1. Variables
Variables are referenced as $variable_name or ${variable_name}. Examples: ${variable:-word} expands to the variable's value if set; otherwise to word. ${variable:+word} expands to word only if the variable is set; otherwise to an empty string.
Escape a variable with a backslash to treat it as a literal string, e.g., \$foo or \${foo}.
2. FROM
Initializes a new build stage and sets the base image:
FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]A Dockerfile can contain multiple FROM lines to create multi‑stage builds. AS name names a stage for later reference with COPY --from=<name>. digest is a content‑addressable ID; it changes only when the image content changes.
If tag or digest is omitted, Docker uses the latest tag by default.
The --platform flag selects a specific architecture (e.g., linux/amd64, linux/arm64, windows/amd64).
3. RUN
Executes a command in a new layer during docker build:
RUN /bin/bash -c 'source $HOME/.bashrc; \
echo $HOME'Two forms are supported: RUN <command> – shell form (default shell is /bin/sh -c on Linux or cmd /S /C on Windows). RUN ["executable", "param1", "param2"] – exec form.
Use a backslash ( \) to split a long RUN across lines.
Cache is reused unless --no-cache is specified.
Combine commands with && to create a single image layer and avoid image bloat.
4. CMD
Specifies the default command that runs when a container starts (different from RUN, which runs at build time). Only one CMD is allowed; the last one wins.
FROM ubuntu
CMD ["/usr/bin/wc", "--help"]Three formats are supported: CMD ["executable","param1","param2"] – exec form (recommended). CMD command param1 param2 – shell form, useful for interactive programs. CMD ["param1","param2"] – provides default arguments to an ENTRYPOINT.
If the user supplies a command at docker run, it overrides the CMD value.
5. LABEL
Adds metadata to the image:
LABEL multi.label1="value1" \
multi.label2="value2" \
other="value3"6. EXPOSE
Informs Docker that the container listens on the specified network ports. It does not publish the ports; docker run -P must be used for that.
EXPOSE <port> [<port>/<protocol>...]
EXPOSE 80/udpDefault protocol is TCP; UDP can be specified explicitly.
7. ENV
Sets environment variables that persist in the final image and are visible with docker inspect. They can be overridden at runtime with docker run --env KEY=VALUE.
ENV KEY=value ...For build‑time‑only values, use ARG instead.
8. ADD
Copies files, directories, or remote URLs ( <src>) into the image at <dest>. Supports wildcards and automatically extracts local tar archives.
ADD hom* /mydir/
ADD hom?.txt /mydir/9. COPY
Same syntax as ADD but only copies from the build context; it does not fetch remote URLs or extract archives. Prefer COPY when remote fetching is not needed.
10. ENTRYPOINT
Defines the container’s main executable. Unlike CMD, it is not overridden by arguments passed to docker run unless --entrypoint is used.
ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2If both ENTRYPOINT and CMD are present, the CMD arguments are appended to the ENTRYPOINT command.
11. VOLUME
Creates a named mount point to persist data outside the container’s writable layer, preventing data loss on container restart and avoiding image growth.
VOLUME ["/var/log/"]
VOLUME /var/log12. ARG
Defines a build‑time variable that does not persist in the final image. It can have a default value.
ARG name[=default_value]Docker provides several predefined build arguments (e.g., HTTP_PROXY, HTTPS_PROXY, NO_PROXY) that can be set with --build-arg:
docker build --build-arg HTTPS_PROXY=https://my-proxy.example.com .13. ONBUILD
Adds a trigger instruction to the image that runs when the image is used as a base for another build.
ONBUILD ADD . /app/src
ONBUILD RUN /usr/local/bin/python-build --dir /app/src14. STOPSIGNAL
Specifies the signal sent to the container on docker stop. The default is SIGTERM. Custom signals enable graceful shutdown logic.
STOPSIGNAL signal15. HEALTHCHECK
Defines a command that Docker runs periodically to assess container health. Two forms:
HEALTHCHECK [OPTIONS] CMD command HEALTHCHECK NONE– disables inherited health checks.
16. SHELL
Overrides the default shell used for subsequent commands. Linux default is ["/bin/sh", "-c"]; Windows default is ["cmd", "/S", "/C"]. Multiple SHELL instructions are allowed; each replaces the previous one.
SHELL ["executable", "parameters"]17. WORKDIR
Sets the working directory for any following instructions. If the directory does not exist, it is created.
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd # outputs /a/b/c
ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME # resolves to /path/$DIRNAME
RUN pwd18. USER
Specifies the user (or UID) and optionally the group (or GID) under which the container runs.
USER <user>[:<group>]
USER <UID>[:<GID>]Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
