Dockerfile Fundamentals: FROM, RUN, COPY, CMD, and ENTRYPOINT

A practical Dockerfile guide with a Node.js example: FROM, COPY vs ADD, RUN, ENV vs ARG, USER, and CMD vs ENTRYPOINT in exec form.

Executive Summary: A Dockerfile is a recipe the builder runs top to bottom: start from a base image, copy files in, run commands to install and build, then record how the container should start. A dozen instructions cover almost every real Dockerfile. The ones that cause the most confusion are CMD and ENTRYPOINT, and the detail that matters most is writing them in exec form, as a JSON array, so your application runs as PID 1 and receives the stop signal Docker sends.
Isometric Dockerfile on a glass floor with instruction lines rising into a finished container image

Most Dockerfiles in the wild are assembled from snippets: an ADD here, a CMD npm start there, an apt-get install without cleanup, and a COPY . . right at the top. They work, but every code change reinstalls all dependencies, the image is several times bigger than needed, the container takes ten seconds to stop, and the app runs as root.

A Dockerfile is a text file of instructions that docker build executes to produce an image. Each instruction either adds a filesystem layer or sets image metadata, as explained in images, containers and layers. Since Docker Engine 23.0 in February 2023, builds on Linux use BuildKit by default, which runs independent steps in parallel, skips unused stages and caches more aggressively.

A complete, sensible Dockerfile

# syntax=docker/dockerfile:1
FROM node:18-bullseye-slim

ENV NODE_ENV=production
WORKDIR /app

# Dependencies first: this layer is cached until package files change
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# Then the source code, which changes on every commit
COPY . .

USER node
EXPOSE 3000
CMD ["node", "server.js"]
docker build -t billing-api:1.0.0 .
docker run -d --name billing -p 127.0.0.1:3000:3000 billing-api:1.0.0

The final . in docker build is the build context: the directory whose files COPY can see. Everything in it is sent to the builder, which is why a .dockerignore file excluding node_modules, .git and local secrets matters; that file and build caching are covered separately.

The instructions, one by one

FROM

Every Dockerfile starts from a base image. Pin it to at least a minor version and a distribution, such as node:18-bullseye-slim or python:3.11-slim, so that a rebuild next month does not silently move you to a new major version or operating system. Pinning by digest (node:18-bullseye-slim@sha256:...) is fully reproducible, at the cost of updating the digest yourself to get security patches. The first line, # syntax=docker/dockerfile:1, tells BuildKit to use the latest stable Dockerfile syntax, which enables features such as cache mounts.

WORKDIR

Sets the working directory for the instructions that follow and for the running container, creating it if needed. Use it instead of RUN cd /app, which only affects that one RUN step.

COPY and ADD

COPY copies files from the build context into the image. ADD does the same but also auto-extracts local tar archives and can download URLs. Those extra behaviors surprise people, and downloaded files are not verified, so use COPY unless you specifically need tar extraction. Use COPY --chown=node:node when the files must be owned by a non-root user.

RUN

Executes a command at build time and commits the resulting filesystem changes as a layer. Chain related commands with && and clean up in the same step, because files removed in a later layer still ship in the image:

RUN apt-get update \
 && apt-get install -y --no-install-recommends curl ca-certificates \
 && rm -rf /var/lib/apt/lists/*

With shell-form RUN, a failing command in the middle of a pipe can go unnoticed. Starting complex scripts with set -eux makes them fail fast and print each command.

ENV and ARG

ARG ENV
Available during build Yes Yes
Available in the running container No Yes
Set from the command line --build-arg NAME=value docker run -e NAME=value overrides it
Typical use Versions to install, build flags Runtime configuration defaults

Neither is safe for secrets. Build arguments appear in the image history, and environment variables are visible in docker inspect. Build-time secrets need BuildKit secret mounts, which are covered in Docker secrets.

USER

Switches the user for later instructions and for the running container. Containers run as root by default, which means a compromised application has root inside the container and a shorter path to the host. Official images such as Node already include an unprivileged node user; for others, create one with useradd and switch to it near the end of the Dockerfile.

EXPOSE

Documents which port the application listens on. It does not publish anything; you still need -p when running the container. Treat it as metadata for humans and tools.

CMD and ENTRYPOINT

Both define what runs when the container starts. The difference is what happens when someone passes arguments to docker run:

  • CMD is the default command. Arguments after the image name replace it entirely.
  • ENTRYPOINT is the fixed executable. Arguments after the image name are appended to it, and CMD, if present, provides default arguments.
Dockerfile docker run img docker run img --verbose
CMD ["node", "server.js"] node server.js --verbose (fails: not a command)
ENTRYPOINT ["node", "server.js"] node server.js node server.js --verbose
ENTRYPOINT ["node"] + CMD ["server.js"] node server.js node --verbose

Use CMD alone for most application images, so operators can easily run a different command, such as docker run billing-api node migrate.js. Use ENTRYPOINT when the image is a wrapper around a single tool, such as a CLI image where users only pass arguments, or with a small entrypoint script that prepares the environment and then runs exec "$@" to hand over to CMD. docker run --entrypoint overrides the entrypoint when you need to.

Exec form vs shell form

CMD ["node", "server.js"]     # exec form: node is PID 1
CMD node server.js            # shell form: /bin/sh -c "node server.js" is PID 1

This is the detail that matters most in production. In shell form, the shell is PID 1 and your application is its child. When Docker stops the container, it sends SIGTERM to PID 1, the shell typically does not forward it, the application never gets a chance to finish in-flight requests, and after ten seconds Docker kills everything with SIGKILL. Deployments get slower and requests get dropped.

Use exec form for CMD and ENTRYPOINT. If you need a shell for variable expansion, end the script with exec so the application replaces the shell as PID 1. And make sure the application itself handles SIGTERM by closing its server and draining connections.

Other instructions worth knowing

  • HEALTHCHECK defines a command Docker runs periodically to decide whether the container is healthy. Compose uses it to order startup; Kubernetes ignores it in favor of its own probes.
  • LABEL adds metadata such as org.opencontainers.image.source and version, which registries and scanners display.
  • STOPSIGNAL changes the signal sent on stop, for applications that shut down on something other than SIGTERM.
  • SHELL changes the shell used by shell-form instructions, for example to bash with -o pipefail.

Frequently Asked Questions

What is the difference between CMD and ENTRYPOINT?

CMD sets the default command, and any arguments passed to docker run replace it. ENTRYPOINT sets a fixed executable, and arguments passed to docker run are appended to it, with CMD supplying default arguments. Use CMD for most application images and ENTRYPOINT for single-tool images.

Should I use COPY or ADD?

Use COPY. ADD additionally extracts local tar archives and downloads URLs, which is rarely needed and can be surprising. Use ADD only when you specifically want automatic tar extraction.

Why does my container take 10 seconds to stop?

Usually because CMD or ENTRYPOINT is in shell form, so a shell runs as PID 1 and does not forward SIGTERM to your application. Docker then waits 10 seconds and kills it. Use the exec form, a JSON array, and handle SIGTERM in the application.

What is the difference between ARG and ENV?

ARG values exist only while the image is being built and can be set with –build-arg. ENV values are stored in the image and available to the running container. Neither should hold secrets.

Write it for the next rebuild

A good Dockerfile is boring: a pinned base, dependencies before source code, cleanup inside each RUN, a non-root user and an exec-form CMD. Those few habits make builds fast, images small, stops clean and containers safer, and they set up everything that comes next, starting with multi-stage builds that keep build tools out of the final image altogether. The official documentation is worth keeping open: the Dockerfile reference and the Docker build best practices guide. Related reading on this site: multi-stage builds and base images.

Originally posted on 7 March 2023 and post last modified on 7 March 2023

Containers DevOps Docker Dockerfile

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *