Docker and CI/CD Junior 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. How does a container differ from a virtual machine?
Correct answer: It shares the host kernel instead of running its own OS
Containers are isolated processes on the host kernel (namespaces and cgroups), so they start in milliseconds and use little memory. A VM boots a whole guest OS on virtual hardware.
2. What is the difference between an image and a container?
Correct answer: An image is a read-only template; a container is a running instance of it
Like a class and its objects: one image can start many containers. Each container adds its own thin writable layer on top of the image.
3. What is a Dockerfile?
Correct answer: A text file with the steps to build an image
Each instruction (
FROM,COPY,RUN,CMD...) describes a build step.docker buildexecutes them and produces an image.4. What does
FROM node:22-alpinedo in a Dockerfile?Correct answer: Sets the base image that the build starts from
Every build starts from a base image, here the official Node.js 22 image on Alpine Linux. Your instructions add layers on top of it.
5. What is the difference between
RUNandCMD?Correct answer:
RUNexecutes at build time;CMDsets what runs at container startRUN npm cibakes the result into an image layer.CMD ["node", "server.js"]is only metadata: the default command when a container starts.6. How does
ENTRYPOINTrelate toCMD?Correct answer:
ENTRYPOINTis the executable;CMDgives its default argumentsWith
ENTRYPOINT ["node"]andCMD ["server.js"],docker run image other.jsreplaces only the arguments. WithoutENTRYPOINT, run arguments replaceCMDentirely.7. Why is
COPYusually preferred overADD?Correct answer:
COPYjust copies;ADDalso fetches URLs and unpacks archivesADDhas extra behavior (auto-extracting local tar files, downloading URLs) that can surprise you. UseCOPYunless you need exactly that.8. What does
WORKDIR /appdo?Correct answer: Sets the directory for the next instructions and the container
It creates the directory if needed and makes later
RUN,COPYandCMDrelative to it. It's cleaner thanRUN cd /app && ..., which doesn't persist between instructions.9. Does
EXPOSE 3000in a Dockerfile make the port reachable from the host?Correct answer: No, it only documents the port; publish it with
-pEXPOSEis metadata for people and tools.docker run -p 8080:3000(orports:in Compose) actually maps a host port to the container port.10. What does
docker run -p 8080:3000 my-appmean?Correct answer: Host port 8080 forwards to port 3000 in the container
The format is
host:container. Openhttp://localhost:8080and the request reaches the app listening on 3000 inside the container.11. How do you see stopped containers as well as running ones?
Correct answer:
docker ps -adocker psshows only running containers. Stopped ones keep their filesystem and logs until you remove them withdocker rm(or start them with--rm).12. How do you read the output of a running container?
Correct answer:
docker logs <container>Docker captures the container's stdout and stderr. Add
-fto follow and--tail 100for recent lines. That's why apps in containers should log to stdout.13. How do you open a shell inside a running container?
Correct answer:
docker exec -it <container> shexecstarts an extra process in an existing container.docker runwould create a new container from an image instead. Minimal images may haveshbut notbash.14. Why does a container exit right after starting?
Correct answer: Its main process finished, and the container lives only as long as it
A container is its main process (PID 1). A script that finishes, or a server that crashes, ends the container. Check
docker logsand the exit code indocker ps -a.15. What happens to files written inside a container when you remove it?
Correct answer: They are lost unless they were written to a volume
The writable layer belongs to the container and is deleted with it. Databases and uploads need a volume or bind mount to outlive the container.
16. What is the difference between a volume and a bind mount?
Correct answer: Docker manages volumes; a bind mount maps a chosen host path
Volumes live in Docker's storage area and are the default choice for data. Bind mounts expose a specific host folder, which is handy in development for live code reloading.
17. What is
.dockerignorefor?Correct answer: Excluding files from the build context sent to the builder
Without it,
node_modules,.gitand.envare sent to the builder, which slows builds, busts the cache and may leak secrets into images viaCOPY . ..18. Why copy
package.jsonand the lockfile before the rest of the source code?Correct answer: So the
npm cilayer is cached until dependencies changeA layer is rebuilt when its inputs change, and so is everything after it. Copying manifests first means editing code doesn't trigger a full reinstall.
19. What does the
latesttag mean?Correct answer: Just the default tag name; it's not guaranteed to be newest
latestis used when you don't give a tag. It points wherever the publisher last pushed it, so builds that rely on it aren't reproducible. Pin specific versions.20. In
docker build -t my-app ., what is the.?Correct answer: The build context: files the build can
COPYThe context is packaged and sent to the builder. By default the Dockerfile is looked up there too;
-fpoints to another one.21. What is a container registry?
Correct answer: A server that stores and distributes images
Docker Hub, GitHub Container Registry, GitLab Registry and cloud registries store images.
docker pushuploads,docker pulldownloads.22. What is the difference between
ARGandENV?Correct answer:
ARGexists only during the build;ENValso at runtimeARGvalues are passed with--build-argand vanish after the build.ENVvalues are stored in the image and visible to the running app. Neither is a safe place for secrets.23. What is Docker Compose used for?
Correct answer: Defining and running a multi-container app from one YAML file
compose.yamldescribes services (app, database, cache), their networks and volumes.docker compose upstarts the whole stack.24. In Compose, how does the
appservice connect to thedbservice?Correct answer: By the service name, e.g.
postgres://db:5432Compose puts services on a shared network with built-in DNS, so the service name resolves to the right container. IPs change between runs; names don't.
25. Does
depends_on: [db]wait until the database is ready to accept connections?Correct answer: Not by default; it only orders startup
By default it waits only for the container to start. Use
condition: service_healthywith a healthcheck ondb, and make the app retry connections anyway.26. What does
docker compose down -vdo in addition todown?Correct answer: It also removes the named volumes, deleting their data
downstops and removes containers and networks but keeps volumes.-vwipes them too, which is great for a fresh local database and a disaster if run by mistake.27. Inside a container, what does
localhostrefer to?Correct answer: The container itself, not the host machine
Each container has its own network namespace. To reach a service on the host, Docker Desktop provides
host.docker.internal; other containers are reached by name.28. What does
docker stopdo?Correct answer: Sends SIGTERM, then SIGKILL after a timeout (10 s by default)
The app gets a chance to finish requests and close connections. If PID 1 ignores SIGTERM, every stop takes the full timeout and ends in a hard kill.
29. What is the difference between
docker rmanddocker rmi?Correct answer:
rmremoves containers;rmiremoves imagesAn image can't be removed while a container (even a stopped one) uses it.
docker system prunecleans unused containers, networks, images and build cache.30. Your disk is full of old Docker data. What is a common cleanup command?
Correct answer:
docker system pruneIt removes stopped containers, unused networks, dangling images and build cache. Add
-afor all unused images and--volumesfor volumes, carefully.31. How do you pass an environment variable when starting a container?
Correct answer:
docker run -e API_URL=https://api.example.com my-app-esets one variable and--env-file .envloads many. Configuration from the environment lets the same image run in every environment.32. What does
--rmdo indocker run --rm my-app?Correct answer: Removes the container automatically when it exits
Great for one-off commands and tests: no pile of stopped containers. Data in named volumes is kept.
33. What is a common gotcha with Alpine-based images?
Correct answer: They use musl instead of glibc, which can break native modules
Alpine is tiny, but prebuilt native binaries compiled for glibc may fail or need rebuilding. Slim Debian images are a common alternative.
34. Why shouldn't you copy a
.envfile with secrets into an image?Correct answer: Anyone who can pull the image can read the secrets
Image layers are just tar archives; deleting a file in a later layer doesn't remove it from history. Pass secrets at runtime or with build secrets.
35. What does
-ddo indocker run -d nginx?Correct answer: Runs the container in the background
Detached mode returns your terminal and prints the container ID. Read the output later with
docker logs.36. What do the
-itflags give you?Correct answer: An interactive terminal: stdin kept open plus a TTY
-ikeeps stdin open and-tallocates a pseudo-terminal, which shells and REPLs need. Scripts in CI usually don't need either.37. What does
--restart unless-stoppeddo?Correct answer: Restarts the container after crashes and reboots, unless you stopped it
Restart policies (
no,on-failure,always,unless-stopped) let Docker bring services back on a single host. Orchestrators handle this in clusters.38. What does a
HEALTHCHECKinstruction add to a container?Correct answer: A command Docker runs periodically to mark it healthy or not
Status appears in
docker psand can gate Compose startup (service_healthy). Plain Docker doesn't restart unhealthy containers by itself.39. What is Continuous Integration (CI)?
Correct answer: Merging small changes often, each checked by an automated build and tests
Integrating frequently keeps conflicts small, and the automated checks catch breakage within minutes of the change that caused it.
40. What is the difference between continuous delivery and continuous deployment?
Correct answer: Delivery keeps every change releasable; deployment releases it automatically
With continuous delivery, a human decides when to push the button. With continuous deployment, every change that passes the pipeline goes to production.
41. What does a typical CI/CD pipeline do, in order?
Correct answer: Build, test, then deploy if the earlier stages pass
Each stage is a gate: a failed lint or test stops the pipeline before a broken build reaches users. Fast checks usually run first.
42. Why run CI on every pull request?
Correct answer: To catch breakage before it is merged into
mainRequired status checks on a protected branch block merging until CI is green, so
mainstays releasable.43. Where do GitHub Actions workflow files live?
Correct answer:
.github/workflows/*.ymlin the repositoryWorkflows are versioned with the code, so changes to the pipeline go through review like any other change.
44. In GitHub Actions, what is the difference between a job and a step?
Correct answer: A job runs on its own runner; steps run in order inside it
Steps in a job share the same machine and filesystem. Separate jobs run in parallel by default and share data only through artifacts or outputs.
45. What does
runs-on: ubuntu-latestset?Correct answer: The type of runner machine the job runs on
GitHub-hosted runners are fresh VMs for each job. Self-hosted runners are your own machines, chosen with labels.
46. What does the step
uses: actions/checkout@v4do?Correct answer: Clones the repository into the runner's workspace
Runners start empty, so most workflows check out the code first. By default it's a shallow clone with only the triggering commit.
47. What does
on: [push, pull_request]define in a workflow?Correct answer: The events that trigger the workflow
Triggers can be narrowed with
branchesandpaths, and there are many more events:schedule,workflow_dispatchfor manual runs,releaseand others.48. How should a workflow access an API token for deployment?
Correct answer: From a repository secret:
${{ secrets.DEPLOY_TOKEN }}Secrets are encrypted, masked in logs and not passed to workflows from forks by default. Even better are short-lived credentials via OIDC.
49. Why use
npm cirather thannpm installin CI?Correct answer: It installs exactly the lockfile and fails if it's out of sync
npm cideletesnode_modulesand installs exactly what the lockfile says, never updating it. Builds become reproducible.50. What does caching dependencies in CI speed up?
Correct answer: Installs, by reusing downloaded packages between runs
The cache key usually includes a hash of the lockfile, so it's invalidated when dependencies change.
actions/setup-nodecan do this withcache: npm.51. What are workflow artifacts?
Correct answer: Files a job uploads to keep or pass to later jobs
Build output, test reports and coverage are typical artifacts. Unlike a cache, they are meant to be downloaded and are kept for a set number of days.
52. What happens by default when a step in a job fails?
Correct answer: The remaining steps are skipped and the job fails
A non-zero exit code fails the step.
continue-on-errororif: always()change this, for example to upload test reports even after failures.53. How do you make a deploy job wait for the test job?
Correct answer: Add
needs: testto the deploy jobJobs run in parallel unless
needscreates a dependency. Iftestfails, jobs that need it are skipped.54. What does a build matrix do?
Correct answer: Runs a job for each combination, e.g. Node 20 and 22
strategy.matrixexpands one job definition into many parallel jobs, which is handy for testing several runtime versions or operating systems.55. Which file configures GitLab CI/CD?
Correct answer:
.gitlab-ci.ymlin the repository rootIt defines stages and jobs; jobs in the same stage run in parallel and stages run in order. GitLab runners execute the jobs.
56. Why keep configuration such as database URLs in environment variables?
Correct answer: The same build can then run in every environment
Twelve-factor apps separate config from code, so one artifact is promoted from staging to production with different settings.
57. What is a staging environment for?
Correct answer: Testing a release in conditions close to production
Staging catches problems that only show up with real infrastructure, configuration and data shapes, before users see them.
58. What is a rollback?
Correct answer: Returning production to the previous working version
With immutable, versioned artifacts, rolling back is redeploying the previous image tag. Database migrations need care, since they don't roll back by themselves.
59. What is blue-green deployment?
Correct answer: Running a new version beside the old, then switching traffic
The old environment stays ready, so a rollback is just switching traffic back. The cost is running two environments during the switch.
60. What does "build once, deploy many" mean?
Correct answer: One artifact is promoted through staging to production
Rebuilding per environment can produce different results (new dependency versions, different flags). Promoting the same image means you deploy exactly what you tested.
61. Why pin
FROM node:22.11-sliminstead ofFROM node?Correct answer: So builds don't silently change when the base updates
nodemeansnode:latest, which jumps major versions over time. A pinned tag (or even a digest) keeps builds reproducible; update it deliberately.62. Why does image size matter?
Correct answer: Smaller images pull faster and carry less to attack
Every deploy and autoscaling event pulls the image. Fewer packages also means fewer vulnerabilities to patch.
63. Should the
.envfile with local secrets be committed to Git?Correct answer: No, add it to
.gitignoreand commit an example file insteadSecrets in Git spread to every clone and stay in history. A
.env.examplewith placeholder values documents which variables are needed.64. What is a required status check?
Correct answer: A CI check that must pass before a PR can be merged
Configured in branch protection, it turns CI from advice into a rule: a red pipeline blocks the merge button.
65. What is a flaky test?
Correct answer: A test that passes or fails without code changes
Timing, shared state and test order are common causes. Flaky tests train people to ignore red builds, so fix or quarantine them quickly.
66. How can a pipeline deploy only released versions?
Correct answer: Trigger the deploy job on version tags like
v1.2.0For example
on: push: tags: ['v*']in GitHub Actions. The tag also names the image, so the deployed version is easy to trace.67. Which user does a container's process run as by default?
Correct answer: root, unless the image sets another
USERRoot in a container is limited but still risky if it escapes. Official Node images include a
nodeuser; switch to it withUSER node.68. What does
docker inspect <container>show?Correct answer: Detailed JSON: config, mounts, network and state
It's the go-to command for checking env variables, mounts, IP addresses and exit codes.
docker statsshows live resource usage.69. Why can't two containers on the default bridge reach each other by name?
Correct answer: Name resolution works only on user-defined networks
Create a network (
docker network create app) and attach both containers; Compose does this automatically for its services.70. How do you follow logs from all services in a Compose project?
Correct answer:
docker compose logs -fOutput is interleaved and prefixed with the service name. Add a service name to see just one.
71.
docker run -p 5432:5432 postgresfails with "port is already allocated". Why?Correct answer: Something on the host already uses port 5432
Perhaps a local Postgres or another container. Map a different host port, like
-p 5433:5432; the container side stays the same.72. How are an image's layers and a container's changes stored?
Correct answer: Image layers are read-only; each container has a writable layer
Copy-on-write lets many containers share one image. Changes go into the container's own layer and disappear with it.
73. How does Docker Desktop run Linux containers on macOS or Windows?
Correct answer: Inside a lightweight Linux VM
Containers need a Linux kernel. That VM is why bind mounts can be slower and why
host.docker.internalexists to reach the host.74. What does
docker build --no-cachedo?Correct answer: Rebuilds every layer instead of reusing cached ones
Useful when a cached
RUN apt-get updateorRUN npm cilayer hides newer packages. Normally the cache is what makes rebuilds fast.75. What does
docker compose up --buildadd toup?Correct answer: Rebuilds service images before starting the containers
Without it, Compose reuses an existing image even if the Dockerfile or code changed, a common reason for "my change doesn't show up".