Card 02/ 06
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.
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]| Instruction | What it adds |
|---|---|
FROM | The filesystem to start from. Every image starts from another one |
WORKDIR | The directory the instructions after it run in, created if missing |
COPY | Files from the build context into the image |
RUN | A command executed during the build, keeping whatever it changed |
CMD | The 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.
← → move through sections and cards