Dockerfile Instructions Explained
Overview
Each Dockerfile instruction changes the image being built or documents how a container should start. Some instructions create filesystem layers, some change image metadata and some only provide build-time or runtime defaults.
Detailed Notes
Instructions that create image layers
FROM chooses a base image:
FROM node:22-alpine
The first instruction is usually FROM. It imports a known filesystem and configuration into the new image. If the local base image is missing, Docker pulls it during build.
RUN executes a command and saves the resulting filesystem changes:
RUN npm ci --omit=dev
Docker runs this command in a temporary build environment. npm ci reads package-lock.json and installs dependencies. The resulting node_modules directory becomes part of an image layer.
COPY copies files from the build context:
COPY package*.json ./
The source is outside the container on the build machine. The destination is inside the image. COPY does not continuously synchronize files after the build.
COPY versus ADD
Prefer COPY for ordinary files. ADD has extra behaviors:
- it can download a remote URL;
- it automatically extracts recognized local archives.
Those extra behaviors are surprising and make builds harder to reproduce, so COPY is normally preferred.
Metadata and startup instructions
ENV sets a runtime default:
ENV NODE_ENV=production
ARG accepts a build-time value:
ARG APP_VERSION=unknown
ARG values are available during build but are not a secret mechanism.
EXPOSE documents listening ports:
EXPOSE 3000
It does not publish port 3000. Publishing still requires -p 3000:3000 or Compose ports.
WORKDIR changes the working directory:
WORKDIR /app
Later COPY, RUN and CMD instructions use /app unless they specify another path.
USER chooses the process account:
USER node
The named user must exist in the image. A common Node image provides node; other images may provide app or nobody.
CMD versus ENTRYPOINT
CMD supplies the default command:
CMD ["node", "server.js"]
Supplying docker run image node other.js replaces the CMD.
ENTRYPOINT fixes the executable:
ENTRYPOINT ["node"]
CMD ["server.js"]
Running docker run image other.js produces node other.js. This pattern is useful for tools where arguments vary but the executable stays constant.
Common Interview Questions
Finished this lesson?
0 of 27 lessons done · 0% of the course

