Docker · Containers in practice
How do you write a Dockerfile?
Short answer
A Dockerfile is a sequence of instructions that builds an image layer by layer. FROM sets the base, then COPY and RUN prepare the filesystem, and CMD or ENTRYPOINT define the process.
Docker executes instructions in order. FROM selects the base image, WORKDIR sets the working directory, COPY adds files from the build context, RUN executes a command during the build, and CMD or ENTRYPOINT define what runs when the container starts.
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
USER node
EXPOSE 3000
CMD ["node", "server.js"]Instructions worth knowing
- ARG is available during the build, ENV is present at runtime
- COPY has clearer semantics than ADD; avoid ADD unless you need archive extraction
- EXPOSE documents the port but does not publish it
- HEALTHCHECK tells the runtime how to test whether the process is usable
- LABEL adds metadata such as source revision or maintainer
Use the exec form for ENTRYPOINT and CMD, as in the example, so the process receives signals directly instead of running through a shell. Avoid installing build tools in the final stage; a multi-stage build keeps them out of the shipped image.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between RUN, CMD and ENTRYPOINT?
- 2Why prefer the exec form over the shell form?
- 3What does EXPOSE actually do?
- 4How would you keep build tooling out of the final image?
Say it in the interview
A Dockerfile is an ordered recipe for building an image. I start from a pinned base, set a working directory, copy dependency manifests first, install dependencies, then copy the source and define the start command. I use the exec form so signals reach the process, and I keep build tools out of the runtime image by using multiple stages.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.