Master Dockerfile: Essential Commands and Best Practices for Building Efficient Images
This guide explains what a Dockerfile is, details each instruction such as FROM, LABEL, COPY, RUN, CMD, and provides best‑practice tips like using .dockerignore, multi‑stage builds, minimizing layers, and optimizing cache to create lean, maintainable container images.
Ways to Generate Images
About Dockerfile
Dockerfile is the source code for building Docker images; it is a plain‑text file.
When building an image from a Dockerfile, the file must reside in a specific directory. The filename must start with a capital “D”. Files to be packaged must be placed in the current working directory, and a .dockerignore file can be defined to exclude unwanted files. Finally, docker build creates the image.
Dockerfile Instructions
FROM
FROM is the first non‑comment line and specifies the base image for the build. Subsequent instructions run on top of this base.
The base image can be any available image; if it is not present locally, Docker pulls it from Docker Hub.
If the specified image cannot be found, docker build returns an error.
Syntax: FROM [registry/][username/]<em>image</em>[:<em>tag</em>] or FROM <em>image</em>@<em>digest</em>
MAINTAINER (deprecated)
Provides author details. Placement is not restricted, but it is recommended after the FROM line.
Syntax: MAINTAINER "Name <[email protected]>"
LABEL
Syntax:
LABEL key=value key=value ...COPY
Copies files from the build context on the host into the new image.
Syntax:
COPY <em>src</em> <em>dest</em> COPY ["src1", "src2", ...] "dest/"When paths contain spaces, the JSON array form should be used.
Copy rules:
Source must be inside the build context; parent‑directory files are not allowed.
If the source is a directory, its contents are copied recursively, but the directory itself is not.
When multiple sources are specified or a wildcard is used, the destination must be a directory ending with /.
Destination directories are created automatically if they do not exist.
# Example: view a file inside a container
docker run --name tinyweb1 --rm tinyhttpd:v0.1-1 cat /data/web/html/index.htmlADD
Similar to COPY but also supports extracting TAR archives and fetching from URLs.
Syntax:
ADD <em>src</em> <em>dest</em> ADD ["src1", "src2", ...] "dest/"When src is a URL ending without / , the file is downloaded and saved as dest . If it ends with / , the file is saved under that directory. TAR files are not automatically extracted.
WORKDIR
Sets the working directory for RUN, CMD, ENTRYPOINT, COPY and ADD instructions.
Syntax examples:
WORKDIR /var/log WORKDIR $STATEPATHWORKDIR can appear multiple times; relative paths are resolved against the previous WORKDIR.
VOLUME
Creates a mount point inside the image for host or other container volumes.
Syntax: VOLUME /data or VOLUME ["/data"]
EXPOSE
Documents which ports the container listens on.
Syntax: EXPOSE 80/tcp 443/tcp
ENV
Defines environment variables for later instructions.
Reference format: $VAR or ${VAR}
Syntax:
ENV VAR=value ENV VAR1=value1 VAR2=value2RUN
Executes a command during the image build.
Two forms:
RUN apt-get update && apt-get install -y wget RUN ["/bin/sh", "-c", "executable", "param1"]The shell form runs via /bin/sh -c , which means the process does not receive Unix signals directly.
CMD
Specifies the default command to run when a container starts from the image. It can be overridden by docker run arguments.
Only the last CMD in a Dockerfile takes effect.
Syntax examples:
CMD /bin/bash CMD ["/usr/sbin/nginx", "-g", "daemon off;"]ENTRYPOINT
Defines a fixed executable for the container; arguments supplied at docker run are appended.
Unlike CMD, the ENTRYPOINT command is not overridden unless --entrypoint is used.
Only the last ENTRYPOINT takes effect.
Syntax:
ENTRYPOINT /usr/sbin/nginx -g "daemon off;" ENTRYPOINT ["/bin/entrypoint.sh"]USER
Specifies the user (or UID) under which subsequent instructions run.
Default is root .
HEALTHCHECK
Defines a command to test container health.
Options include --interval , --timeout , --retries , and --start-period .
Example:
HEALTHCHECK --interval=5m --timeout=3s \
CMD curl -f http://localhost/ || exit 1ONBUILD
Registers a trigger instruction that runs when the image is used as a base for another build.
Cannot be nested and does not trigger FROM or MAINTAINER.
Basic Dockerfile Guidelines
Containers should be short‑lived and start quickly.
Use .dockerignore to exclude unnecessary files (syntax same as .gitignore).
Leverage multi‑stage builds to reduce final image size.
Avoid installing unnecessary packages.
One container should do one thing; split services into separate containers.
Minimize image layers; only RUN, COPY, and ADD create layers.
Sort RUN arguments on a single line for readability and cache efficiency.
Understand Docker’s build cache: each instruction is cached unless its content changes.
Dockerfile Examples
Build an SSHD Image
# Dockerfile
FROM centos:centos7
LABEL maintainer="hukey<[email protected]>"
RUN yum install -y openssh* net-tools iproute NetworkManager && \
echo "UseDNS no" >> /etc/ssh/sshd_config && \
sed -i '/pam_loginuid.so/d' /etc/pam.d/sshd && \
echo '123123' | passwd --stdin root && \
/usr/bin/ssh-keygen -A && \
yum clean all
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]Build a Systemd Image
# Dockerfile
FROM sshd:v0.1-2
LABEL maintainer="hukey<[email protected]>"
# (omitted cleanup commands for brevity)
VOLUME ["/sys/fs/cgroup"]
CMD ["/usr/sbin/init"]Build an Nginx Image
# Dockerfile
FROM centos:centos7
LABEL maintainer="hukey<[email protected]>"
ENV NGX_PACKAGE="nginx-1.18.0"
ADD http://192.168.118.45/${NGX_PACKAGE}.tar.gz /usr/local/src/
WORKDIR /usr/local/src/${NGX_PACKAGE}
RUN tar xf ${NGX_PACKAGE}.tar.gz && \
yum install -y gcc make openssl-devel && \
./configure --prefix=/usr/local/nginx --with-http_ssl_module && \
make -j2 && make install && \
echo "daemon off;" >> /usr/local/nginx/conf/nginx.conf && \
yum clean all && rm -rf /var/cache/yum/*
EXPOSE 80/tcp 443/tcp
ADD run.sh /run.sh
CMD ["/run.sh"]Build a Tomcat Image
# Dockerfile
FROM centos:centos7
LABEL maintainer="hukey<[email protected]>"
ADD jdk-8u77-linux-x64.tar.gz /usr/local/
ADD apache-tomcat-8.5.61.tar.gz /usr/local/
ENV JAVA_HOME="/usr/local/java" \
JAVA_BIN="/usr/local/java/bin" \
JRE_HOME="/usr/local/java/jre" \
PATH="$PATH:/usr/local/java/bin:/usr/local/java/jre/bin"
WORKDIR /usr/local/
RUN mv jdk1.8.0_77 java && mv apache-tomcat-8.5.61 tomcat8
EXPOSE 8080
ENTRYPOINT ["/usr/local/tomcat8/bin/catalina.sh", "run"]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.
