Skip to content

Interview PrepDocker

Dockerfile Instructions ​

46. What are the most commonly used Dockerfile instructions, and what does each do? ​

The short answer

FROM picks the base image. RUN runs a command during the build. COPY and ADD bring files in. WORKDIR sets the folder. ENV and ARG set variables. USER picks who the app runs as. EXPOSE, LABEL and HEALTHCHECK add information. CMD and ENTRYPOINT decide what runs when a container starts. The key split is that some instructions act at build time and some only record what should happen at run time.

Group the instructions by when they matter. That one idea answers half the follow-up questions.

InstructionActs atWhat it does
FROMBuildStarts a stage from a base image
RUNBuildRuns a command, saves the result as a layer
COPYBuildCopies files from the build context or a stage
ADDBuildLike COPY, plus unpacks tar files and fetches URLs
WORKDIRBuild and runSets the current folder
ARGBuildA variable that exists only during the build
ENVBuild and runA variable stored in the image
USERBuild and runWhich user later steps and the app run as
EXPOSEInfo onlyDocuments a port the app listens on
LABELInfo onlyAdds key and value metadata
HEALTHCHECKRunA command Docker runs to test health
CMDRunDefault command or arguments
ENTRYPOINTRunThe fixed program a container runs
VOLUMERunMarks a folder for a volume
STOPSIGNALRunWhich signal docker stop sends

Here they are together, in a realistic file for the shop's API:

dockerfile
# syntax=docker/dockerfile:1
# (2)
FROM node:20-slim
# (3)
LABEL org.opencontainers.image.source="https://github.com/shop/checkout-api"
# (4)
ARG APP_VERSION=dev
# (5)
ENV NODE_ENV=production APP_VERSION=${APP_VERSION}
# (6)
WORKDIR /app
# (7)
COPY package.json package-lock.json ./
# (8)
RUN npm ci --omit=dev
# (9)
COPY --chown=node:node dist/ ./dist/
# (10)
USER node
# (11)
EXPOSE 8080
# (12)
HEALTHCHECK --interval=30s --timeout=3s CMD ["node", "dist/health.js"]
# (13)
CMD ["node", "dist/server.js"]
  1. The first line is a parser directive. It tells Docker to use the newest stable Dockerfile syntax, which unlocks BuildKit features such as secret mounts. It must be the very first line, so it carries no marker. The numbered # (n) lines are ordinary comments: Docker treats # as a comment only at the start of a line, which is why the markers sit on their own lines.
  2. The base image.
  3. Records where the source code lives. Question 220 shows why labels help trace an image back to its code.
  4. A build-time variable with a default. Pass a real value with --build-arg APP_VERSION=1.4.2.
  5. Two environment variables stored in the image. The second copies the build-time value into the image so the running app can report its version.
  6. All following steps work in /app.
  7. and 8. Dependencies first, so this slow step is cached when only code changes (question 63).
  8. Copies the compiled code and sets its owner in the same step (question 468).
  9. Everything from here on, including the running app, uses the unprivileged user node.
  10. Documents the port. It does not publish it (question 58).
  11. Tells Docker how to check the app's health (question 57).
  12. What a container runs when it starts.

47. What is the purpose of FROM in a Dockerfile? ​

The short answer

FROM chooses the image your build starts from, and every later instruction adds layers on top of it. It also starts a new build stage, so a Dockerfile with several FROM lines has several stages, which is how multi-stage builds work. FROM scratch starts from a completely empty filesystem.

Every image is built on top of another image. FROM names that starting point. Everything in the base image, its files, its environment variables, its default user, becomes the starting state of your build.

dockerfile
# (1)
FROM node:20-slim AS build
# (2)
FROM gcr.io/distroless/nodejs20-debian12 AS runtime
# (3)
FROM scratch
# (4)
FROM --platform=$BUILDPLATFORM golang:1.23 AS compile
# (5)
FROM node:20-slim@sha256:9a1f...
  1. Starts a stage named build. The name lets later stages copy from it with COPY --from=build. Question 65 covers multi-stage builds.
  2. A second stage from a different base. Only the last stage becomes the final image, unless you choose another with --target.
  3. scratch is a reserved name for "nothing". The filesystem is empty: no shell, no libraries. It works for programs that carry everything inside themselves, such as many Go programs (question 70).
  4. --platform picks which processor type's version of the base image to use. $BUILDPLATFORM means "the machine doing the build", which is the trick behind fast cross-compiling (question 83).
  5. Pins the base image by digest, so the build always starts from exactly the same bytes (question 86).

Rules worth knowing:

  • FROM must be the first instruction, except for parser directives, comments, and ARG lines. An ARG before FROM can be used inside the FROM line, for example FROM node:${NODE_VERSION}-slim.
  • The base image is the biggest choice you make in a Dockerfile. It decides your image's size, which security fixes you get, and which system library your programs run against. Question 70 compares the options.

48. What is the difference between RUN, CMD, and ENTRYPOINT? ​

The short answer

RUN executes a command while the image is being built, and saves the result into a layer. CMD and ENTRYPOINT do not run anything at build time. They are written into the image's configuration and decide what runs when a container starts. ENTRYPOINT is the fixed program. CMD gives default arguments, or a default command, that docker run can easily replace.

The figure separates the two moments in an image's life.

build time: docker buildRUN npm cicommand runs now, inside the builderresult saved as a layerrun time: docker runENTRYPOINTCMDread from the image configjoined into one command:ENTRYPOINT + CMD argumentsimage
Two moments, three instructions. RUN happens once, when the image is built. ENTRYPOINT and CMD happen every time a container starts, and they only make sense together.

A restaurant comparison helps. RUN is the cooking done in the kitchen before the restaurant opens: chopping, baking, preparing. ENTRYPOINT is the restaurant itself, which does not change. CMD is the dish of the day, a sensible default that a customer can swap for something else.

dockerfile
# (1)
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates
# (2)
ENTRYPOINT ["node"]
# (3)
CMD ["dist/server.js"]
  1. Runs during docker build. The installed certificate files end up in a layer. This command never runs again when containers start.
  2. The program every container runs: node.
  3. The default argument. A container started with no extra arguments runs node dist/server.js.

With this image:

  • docker run checkout-api runs node dist/server.js.
  • docker run checkout-api dist/migrate.js runs node dist/migrate.js. The argument replaced CMD, and ENTRYPOINT stayed.

Two rules: only the last CMD and the last ENTRYPOINT in a Dockerfile count. And RUN can appear as many times as you like, each one adding a layer. Question 51 covers how CMD and ENTRYPOINT combine in every case.

49. What is the difference between shell form and exec form for CMD or ENTRYPOINT? ​

The short answer

Shell form is a plain string, such as CMD npm start, and Docker runs it through a shell: /bin/sh -c "npm start". Exec form is a JSON list, such as CMD ["node", "server.js"], and Docker starts that program directly with no shell in between. Shell form gives you shell features like $VARIABLES and &&. Exec form makes your app the main process, which is what you want for signals and clean shutdowns.

dockerfile
CMD node dist/server.js            # shell form
CMD ["node", "dist/server.js"]     # exec form

Docker stores them differently. You can see it in the image's configuration:

bash
docker inspect -f '{{json .Config.Cmd}}' api-shell
docker inspect -f '{{json .Config.Cmd}}' api-exec
["/bin/sh","-c","node dist/server.js"]
["node","dist/server.js"]

So the shell form secretly becomes "run a shell, and ask the shell to run my command".

What the shell gives you:

  • Variable expansion: CMD node server.js --port $PORT replaces $PORT with its value.
  • Chaining and pipes: CMD ./migrate && node server.js.

What the shell costs you:

  • The shell is process 1, not your app. Your app is the shell's child. Question 50 explains why that breaks shutdowns.
  • The image must contain a shell. Distroless and scratch images do not, so shell form simply fails there.

Exec form details that catch people:

  • It must be valid JSON: double quotes only. CMD ['node', 'server.js'] with single quotes is not valid JSON, so Docker silently treats the whole line as shell form.
  • It does no variable expansion. CMD ["node", "server.js", "--port", "$PORT"] passes the literal text $PORT. If you need a variable, either read it inside the app, or ask for a shell explicitly with CMD ["sh", "-c", "exec node server.js --port $PORT"]. The word exec there makes the shell replace itself with node, so node becomes process 1 after all.

For RUN, shell form is normal and fine. Build steps are short-lived and are never sent stop signals, so the shell causes no harm there.

50. Why is exec form generally preferable for a long-running application container? ​

The short answer

Because with exec form your app is process 1, so it receives the stop signal directly and can shut down cleanly. With shell form, a shell is process 1 and your app is its child. When Docker or Kubernetes sends SIGTERM, the shell gets it, and common shells do not pass it on. Your app never hears it, keeps working, and is killed by force when the timeout runs out, dropping whatever it was doing.

The figure shows where the stop signal goes in each case.

Shell formdocker stopSIGTERMPID 1: /bin/shnode, still runningsignal not passed on10 seconds later: SIGKILLrequests cut off, exit code 137Exec formdocker stopSIGTERMPID 1: nodestops taking new requestsfinishes the ones in flightcloses database connectionsexits on its own in about a secondclean shutdown, exit code 0
Who receives the stop signal. In shell form the signal stops at the shell, and the app is killed later without warning. In exec form the app itself receives the signal and can finish its work first.

Step by step, in shell form:

  1. docker stop sends SIGTERM to process 1 in the container.
  2. Process 1 is /bin/sh. On Debian-based images that is a shell called dash, which does not forward signals to the command it started.
  3. Node never receives the signal. It keeps serving requests normally.
  4. After 10 seconds, Docker gives up and sends SIGKILL, which cannot be caught. Node dies instantly, in the middle of whatever it was doing.
  5. The exit code is 137, and stopping took the full 10 seconds every time.

In exec form, node is process 1, so it receives SIGTERM itself. If the app has a handler for it, it stops accepting new connections, finishes the requests in progress, closes its database pool, and exits with code 0. Question 105 shows the shutdown code.

You can measure the difference in one line:

bash
time docker stop api-shell   # about 10 seconds
time docker stop api-exec    # under 1 second

Two related traps:

  1. npm start as the command. Even in exec form, CMD ["npm", "start"] makes npm process 1, and node its child. Older npm versions did not pass signals on reliably, and npm adds no value at run time. Start node directly: CMD ["node", "dist/server.js"].
  2. Process 1 has extra duties. It must also collect finished child processes, or they pile up as "zombies". Most apps do not do this. Question 103 explains it, and question 471 shows the small helper, tini, that does it for you.

In Kubernetes this matters even more, because pods are stopped on every rollout, every scale-down and every node drain. The story in question 9 of this module is exactly this bug.

51. How do CMD and ENTRYPOINT work when used together? ​

The short answer

In exec form, Docker joins them: the container runs the ENTRYPOINT program with the CMD values as its default arguments. ENTRYPOINT ["curl", "-s"] plus CMD ["https://example.com"] runs curl -s https://example.com. Arguments given to docker run replace the CMD part only. If ENTRYPOINT is in shell form, CMD is ignored completely.

Docker's documentation has a table of every combination. These are the cases you need:

ENTRYPOINTCMDWhat runs
none["node","app.js"]node app.js
["node"]["app.js"]node app.js
["node"]nonenode
node (shell form)["app.js"]/bin/sh -c node only
["entry.sh"]["node","app.js"]entry.sh node app.js

The fourth row is the trap. Shell-form ENTRYPOINT swallows the arguments, so CMD silently has no effect.

The most useful pattern is the last row: an entrypoint script that does some setup and then runs whatever CMD says. The official PostgreSQL and nginx images work this way.

bash
#!/bin/sh
# docker-entrypoint.sh
set -e                                   # (1)
if [ -n "$WAIT_FOR_DB" ]; then           # (2)
  ./wait-for-db.sh "$WAIT_FOR_DB"
fi
exec "$@"                                # (3)
dockerfile
COPY docker-entrypoint.sh /usr/local/bin/
# (4)
ENTRYPOINT ["docker-entrypoint.sh"]
# (5)
CMD ["node", "dist/server.js"]
  1. set -e stops the script at the first failing command, so a failed setup step does not go unnoticed.
  2. An optional setup step, controlled by an environment variable.
  3. The important line. "$@" means "all the arguments this script was given", which are the CMD values. exec makes the shell replace itself with that command. So node becomes process 1 and receives stop signals directly, exactly as question 50 requires.
  4. The script always runs first.
  5. The default command the script hands over to.

Now docker run checkout-api runs the setup and then node. docker run checkout-api sh runs the setup and then gives you a shell, which is handy for debugging. Forgetting the exec in line 3 brings back the signal problem from question 50.

52. What happens to the default CMD when arguments are supplied to docker run? ​

The short answer

The arguments replace the default CMD completely. They are not added to it. If the image also has an ENTRYPOINT, the arguments become the entrypoint's arguments, and the entrypoint itself stays. To replace the entrypoint, you need the separate --entrypoint flag.

Take the official nginx image. Its configuration is:

  • ENTRYPOINT ["/docker-entrypoint.sh"]
  • CMD ["nginx", "-g", "daemon off;"]
bash
docker run nginx                                   # (1)
docker run nginx nginx -T                          # (2)
docker run nginx echo hello                        # (3)
docker run --entrypoint sh -it nginx               # (4)
docker run --entrypoint nginx nginx -v             # (5)
  1. No arguments: runs /docker-entrypoint.sh nginx -g "daemon off;". The script does its setup, then starts nginx.
  2. Arguments replace CMD: runs /docker-entrypoint.sh nginx -T, which prints the full configuration and exits.
  3. Replaces CMD with echo hello. The entrypoint script runs, then executes echo hello. This works because the script ends with exec "$@".
  4. --entrypoint replaces the entrypoint with sh. Docker also clears the image's default CMD in this case, so you get a plain shell.
  5. Replaces the entrypoint with nginx and passes -v. It prints the nginx version.

The same rule in Kubernetes, with different names. In a pod spec, command replaces the image's ENTRYPOINT, and args replaces its CMD. If you set only args, the image's entrypoint still runs. Mixing up these two fields is a common reason a container "ignores" its configuration.

53. What is the difference between COPY and ADD, and when would you use each? ​

The short answer

COPY copies files from the build context, or from another build stage, into the image, and does nothing else. ADD does the same, but also unpacks local tar archives automatically and can download from URLs and Git repositories. Use COPY by default, because it does exactly what it says. Use ADD only when you really want a local archive unpacked, or a remote file fetched with a checksum.

dockerfile
# (1)
COPY package.json ./
# (2)
COPY --from=build /app/dist ./dist
# (3)
ADD rootfs.tar.gz /
# (4)
ADD --checksum=sha256:24454f8...e2ad https://example.com/tool-1.2.tar.gz /tmp/
  1. A plain copy from the build context.
  2. A copy from an earlier build stage named build. Only COPY is used this way in practice.
  3. ADD sees a local compressed tar file and unpacks it into /. COPY would copy the archive file itself, still packed.
  4. Downloads a file from a URL. --checksum makes the build fail if the file's hash does not match, so a tampered download cannot sneak in. Note that remote files are not unpacked, even if they are archives.

Why COPY is the default choice. ADD's automatic unpacking is a surprise for the next person who reads the Dockerfile. Someone adds ADD vendor.tar.gz /opt/ expecting the file, and gets a folder full of extracted files instead. Clear beats clever.

Why not download with ADD without a checksum? Because the file at that URL can change at any time. Your build would silently pick up different bytes. If you need a remote file, either use ADD --checksum, or use RUN curl followed by your own hash check, so the build fails loudly when the file changes.

54. What does WORKDIR do, and why is it preferable to repeated cd commands? ​

The short answer

WORKDIR sets the current folder for every instruction after it, and for the running container. It creates the folder if it does not exist. RUN cd /app does not work the same way, because each RUN starts a fresh shell, so the change of folder is forgotten as soon as that step ends.

dockerfile
# (1)
WORKDIR /app
# (2)
COPY package.json ./
# (3)
RUN npm ci
# (4)
WORKDIR src
# (5)
CMD ["node", "server.js"]
  1. Creates /app if needed and makes it the current folder.
  2. ./ now means /app.
  3. Runs inside /app.
  4. A relative WORKDIR is joined to the current one, so this means /app/src.
  5. The container will start in /app/src, so server.js is found there.

Why cd fails:

dockerfile
RUN cd /app
RUN npm ci        # runs in /, not /app: "package.json not found"

Each RUN is a separate shell process that starts in the current WORKDIR. The cd happened inside the first process, which then ended. The second process knows nothing about it. You can write RUN cd /app && npm ci in a single step, but it is harder to read, and you would have to repeat the cd in every step.

Two good habits: use absolute paths in WORKDIR so the reader never has to work out where they are, and never leave the working folder as /, where a careless COPY . . would scatter files across the root of the filesystem.

55. What is the difference between ARG and ENV in a Dockerfile? ​

The short answer

ARG is a build-time variable. You set it with --build-arg, the build steps can use it, and it is gone when the build ends, so running containers do not see it. ENV sets an environment variable that is stored in the image. Build steps after it can use it, and every container started from the image has it. Use ARG for things that shape the build, and ENV for things the running app needs.

dockerfile
# (1)
ARG NODE_VERSION=20
# (2)
FROM node:${NODE_VERSION}-slim
# (3)
ARG APP_VERSION
# (4)
ENV APP_VERSION=${APP_VERSION}
# (5)
ENV NODE_ENV=production
# (6)
RUN echo "building ${APP_VERSION}"
bash
docker build --build-arg NODE_VERSION=22 --build-arg APP_VERSION=1.4.2 -t api .
docker run --rm api printenv APP_VERSION NODE_ENV
1.4.2
production
  1. An ARG before FROM with a default of 20. It can only be used in FROM lines.
  2. Chooses the base image from the argument. The build command above overrides it to 22.
  3. Declares APP_VERSION inside the stage. An ARG declared before FROM is not visible after it, so it must be declared again inside each stage that needs it.
  4. Copies the build-time value into a real environment variable, so the running app can read it. This is the standard way to keep a build value.
  5. An environment variable set directly. Every container gets NODE_ENV=production, and docker run -e NODE_ENV=staging can override it.
  6. Build steps can read both kinds.
ARGENV
Set with--build-argThe Dockerfile, or -e at run time
Visible during the buildFrom its line to the end of its stageFrom its line onwards
Visible in running containersNoYes
Stored in the imageNot as a variableYes, in the config

56. At what stages are ARG and ENV values available, and can either accidentally expose sensitive data? ​

The short answer

ARG values exist only during the build, from the line where they are declared to the end of that stage. ENV values exist from their line onwards, in later stages built from that stage, and in every running container. Both can leak secrets. ENV is stored in the image config, which anyone who can pull the image can read. ARG values used by a RUN step are recorded in the image's build history. Never pass secrets through either. Use build secret mounts instead.

Where each one lives:

  1. ARG before FROM: usable only in FROM lines.
  2. ARG inside a stage: from its line to the end of that stage. A later stage must declare it again.
  3. ENV inside a stage: from its line to the end of the stage, in any stage that starts FROM this stage, and in every container from the final image.

How ENV leaks. The value is written into the image configuration. Anyone who can pull the image can run:

bash
docker image inspect shop/checkout-api:1.4 --format '{{json .Config.Env}}'
json
["PATH=/usr/local/bin:...", "NODE_ENV=production", "NPM_TOKEN=npm_9f8e7d6c5b4a..."]

That token is now in every copy of the image, in every registry it was pushed to, forever. It is also in the environment of every running container, where it shows up in crash reports, debugging output and docker inspect on the host.

How ARG leaks. People think ARG is safe because it does not reach the container. But when a RUN step uses a build argument, the builder records the argument and its value in that step's history entry:

bash
docker history --no-trunc shop/checkout-api:1.4
RUN |1 NPM_TOKEN=npm_9f8e7d6c5b4a... /bin/sh -c npm ci

The value is in plain text, readable by anyone with the image. Build tools that record detailed build provenance can capture build arguments too. Docker's own build checks warn when an ARG or ENV name looks like a secret, such as one containing TOKEN or PASSWORD.

The fix. Pass build-time secrets as a secret mount, which exists only for the one RUN step that needs it and is never written into a layer or into the history. Question 79 shows exactly how. Pass run-time secrets from a secret store when the container starts (question 144).

57. What do EXPOSE, USER, LABEL, and HEALTHCHECK do? ​

The short answer

EXPOSE records which port the app listens on, as documentation. USER sets which user later build steps and the running app use, so the app does not run as root. LABEL attaches key and value metadata, such as the source repository and commit. HEALTHCHECK gives Docker a command to run regularly inside the container to test whether the app is healthy.

EXPOSE is metadata. It says "this app listens on port 8080 over TCP". It publishes nothing (question 58). Two things do use it: docker run -P publishes every exposed port to a random free port on the host, and tools that read images can show it to people.

dockerfile
EXPOSE 8080/tcp

USER changes the user for everything after it.

dockerfile
# (1)
RUN groupadd --system --gid 10001 app && useradd --system --uid 10001 --gid app app
# (2)
USER 10001:10001
  1. Creates a system user and group with fixed numbers.
  2. Switches to that user by number. Kubernetes can only confirm that a container does not run as root if the image's user is a number, because a name like app could secretly map to user 0. Question 139 explains why a non-root user matters.

LABEL adds metadata. The OCI standard defines common keys, so every tool understands them:

dockerfile
LABEL org.opencontainers.image.source="https://github.com/shop/checkout-api" \
      org.opencontainers.image.revision="3f9c2ab" \
      org.opencontainers.image.version="1.4.2"

These answer "which code is this image built from?" months later. Question 220 builds on this.

HEALTHCHECK tells Docker how to test the app:

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
  CMD ["node", "dist/health.js"]

Every 30 seconds Docker runs that command inside the container. Exit code 0 means healthy, 1 means unhealthy. --start-period gives a slow-starting app 20 seconds before failures count. After 3 failures in a row the status becomes unhealthy. Using a small Node script instead of curl means the image does not need curl installed. Question 109 covers what "unhealthy" means.

One important gap: Kubernetes ignores HEALTHCHECK completely. It uses its own probes, defined in the pod spec (question 401). And plain Docker only reports an unhealthy status. It does not restart the container by itself.

58. Does EXPOSE publish a container port to the host automatically? Why or why not? ​

The short answer

No. EXPOSE is only documentation inside the image. A port becomes reachable from the host only when you publish it at run time with -p host_port:container_port, or with -P. This is deliberate: which host port to use, and on which network interface, is a decision for whoever runs the container, not for whoever built the image.

Many people expect this to work and are surprised:

bash
docker run -d --name web nginx       # nginx's image has EXPOSE 80
curl http://localhost:80             # fails: connection refused
docker run -d --name web2 -p 8080:80 nginx
curl http://localhost:8080           # works

Why the design is right. An image is built once and run in many places. If the image itself could grab host port 80:

  1. Two containers from the same image could never run on one machine, because both would want port 80.
  2. The image author would be making a security decision, opening a port to the world, on machines they have never seen.
  3. The operator could not choose to publish only on 127.0.0.1, which keeps a service private to the machine. Question 114 shows how.

Containers on the same network do not need publishing at all. On a user-defined Docker network, every container can reach every port of every other container, whether or not it is exposed. Publishing is only about reaching a container from outside Docker's networks, through the host. Question 113 draws the difference between a container port and a host port.

So what is EXPOSE good for? It tells humans and tools which port the app uses. docker run -P publishes all exposed ports to random high-numbered host ports, and docker ps shows the mapping.

59. What is a build context, and why can a large build context slow down builds? ​

The short answer

The build context is the set of files the builder may use, usually the folder you pass to docker build, such as .. COPY and ADD can only read files from it. With the old builder, the whole folder was uploaded to the daemon before any step ran. BuildKit transfers only the files the build actually uses, but it still has to scan the folder, and a careless COPY . . still sends everything, breaks the cache on every change, and bloats the image.

bash
docker build -t api .                         # (1)
docker build -t api -f docker/Dockerfile .    # (2)
  1. The . at the end is the build context: the current folder.
  2. The Dockerfile can live anywhere. The context is still ..

Why a large context hurts:

  1. Upload time. The old builder printed Sending build context to Docker daemon 2.3GB and you waited while it copied every file, including a 2 GB node_modules folder and the whole .git history. With a remote daemon (question 464), that upload crosses the network.
  2. Cache misses. COPY . . hashes every file it copies. If anything in the folder changes, even a log file or a file in .git, that step and every step after it rebuild.
  3. Bloated images. COPY . . puts everything into the image: test data, documentation, local .env files with passwords.
  4. Wrong files. Copying your laptop's node_modules into a Linux image can break native modules that were compiled for macOS or Windows.

What BuildKit improved. BuildKit, Docker's current builder, asks the client only for files that build steps actually reference, and on later builds it sends only what changed. That fixes most of the upload cost. It does not fix points 2 to 4, because COPY . . still asks for everything.

The fix for all four is a .dockerignore file, plus copying only what each step needs. Question 60 covers it.

60. What is a .dockerignore file, and which files would you normally exclude? ​

The short answer

A .dockerignore file sits next to the build context and lists files and folders the builder must never see, using patterns like .gitignore. Normally you exclude version control data, dependency folders and build output made on the host, secrets and .env files, logs, test reports, editor settings and operating system junk files.

text
# .dockerignore
# (1)
.git
# (2)
node_modules
dist
# (3)
coverage
*.log
# (4)
.env
.env.*
# (5)
!.env.example
# (6)
**/*.pem
.vscode
.idea
.DS_Store
# (7)
Dockerfile*
.dockerignore
  1. Git's history can be hundreds of megabytes, and it changes on every commit, which would break the cache constantly.
  2. Dependencies must be installed inside the image, for the image's own operating system. A laptop's node_modules may contain native code compiled for the wrong system. The same goes for dist, if the build creates it inside the image.
  3. Test reports and logs have no place in a production image.
  4. Local secrets. This line has prevented countless leaked passwords.
  5. ! makes an exception: the example file with no real values may be included.
  6. **/ matches in any folder, so private key files are excluded everywhere.
  7. Optional. The Dockerfile does not need to be inside the image.

Details that matter:

  • The file must be at the root of the build context, not next to the Dockerfile if they are in different places. BuildKit also accepts a file named after the Dockerfile, such as docker/api.Dockerfile.dockerignore, so one repository can have different ignore rules per image.
  • Patterns are matched against paths relative to the context root.
  • An allow-list is even safer than a block-list. Exclude everything with *, then re-include only what the build needs with !package.json, !src/ and so on. A new secret file added to the repository later is then excluded automatically.

467. What do VOLUME, STOPSIGNAL, SHELL, and ONBUILD do in a Dockerfile? ​

The short answer

VOLUME marks a folder where Docker should mount a volume, and Docker creates an anonymous one there if you do not provide one. STOPSIGNAL changes the signal docker stop sends, for apps that shut down cleanly on something other than SIGTERM. SHELL changes the shell used for shell-form instructions. ONBUILD stores an instruction that runs later, when another image is built FROM this one. All four are used rarely, and each has a trap.

VOLUME

dockerfile
VOLUME /var/lib/postgresql/data

Every container from this image gets a volume at that path, so the database's data does not land in the writable layer. The traps: if you forget to name a volume at run time, Docker creates an anonymous volume with a random name, and these pile up unnoticed on the disk. Also, with the old builder, changes made to that folder by later Dockerfile steps were thrown away. Many teams prefer to leave VOLUME out of the image and always mount storage explicitly at run time.

STOPSIGNAL

dockerfile
STOPSIGNAL SIGQUIT

The official nginx image uses this, because nginx shuts down gracefully on SIGQUIT and fast on SIGTERM. docker stop then sends SIGQUIT first. containerd also uses the image's stop signal when Kubernetes stops the container.

SHELL

dockerfile
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN curl -fsSL https://example.com/install.sh | bash

By default, a pipe's exit status is the status of its last command. If curl fails here, bash happily runs an empty script and the step "succeeds". -o pipefail makes the whole pipe fail if any part fails. On Windows images, SHELL ["powershell", "-Command"] switches shell-form steps to PowerShell.

ONBUILD

dockerfile
# in a base image called shop/node-base
ONBUILD COPY package*.json ./
ONBUILD RUN npm ci

These lines do nothing when the base image is built. They run at the start of any build that says FROM shop/node-base. It looks clever but hides steps from whoever writes the child Dockerfile, which makes failures confusing. Most teams avoid it and share a documented template instead.

468. What do COPY --chown, --chmod, and --link do, and why do they matter for image size and build speed? ​

The short answer

--chown and --chmod set the owner and the permissions of files as they are copied, in the same layer. Doing it in a separate RUN chown or RUN chmod step copies every affected file again into a new layer, which can double the image size. --link puts the copied files in a layer that does not depend on the layers before it, so it can be reused from cache even when earlier layers change, which makes rebuilds faster.

The size trap that --chown fixes:

dockerfile
COPY dist/ /app/dist/                  # layer A: 200 MB of files owned by root
RUN chown -R node:node /app/dist       # layer B: 200 MB again

Changing a file's owner is a change to that file. By the copy-on-write rule from question 29, every one of those files is copied into the new layer with its new owner. Layer A still holds the old copies. The image is now 400 MB for 200 MB of files.

dockerfile
# (1)
COPY --chown=node:node dist/ /app/dist/
# (2)
COPY --chmod=755 scripts/entry.sh /usr/local/bin/
  1. The files arrive already owned by node. One layer, 200 MB.
  2. The script arrives already executable. No extra RUN chmod layer.

What --link does:

dockerfile
COPY --link --from=build /app/dist /app/dist

Normally, a layer's files are recorded relative to everything below it, so if any earlier layer changes, this layer must be rebuilt too. With --link, BuildKit stores the copied files as an independent layer and simply places it on top. If the base image gets a security update, a --link layer of your compiled code can be reused straight from cache, and even pushed without uploading it again. This is called rebasing a layer.

--link needs BuildKit, and it has one limit: because the layer is independent, the copy cannot follow symbolic links or depend on what files already exist at the destination.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Docker, CI/CD, Kubernetes & Cloud
Your project
Docker
CI/CD
Kubernetes
Cloud
Observability
Scenarios
Other topics
Nothing picked yet