Walk through writing a Dockerfile from scratch.
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Pick a base with FROM, set WORKDIR, COPY dependency manifests first, RUN the install, COPY the rest of the source, then set EXPOSE/ENV/USER and a default CMD. Order matters: dependencies before source so code edits do not bust the install cache.
Detailed explanation
A Dockerfile is a text document the builder executes top to bottom. The canonical Node example from the docs builds in five lines: FROM node:22-alpine (extend a small base), WORKDIR /app (where later COPY/RUN/CMD execute), COPY . . (bring in project files), RUN yarn install --production (bake dependencies into a layer), CMD ["node", "./src/index.js"] (default process). The eight instructions to know cold: FROM (base), WORKDIR (working dir), COPY host→image, RUN (execute and commit a layer), ENV (runtime variables), EXPOSE (documents the intended port — does not publish it), USER (drop from root for security), CMD in exec form (default command, only the last one counts). The exercise has you delete the sample app's Dockerfile and recreate it by hand — remember it has no file extension. The first version works but is deliberately not production-ready: it copies everything before installing (busting cache) and runs as root; cache ordering and non-root USER come next.
Official docs:Docker docs: Writing a Dockerfile
Example
FROM node:22-alpine
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "./src/index.js"]
# Production-leaning shape (deps first, non-root):
# COPY package.json yarn.lock ./
# RUN yarn install --production
# COPY . .
# RUN useradd app
# USER appInterview tip
Narrate a Dockerfile as four phases — base → deps → source → runtime config — then name EXPOSE-does-not-publish and only-last-CMD-counts as the two gotchas.
Common mistakes
- Thinking EXPOSE publishes the port (it only documents it; -p publishes).
- Using shell-form CMD without knowing exec form, or defining multiple CMDs.