Master Dockerfile: Essential Commands and Best Practices Explained
This article provides a comprehensive guide to Dockerfile syntax, covering variables, FROM, RUN, CMD, LABEL, EXPOSE, ENV, ADD, COPY, ENTRYPOINT, VOLUME, ARG, ONBUILD, STOPSIGNAL, HEALTHCHECK, SHELL, and WORKDIR instructions, with examples and usage tips for building efficient Docker images.
Variables
Variables are referenced as $variable_name or ${variable_name}. ${variable:-word} expands to the variable's value if set, otherwise to word. ${variable:+word} expands to word only when the variable is set. Escape with \$foo or \${foo}.
FROM
Initializes a new build stage and sets the base image. Syntax examples:
FROM [--platform=<platform>] <image> [AS <name>]
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM [--platform=<platform>] <image>[@<digest>] [AS <name>]Multiple FROM statements allow multi‑stage builds. AS name names a stage for later COPY --from=<name>. The tag or digest is optional; if omitted Docker uses latest. The --platform flag selects the target architecture (e.g., linux/amd64, linux/arm64, windows/amd64).
RUN
Executes a command in a new layer during docker build. Two forms: RUN <command> – shell form (default /bin/sh -c on Linux, cmd /S /C on Windows). RUN ["executable","param1","param2"] – exec form.
Use backslash \ to split a RUN command across lines. Add --no-cache to invalidate the cache. Combine commands with && to reduce the number of layers.
CMD
Specifies the default command to run when the container starts (different from RUN, which runs at build time). Three formats: CMD ["executable","param1","param2"] – exec form (recommended). CMD command param1 param2 – shell form. CMD ["param1","param2"] – default parameters for ENTRYPOINT.
Only one CMD is allowed; the last one wins. It can be overridden by arguments passed to docker run.
LABEL
Adds metadata to the image, e.g.:
LABEL multi.label1="value1" \
multi.label2="value2" \
other="value3"EXPOSE
Informs Docker 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 the port; use docker run -P to publish.
ENV
Sets environment variables that persist in the image and can be inspected with docker inspect. Example: ENV KEY=value ... For build‑time only variables, use ARG instead.
ADD
Copies files, directories, or remote URLs into the image. Supports wildcards and can unpack local tar archives. Example:
ADD hom* /mydir/
ADD hom?.txt /mydir/COPY
Similar to ADD but only copies from the build context and does not support remote URLs or automatic tar extraction. Prefer COPY for simple file copies.
ENTRYPOINT
Defines the container’s entry point. Two forms:
ENTRYPOINT ["executable","param1","param2"]
ENTRYPOINT command param1 param2If both ENTRYPOINT and CMD are set, the CMD arguments are passed to the ENTRYPOINT.
VOLUME
Creates a mount point with a specified name, useful for persisting data and preventing container bloat.
VOLUME ["/var/log/"]
VOLUME /var/logARG
Defines a build‑time variable that does not persist in the final image. Example: ARG name[=default value] Common predefined ARGs include HTTP_PROXY, HTTPS_PROXY, FTP_PROXY, NO_PROXY, etc., which can be passed with --build-arg.
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/srcSTOPSIGNAL
Specifies the signal sent to the container on docker stop. Default is SIGTERM; can be changed with --stop-signal to allow graceful shutdown.
HEALTHCHECK
Defines a command to monitor container health. Two forms:
HEALTHCHECK [OPTIONS] CMD command HEALTHCHECK NONESHELL
Overrides the default shell used for RUN commands. Default on Linux is ["/bin/sh","-c"], on Windows ["cmd","/S","/C"]. Can be set multiple times; each overrides the previous.
SHELL ["executable","parameters"]WORKDIR
Sets the working directory for subsequent instructions. It is created if it does not exist. Multiple WORKDIR commands can be chained, and they can reference previously defined ENV variables.
WORKDIR /a
WORKDIR b
WORKDIR c
RUN pwd # outputs /a/b/c
ENV DIRPATH=/path
WORKDIR $DIRPATH/$DIRNAME
RUN pwd # outputs /path/$DIRNAMEUSER
Specifies the user (or UID) and optional 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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
