Docker and CI/CD Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is the main benefit of a multi-stage build?
Correct answer: Build tools stay in earlier stages; the final image has only runtime files
A
builderstage installs dev dependencies and compiles; the final stage copies only the output withCOPY --from=builder. Images get smaller and safer.2. Why does this Dockerfile reinstall all dependencies on every code change?
COPY . . RUN npm ciCorrect answer: Any file change invalidates
COPY . ., sonpm cireruns tooCache invalidation cascades: once a layer changes, every later layer is rebuilt. Copy
package.jsonand the lockfile, runnpm ci, then copy the rest.3. Why combine
apt-get updateandapt-get installin oneRUN?Correct answer: A cached
updatelayer would install packages from a stale indexIf
updateis its own cached layer, a later change to the install line reuses an old package index. Also clean/var/lib/apt/listsin the sameRUN.4. Why does
RUN rm -rf /tmp/buildin a later layer not shrink the image?Correct answer: Earlier layers still contain the files; deletion only hides them
Layers are additive. Clean up in the same
RUNthat created the files, or use a multi-stage build so temporary files never reach the final image.5. What is the difference between
CMD ["node", "server.js"]andCMD node server.js?Correct answer: Exec form runs node as PID 1; shell form wraps it in
/bin/sh -cIn shell form, the shell is PID 1 and usually doesn't forward SIGTERM, so
docker stopwaits for the timeout and kills the app without a graceful shutdown.6. Why can a process running as PID 1 in a container misbehave?
Correct answer: PID 1 gets no default signal handlers and must reap zombies
The kernel doesn't apply default actions for signals to PID 1, so an app without a SIGTERM handler ignores it.
docker run --initor tini adds a tiny init that forwards signals and reaps children.7. What should a Node.js server do on SIGTERM?
Correct answer: Stop accepting connections, finish requests, close pools, then exit
server.close()stops new connections while in-flight requests complete. Then close database pools and exit within the grace period.8. Why is
CMD ["npm", "start"]discouraged in production images?Correct answer: npm may not forward signals to node, and it adds an extra process
Running
nodedirectly makes it the process that gets SIGTERM, so graceful shutdown works, and it avoids npm's overhead.9. After
USER node, the app can't write to/app. What's a common fix?Correct answer: Copy files with
COPY --chown=node:nodeor give that user the folderFiles copied as root stay owned by root. Set ownership during the copy, and prefer writing only to specific folders or volumes.
10. How do you use an npm token during a build without leaving it in the image?
Correct answer: Mount it as a build secret:
RUN --mount=type=secret,id=npm ...Build secrets are available only during that
RUNand never written to a layer.ARGvalues and copied files end up in the image history.11. What does
RUN --mount=type=cache,target=/root/.npm npm cigive you?Correct answer: A persistent download cache shared between builds, not in the image
Even when the layer is rebuilt, packages already downloaded are reused. The cache lives on the builder, so on ephemeral CI runners it needs exporting.
12. What does BuildKit do with independent stages of a multi-stage build?
Correct answer: Builds them in parallel and skips stages the target doesn't need
BuildKit builds a dependency graph of stages. A
teststage that the final target doesn't depend on isn't built unless you target it.13. How is an image digest different from a tag?
Correct answer: A digest is a content hash and never changes; a tag can be moved
node:22@sha256:...always resolves to the same bytes. Deploying by digest guarantees you run exactly what was tested.14. What are
<none>:<none>(dangling) images?Correct answer: Old images whose tag moved to a newer build
Rebuilding
my-app:latestmoves the tag and leaves the previous image untagged.docker image pruneremoves them.15. What is
compose.override.yamlused for?Correct answer: Local tweaks merged over
compose.yamlautomaticallyTypical overrides add bind mounts, debug ports or dev commands. For other environments, pass files explicitly:
-f compose.yaml -f compose.prod.yaml.16. What are Compose profiles for?
Correct answer: Starting optional services only when a profile is enabled
For example an admin UI or a seeding job marked
profiles: [tools]starts only withdocker compose --profile tools up.17. You bind-mount the project into a Node container and the app can't find its modules. Why?
Correct answer: The mount hides
node_modulesfrom the image; use a separate volumeMounting over
/appreplaces the image's/app/node_moduleswith the host folder. An extra volume on/app/node_modules, or Compose Watch sync, avoids it.18. In Compose, what is the difference between the
.envfile andenv_file:?Correct answer:
.envfills${VAR}in the YAML;env_filesets container variablesThe project
.envis used for interpolation incompose.yaml. Variables reach the container only throughenvironment:orenv_file:.19. A container stops with exit code 137. What is the likely cause?
Correct answer: It was killed by SIGKILL, often for exceeding its memory limit
128 + 9 (SIGKILL).
docker inspectshowsOOMKilled: truewhen the memory limit was hit. Exit 143 (128 + 15) means SIGTERM.20. Why may Node.js ignore a container's memory limit and get OOM-killed?
Correct answer: The heap limit might not match the container limit, so set it
Recent Node versions read cgroup limits, but heap is only part of the memory. Tune
--max-old-space-sizeand leave headroom for buffers and native memory.21. What does
--network hostdo?Correct answer: The container uses the host's network stack directly
No port mapping is needed and there's no NAT overhead, but there's also no network isolation and ports can clash. On Docker Desktop it behaves differently.
22. Why should containers log to stdout and stderr?
Correct answer: The platform collects and routes the streams for you
Log files inside a container fill its writable layer and vanish with it. Twelve-factor apps treat logs as event streams; the platform ships them to a log store.
23. What prevents Docker's default
json-filelogs from filling the disk?Correct answer: Rotation options like
max-sizeandmax-fileWithout rotation, a chatty container can fill the host disk. Set it per container or in the daemon config, or use the
localdriver.24. What does running with
--read-onlyachieve?Correct answer: The root filesystem can't be modified; writes go to volumes
An attacker can't drop binaries or change code. Mount a
tmpfsfor/tmpand volumes for data that must be written.25. What is a distroless image?
Correct answer: An image with your app and runtime, but no shell or package manager
Fewer tools mean fewer vulnerabilities and less for an attacker to use. Debugging is harder, so
debugvariants with a shell exist.26. Why install only production dependencies in the final image?
Correct answer: Dev tools add size and vulnerabilities but aren't needed to run
npm ci --omit=devin the runtime stage (or copying a prunednode_modulesfrom a builder) keeps TypeScript, test runners and linters out of production.27. What does an image scanner such as Trivy check?
Correct answer: Known CVEs in OS packages and app dependencies
Run it in CI and fail the build on high-severity issues that have a fix. Rebuilding regularly picks up patched base images.
28. Why is mounting
/var/run/docker.sockinto a container risky?Correct answer: It effectively gives that container root on the host
Whoever controls the Docker API can start a privileged container that mounts the host filesystem. Only trusted tools should get the socket.
29. An image built on an Apple Silicon Mac fails on an x86 server with
exec format error. Why?Correct answer: It was built for arm64; build for linux/amd64 or multi-platform
Images contain CPU-specific binaries.
docker buildx build --platform linux/amd64,linux/arm64produces a multi-arch image with the right variant for each host.30. What does
exec "$@"do at the end of an entrypoint script?Correct answer: Replaces the shell with the command, so it becomes PID 1
Entrypoint scripts often prepare config, then hand over. Without
exec, the shell stays PID 1 and signals may never reach the app.31. Does Kubernetes use the Dockerfile
HEALTHCHECK?Correct answer: No, it uses its own liveness and readiness probes
Kubernetes ignores the image healthcheck. Define probes in the pod spec so it knows when to route traffic and when to restart.
32. What makes a good cache key for
node_modulesor the npm cache in CI?Correct answer: The OS plus a hash of the lockfile
hashFiles('**/package-lock.json')changes only when dependencies change. A commit SHA would never hit;restore-keyscan fall back to a partial match.33. Cache vs artifacts in CI: what's the difference?
Correct answer: Cache speeds up later runs; artifacts are outputs you keep
A cache miss should only cost time. Build output passed to a deploy job, or test reports, belong in artifacts.
34. What does this do?
concurrency: group: deploy-${{ github.ref }} cancel-in-progress: trueCorrect answer: A new run cancels the older one for the same branch
Pushing three times quickly then runs CI only for the last push. For production deploys you may prefer queueing over cancelling a deploy halfway.
35. In a monorepo, how can you avoid running the backend pipeline when only the frontend changed?
Correct answer: Filter triggers by
pathsor detect changed packageson: push: paths: ['apps/api/**']is the simple version. Tools like Nx or Turborepo compute affected projects from the dependency graph.36. What is
workflow_dispatchfor?Correct answer: Starting a workflow manually, optionally with inputs
It adds a "Run workflow" button and API trigger, useful for manual deploys, backfills or one-off maintenance jobs.
37. Why set
permissions:explicitly forGITHUB_TOKEN?Correct answer: To give the workflow only the access it needs
Least privilege limits the damage if a step or dependency is compromised. For example
contents: readfor tests,packages: writeonly in the publish job.38. Why don't workflows triggered by
pull_requestfrom forks get repository secrets?Correct answer: Fork code is untrusted and could send the secrets out
Anyone can open a PR that changes the workflow or test code.
pull_request_targetruns with secrets, which is why checking out PR code there is dangerous.39. What do deployment environments with required reviewers add?
Correct answer: A manual approval gate and environment-scoped secrets
A job that targets
environment: productionwaits for approval, and production secrets are available only to such jobs.40. What is a reusable workflow?
Correct answer: A workflow with
on: workflow_callthat others call like a jobTeams centralize build or deploy logic in one place and call it with
uses: org/repo/.github/workflows/deploy.yml@v1, passing inputs and secrets.41. What is a composite action?
Correct answer: A bundle of steps reused as a single step
Composite actions group steps (setup, install, cache) into one
uses:. Reusable workflows reuse whole jobs instead.42. Why pin third-party actions to a full commit SHA rather than
@v3?Correct answer: A tag can be moved to malicious code; a SHA can't
If an action's repository is compromised, the attacker can retag
v3. Pinning to a SHA (with Dependabot updating it) prevents that.43. What does OIDC give a CI pipeline that deploys to a cloud provider?
Correct answer: Short-lived credentials instead of stored long-lived keys
The job gets a signed identity token, and the cloud trusts it for a specific repo, branch or environment. No static access keys to leak or rotate.
44. How does one job pass a value, such as an image tag, to another?
Correct answer: Through job
outputs, read vianeeds.<job>.outputsA step writes to
$GITHUB_OUTPUT, the job maps it to an output, and downstream jobs read it. For files, use artifacts.45. How do you run a deploy step only for pushes to
main?Correct answer:
if: github.ref == 'refs/heads/main'Expressions in
if:can check the event, branch, previous results (success(),failure()) and more.only:is GitLab's older syntax.46. What does
fail-fast: falsechange in a matrix?Correct answer: Other matrix jobs keep running when one fails
By default one failing combination cancels the rest. Turning it off shows every failing version at once, at the cost of runner minutes.
47. Why are self-hosted runners risky for public repositories?
Correct answer: PRs from anyone could run code on your machine
A malicious PR can leave persistent malware on a non-ephemeral runner. Use GitHub-hosted runners for public repos or isolate self-hosted ones per job.
48. Why are Docker builds on fresh CI runners often slow, and what helps?
Correct answer: There's no local cache; export it with
--cache-toand reuse itEach job starts on a clean machine. Cache backends (registry,
type=gha) store layers between runs so unchanged steps are reused.49. Why tag images with the commit SHA?
Correct answer: Each image maps to exact code and is never overwritten
my-app:3f2a9c1tells you what's running and makes rollbacks precise. Version tags like1.4.0can be added for releases.50. How do you speed up a slow pipeline without dropping checks?
Correct answer: Run independent jobs in parallel and put fast checks first
Lint and type checks fail in seconds; long test suites can be sharded across runners. Caching dependencies and build layers saves more minutes.
51. How can integration tests in GitHub Actions get a real PostgreSQL?
Correct answer: Declare it under
services:; it runs as a side containerService containers start before the steps and are reachable on mapped ports (or by name when the job runs in a container). Health options make the job wait for readiness.
52. What does Testcontainers do?
Correct answer: Starts throwaway Docker containers from test code
Tests start a real database or broker, get its connection details and stop it afterwards. It works the same locally and in CI where Docker is available.
53. Why should database migrations stay backward compatible during a deploy?
Correct answer: Old and new app versions run at the same time during rollout
In a rolling or blue-green deploy, the old code still runs against the new schema. Expand-and-contract: add first, migrate data, remove later.
54. What is a canary release?
Correct answer: Sending a small share of traffic to the new version first
If error rates and latency stay healthy, the share grows; otherwise traffic goes back. It limits how many users a bad release can hurt.
55. What does a rolling update do?
Correct answer: Replaces instances a few at a time, keeping the service up
It's the default for Kubernetes Deployments. Readiness probes make sure new instances get traffic only when they can serve it.
56. How do feature flags change the relationship between deploy and release?
Correct answer: Code can be deployed dark and enabled later for chosen users
Deploying becomes a technical event and releasing a business decision. Clean up old flags, since each one adds branches to the code.
57. What are smoke tests after a deploy for?
Correct answer: Quickly checking that key paths work in the new environment
A few requests (health endpoint, login, a main page) catch misconfiguration right away, and can trigger an automatic rollback.
58. Which are the classic DORA metrics?
Correct answer: Deploy frequency, lead time, change failure rate, restore time
Two measure throughput and two stability. Research shows high performers do well on both, so speed and stability aren't a trade-off.
59. What does "lead time for changes" measure?
Correct answer: Time from a commit to it running in production
Short lead times come from small batches, fast pipelines and automated deploys, and they make fixes reach users quickly too.
60. Why do CI and long-lived feature branches work against each other?
Correct answer: Code isn't integrated until merge, so conflicts pile up
Running a pipeline on a branch isn't integration. Real CI means merging into the mainline at least daily, which trunk-based development encourages.
61. What is infrastructure as code?
Correct answer: Describing servers and networks in versioned config files
Tools like Terraform turn reviewable files into infrastructure. Changes go through pull requests and environments become reproducible.
62. What is the core idea of GitOps?
Correct answer: Git holds the desired state; an agent syncs the system to it
Instead of CI pushing to the cluster, an operator like Argo CD or Flux pulls and continuously reconciles. Rollback is a Git revert.
63. Readiness vs liveness probe in Kubernetes: what's the difference?
Correct answer: Readiness gates traffic; liveness restarts a stuck container
A pod that isn't ready is removed from Service endpoints but not restarted. Don't let liveness depend on the database, or an outage restarts every pod.
64. Why do you usually create a Deployment rather than Pods directly?
Correct answer: It keeps the replica count and manages rolling updates
A bare pod that dies is gone. A Deployment (through a ReplicaSet) recreates pods and rolls out new versions gradually.
65. Are Kubernetes Secrets encrypted by default?
Correct answer: Not necessarily; they're base64-encoded unless encryption is set
Base64 is an encoding, not encryption. Enable encryption at rest, restrict access with RBAC, or use an external secrets manager.
66. Resource requests vs limits in Kubernetes: what do they do?
Correct answer: Requests are used for scheduling; limits cap usage
The scheduler places pods by requests. Exceeding a memory limit gets the container OOM-killed; exceeding a CPU limit throttles it.
67. What do
maxSurgeandmaxUnavailablecontrol?Correct answer: How many extra or missing pods a rolling update allows
maxSurge: 1, maxUnavailable: 0adds a new pod before removing an old one, keeping full capacity at the cost of extra resources.68. What do Dependabot or Renovate do?
Correct answer: Open PRs that update dependencies, letting CI test them
Small, frequent updates are easier than rare big ones. Grouping and auto-merging patch updates with green CI keeps the noise down.
69. Why shouldn't you overwrite an existing image tag like
1.4.0?Correct answer: Hosts that pulled it differ from new ones
Different machines would run different code under the same name, and rollbacks become guesswork. Treat release tags as immutable; many registries can enforce it.
70. What does
needs:change in a GitLab CI job?Correct answer: The job starts once its needs finish, not after the stage
Without
needs, a job waits for the whole previous stage. With it, the pipeline becomes a directed graph and finishes sooner.71. CI masks secret values in logs. Why can a secret still leak?
Correct answer: Masking matches exact strings, so encoded values slip through
Base64-encoding, splitting or writing the secret to an artifact bypasses masking. Avoid printing secrets at all and keep their scope small.
72. Why should every production deploy go through the pipeline, not a manual
docker pushfrom a laptop?Correct answer: The pipeline builds from reviewed code and records what was deployed
A laptop build may include uncommitted changes and different dependencies, and leaves no audit trail. One path to production keeps deploys repeatable.
73. What does
docker history my-apphelp you find?Correct answer: Which instructions created which layers and how big each is
It lists layers with their size and the instruction that produced them, a quick way to spot a huge
COPYor a forgotten cache folder.74. What does
docker compose configprint?Correct answer: The final config after merging files and filling variables
It shows exactly what Compose will run once override files and
${VAR}interpolation are applied, which helps debug "why is this value wrong".75. What does
restore-keysadd to a cache step?Correct answer: Fallback prefixes used when the exact key misses
With
restore-keys: npm-${{ runner.os }}-, a lockfile change still restores the most recent similar cache, so only new packages are downloaded.