Card 02/ 06

CodeDifficulty: Beginner1 min

Dockerfile Instructions: FROM, WORKDIR, COPY, RUN and CMD

Six lines that cover most Dockerfiles, and the one pair everyone confuses.

Most Dockerfiles use five instructions: FROM, WORKDIR, COPY, RUN and CMD. The listing is a complete Dockerfile, the recipe docker build follows to make an image (the packaged program and files a container runs from), for a small Node.js web application (Node.js runs JavaScript outside a browser, and npm installs its packages), and every line uses one of the five.

Dockerfiletext
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]
What each instruction contributes
InstructionWhat it adds
FROMThe filesystem to start from. Every image starts from another one
WORKDIRThe directory the instructions after it run in, created if missing
COPYFiles from the build context into the image
RUNA command executed during the build, keeping whatever it changed
CMDThe command to run when a container starts. It changes nothing at build time

The build context in the COPY row is the directory you hand to docker build, usually the project directory. COPY can only read files from inside it.

The highlighted lines decide the most: what you inherit (FROM), what you install (RUN) and what runs (CMD). RUN and CMD are the pair people confuse. RUN npm ci runs once, while the image is being built, and its result is saved in the image. CMD runs nothing at build time; it records the command every new container starts with.