🐳

Docker & Containers MCQ

Test your Docker & Containers knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

What is a Docker container?

B

Correct Answer

A lightweight, standalone, executable package that includes an application and everything it needs to run, sharing the host OS kernel

Explanation

Containers package an application with its dependencies but share the host operating system's kernel, making them more lightweight than full virtual machines.

2

What is a Docker image?

B

Correct Answer

A read-only template containing instructions for creating a container, including the application code, libraries, and dependencies

Explanation

An image is the immutable blueprint from which one or more containers can be created; the container is the running instance of that image.

3

Which command is used to build a Docker image from a Dockerfile?

B

Correct Answer

docker build

Explanation

"docker build" reads instructions from a Dockerfile and builds an image, typically tagged with "-t name:tag".

4

What is the purpose of a Dockerfile?

B

Correct Answer

A text file containing a series of instructions used to automatically build a Docker image

Explanation

A Dockerfile defines step-by-step instructions (FROM, RUN, COPY, CMD, etc.) that Docker executes to produce an image.

5

Which command starts a new container from an image?

B

Correct Answer

docker run

Explanation

"docker run" creates and starts a new container from a specified image; "docker start" restarts an existing stopped container.

6

What does the "docker ps" command show?

B

Correct Answer

A list of currently running containers

Explanation

"docker ps" lists running containers by default; adding "-a" shows all containers including stopped ones.

7

What is the FROM instruction in a Dockerfile used for?

B

Correct Answer

To specify the base image upon which the new image will be built

Explanation

FROM defines the starting point/base image for subsequent instructions, such as "FROM ubuntu:22.04" or "FROM node:20-alpine".

8

What does the Dockerfile instruction "COPY" do?

A

Correct Answer

Copies files or directories from the build context into the image's filesystem

Explanation

COPY transfers files and directories from the build context (the directory passed to "docker build") into the image being built.

9

What is the difference between the Dockerfile "CMD" and "ENTRYPOINT" instructions, at a basic level?

B

Correct Answer

CMD specifies the default command to run when a container starts, which can be overridden by arguments passed to "docker run"

Explanation

CMD provides default arguments/command for the container that can be easily overridden, while ENTRYPOINT configures a command that is harder to override and CMD often supplies its default arguments.

10

What does "docker stop" do to a running container?

B

Correct Answer

Sends a signal to gracefully stop the container's main process, halting the container

Explanation

"docker stop" sends SIGTERM (then SIGKILL after a timeout) to stop the container's process gracefully; the container still exists and can be restarted with "docker start".

11

What is the purpose of "docker rm"?

A

Correct Answer

To remove a stopped container

Explanation

"docker rm <container>" deletes a stopped container; a running container must be stopped first or removed with "-f" to force removal.

12

What is the purpose of "docker rmi"?

B

Correct Answer

To remove a Docker image from local storage

Explanation

"docker rmi <image>" deletes a local image; it fails if a container is currently using that image unless forced.

13

What is Docker Hub?

B

Correct Answer

A cloud-based registry service for storing, sharing, and distributing Docker images

Explanation

Docker Hub is the default public registry where official and community images (like "nginx" or "ubuntu") are hosted and can be pulled with "docker pull".

14

What does "docker pull" do?

B

Correct Answer

Downloads an image from a registry to the local machine

Explanation

"docker pull <image>:<tag>" fetches an image (or a specific tag of it) from a registry such as Docker Hub.

15

What is the purpose of port mapping with "docker run -p 8080:80"?

B

Correct Answer

It forwards traffic from port 8080 on the host machine to port 80 inside the container

Explanation

The "-p hostPort:containerPort" flag publishes a container's port to the host, so requests to host port 8080 are forwarded to port 80 inside the container.

16

What does the "-d" flag do when used with "docker run -d"?

B

Correct Answer

Runs the container in detached mode, in the background

Explanation

"-d" (detached) runs the container in the background and prints the container ID, returning control of the terminal immediately.

17

What is a "volume" in Docker used for?

B

Correct Answer

To persist data generated by and used by containers, independent of the container's lifecycle

Explanation

Volumes provide persistent storage that exists outside a container's writable layer, so data survives container removal and can be shared between containers.

18

What does "docker exec -it <container> bash" do?

B

Correct Answer

Opens an interactive bash shell inside an already-running container

Explanation

"docker exec" runs an additional command inside a running container; "-it" allocates an interactive terminal, commonly used to open a shell for debugging.

19

What is the default isolation mechanism that allows multiple containers to run on the same host without interfering with each other's processes and filesystems?

B

Correct Answer

Linux namespaces and cgroups

Explanation

Docker uses Linux kernel features — namespaces for isolating views of resources (PIDs, network, mounts) and cgroups for limiting resource usage — to isolate containers.

20

What is the purpose of a ".dockerignore" file?

B

Correct Answer

To specify files and directories that should be excluded from the build context sent to the Docker daemon

Explanation

Similar to .gitignore, .dockerignore prevents unnecessary or sensitive files (like node_modules or .git) from being included in the build context, speeding up builds and reducing image size.

21

What does "docker-compose" (or "docker compose") primarily help you do?

B

Correct Answer

Define and run multi-container applications using a single YAML configuration file

Explanation

Docker Compose lets you define multiple services, networks, and volumes in a "docker-compose.yml" file and start/stop them together with simple commands.

22

In a "docker-compose.yml" file, what does the "services" key represent?

B

Correct Answer

The individual containers (applications) that make up the application, each with its own configuration

Explanation

Each entry under "services" defines a container — its image or build context, ports, volumes, environment variables, and dependencies.

23

What is the purpose of the "EXPOSE" instruction in a Dockerfile?

B

Correct Answer

It documents which ports the container listens on at runtime, serving as informational metadata (does not by itself publish the port)

Explanation

EXPOSE is documentation/metadata about which ports the application uses; actually publishing a port to the host still requires the "-p" flag on "docker run".

24

What is a "tag" in the context of a Docker image, e.g. "nginx:1.25"?

B

Correct Answer

A label that identifies a specific version or variant of an image, with "latest" being the default tag if none is specified

Explanation

Tags allow multiple versions of an image to coexist (e.g. "nginx:1.25", "nginx:latest"); if no tag is specified, Docker defaults to "latest".

25

What command shows logs output from a running container?

A

Correct Answer

docker logs <container>

Explanation

"docker logs <container>" fetches the stdout/stderr output of a container's main process; adding "-f" follows the log stream in real time.

26

What is the difference between a Docker container and a virtual machine, at a high level?

B

Correct Answer

A container shares the host OS kernel and is more lightweight, while a virtual machine includes its own full operating system and is managed by a hypervisor

Explanation

VMs virtualize hardware and run a complete guest OS via a hypervisor, which is heavier; containers virtualize at the OS level, sharing the host kernel, making them start faster and use fewer resources.

27

What does the Dockerfile instruction "WORKDIR" do?

A

Correct Answer

Sets the working directory for subsequent instructions like RUN, CMD, COPY in the image

Explanation

WORKDIR sets (and creates if needed) the working directory inside the image for all following instructions, avoiding repeated absolute paths.

28

What does the "docker images" command display?

A

Correct Answer

A list of locally stored images, including their repository, tag, and size

Explanation

"docker images" lists all images stored locally, showing repository name, tag, image ID, creation date, and size.

29

What is the purpose of the "ENV" instruction in a Dockerfile?

A

Correct Answer

To set environment variables that persist in the image and are available to the running container

Explanation

ENV sets environment variables both during the build process and within containers started from the resulting image.

30

What happens to data written inside a container's writable layer if the container is removed (without using volumes)?

B

Correct Answer

It is permanently lost, since the writable layer is removed along with the container

Explanation

A container's writable layer is ephemeral; without a volume or bind mount, any data written there is lost when the container is removed.

31

What is the purpose of the "docker network" command?

A

Correct Answer

To manage Docker networks, allowing containers to communicate with each other and the outside world

Explanation

"docker network" subcommands (create, ls, inspect, connect) manage virtual networks that containers use to communicate.

32

What does the default "bridge" network in Docker provide?

B

Correct Answer

A private internal network on the host where containers can communicate with each other via IP addresses, with NAT used for external access

Explanation

The default bridge network creates an isolated internal network; containers on it get their own IP addresses and can reach external networks via NAT through the host.

33

What is the purpose of "docker tag"?

A

Correct Answer

To create a new, additional name (tag) referencing an existing image

Explanation

"docker tag <source> <target>" creates an additional reference to the same image, often used before pushing to a specific registry/repository.

34

What does "docker push" do?

B

Correct Answer

Uploads a local image to a remote registry such as Docker Hub

Explanation

"docker push <repository>:<tag>" uploads a locally tagged image to a remote registry so it can be pulled by others.

35

What is the typical purpose of the "RUN" instruction in a Dockerfile?

B

Correct Answer

To execute a command during the image build process, creating a new layer with the result (e.g. installing packages)

Explanation

RUN executes commands at build time (like "apt-get install"), and the result is committed as a new image layer; this differs from CMD/ENTRYPOINT which run at container startup.

36

What is an Alpine-based image, and why is it commonly used as a base image?

B

Correct Answer

An image based on Alpine Linux, a minimal Linux distribution, chosen because it produces much smaller image sizes than full distributions like Ubuntu

Explanation

Alpine Linux is a minimal distribution (a few MB), so Alpine-based images (e.g. "node:20-alpine") significantly reduce image size compared to larger base distributions.

37

What does "docker container prune" do?

B

Correct Answer

Removes all stopped containers to free up space

Explanation

"docker container prune" removes containers that are in the "exited" or "created" state, helping clean up disk space.

38

What is the purpose of the "LABEL" instruction in a Dockerfile?

A

Correct Answer

To add metadata (key-value pairs) to an image, such as version, author, or description

Explanation

LABEL adds arbitrary metadata to an image (e.g. "LABEL maintainer=\"dev@example.com\""), useful for organization and automation tooling.

39

Why is it generally recommended to run only one main process per container?

B

Correct Answer

It follows the single-responsibility principle, simplifying scaling, logging, and lifecycle management — each service can be scaled, restarted, and monitored independently

Explanation

While technically possible to run multiple processes, the convention of one process per container simplifies dependency management, scaling, and failure isolation in container orchestration.

40

What information does "docker inspect <container>" provide?

B

Correct Answer

Detailed low-level configuration and state information about a container or image in JSON format, including network settings, mounts, and environment variables

Explanation

"docker inspect" returns a detailed JSON document describing a container's (or image's/volume's/network's) full configuration and current state.

1

What is a "multi-stage build" in Docker, and why is it useful?

B

Correct Answer

A Dockerfile technique using multiple FROM statements where artifacts from earlier stages can be copied into later stages, allowing build tools to be excluded from the final image to reduce its size

Explanation

Multi-stage builds let you compile/build in one stage (with full toolchains) and copy only the final artifacts into a minimal runtime stage, significantly reducing the final image size.

2

What is the difference between a Docker "volume" and a "bind mount"?

B

Correct Answer

A volume is managed by Docker and stored in a Docker-controlled location, while a bind mount maps a specific path on the host filesystem directly into the container

Explanation

Volumes are fully managed by Docker (location abstracted away, portable), while bind mounts depend on the host's directory structure, giving direct access but tying the container to a specific host path.

3

Why does Docker use a layered filesystem for images, and what benefit does this provide?

B

Correct Answer

Each instruction in a Dockerfile creates a new layer; layers are cached and can be shared between images, speeding up builds and reducing storage by reusing unchanged layers

Explanation

Layer caching means unchanged instructions don't need to be re-executed on rebuild, and multiple images sharing a base can reuse the same underlying layers on disk, saving space and build time.

4

Why is the ordering of instructions in a Dockerfile important for build performance?

B

Correct Answer

Docker caches layers and invalidates the cache for a layer and all subsequent layers once a change is detected, so placing rarely-changing steps (dependency installs) before frequently-changing ones (copying source code) maximizes cache reuse

Explanation

Since a cache miss on one layer invalidates all subsequent layers, placing stable steps (installing dependencies) early and frequently-changing steps (copying app code) later avoids unnecessary re-execution of expensive steps.

5

What is the purpose of "docker-compose up -d" versus "docker-compose up"?

B

Correct Answer

"docker-compose up" runs services in the foreground, streaming combined logs to the terminal, while "-d" runs them in detached/background mode

Explanation

The "-d" flag for Compose runs containers in the background (detached), similar to "docker run -d", freeing up the terminal.

6

What is the purpose of "healthcheck" configuration in Docker?

B

Correct Answer

It defines a command Docker periodically runs inside the container to determine if the application is functioning correctly, reporting status as healthy, unhealthy, or starting

Explanation

HEALTHCHECK instructions (or compose healthcheck config) let Docker monitor container health by periodically running a test command, which orchestration tools can use to restart unhealthy containers.

7

What does the "depends_on" key in docker-compose.yml control?

B

Correct Answer

It controls the order in which Compose starts/stops containers, but by default only waits for the container to start, not for the application inside to be ready

Explanation

depends_on controls startup/shutdown order at the container level; it does not wait for the application inside the container to be ready to accept connections — health checks or wait-scripts are needed for that.

8

What is the effect of running a container with "--rm"?

A

Correct Answer

The container is automatically removed once it exits

Explanation

"--rm" automatically cleans up the container's filesystem and removes it from "docker ps -a" once it stops, useful for temporary/one-off containers.

9

What is the purpose of "docker-compose down -v"?

B

Correct Answer

Stops and removes containers, networks, and also removes named volumes declared in the "volumes" section of the compose file

Explanation

"docker-compose down" stops and removes containers and networks; adding "-v" additionally removes named volumes, which can permanently delete persisted data.

10

How can you limit the amount of memory a container can use?

B

Correct Answer

Using the "--memory" (or "-m") flag with "docker run", e.g. "docker run -m 512m", which is enforced via cgroups

Explanation

Docker uses cgroups to enforce resource limits like "--memory" and "--cpus", preventing a single container from consuming all of the host's resources.

11

What is the purpose of "ARG" in a Dockerfile, and how does it differ from "ENV"?

B

Correct Answer

ARG defines build-time variables that are only available during the image build (and not in the running container) unless also set as ENV, while ENV variables persist into the running container

Explanation

ARG values (passed via "--build-arg") are accessible only during the build process by default; ENV values are baked into the image and available to containers at runtime.

12

What does "docker system prune -a" do, and why should it be used carefully?

B

Correct Answer

It removes all stopped containers, unused networks, dangling and unused images, and build cache — potentially deleting images that are not currently used by any container but might be needed later

Explanation

"docker system prune -a" aggressively reclaims disk space by removing all unused data, including images not referenced by any container, which could require re-downloading or rebuilding them later.

13

What is the purpose of naming a Docker network and attaching multiple containers to it (instead of using the default bridge)?

B

Correct Answer

A user-defined network provides automatic DNS-based service discovery, allowing containers to reach each other by container/service name rather than requiring static IP addresses

Explanation

On user-defined bridge networks, Docker provides automatic DNS resolution by container name, so services can reference each other by name (e.g. "db") instead of hardcoded IPs.

14

What does it mean for a Docker image layer to be "cached", and what invalidates that cache during a rebuild?

B

Correct Answer

Docker reuses a previously built layer if the instruction and its inputs (e.g. files being copied) are unchanged; a change to the instruction itself, or to files referenced by COPY/ADD, invalidates that layer's cache and all subsequent layers

Explanation

Docker computes a checksum of each instruction (and file contents for COPY/ADD); if these match a previous build, the cached layer is reused, otherwise that layer and everything after it must be rebuilt.

15

What is the difference between "CMD [\"executable\", \"param\"]" (exec form) and "CMD executable param" (shell form) in a Dockerfile?

B

Correct Answer

Exec form runs the command directly without a shell (so the process becomes PID 1 and properly receives signals like SIGTERM), while shell form wraps the command in "/bin/sh -c", which can interfere with signal handling

Explanation

Exec form avoids an extra shell process, making the application PID 1 and able to receive signals (like SIGTERM from "docker stop") directly, while shell form runs the command through "/bin/sh -c", which may not forward signals properly.

16

How does "docker-compose" handle environment-specific configuration, e.g. using multiple compose files?

B

Correct Answer

Multiple compose files can be merged using the "-f" flag (e.g. "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up"), where later files override or extend settings from earlier ones

Explanation

Compose supports layering multiple YAML files via "-f", commonly used to define a base configuration plus environment-specific overrides (e.g. for development vs production).

17

What is the purpose of "docker cp"?

B

Correct Answer

To copy files or directories between a container's filesystem and the local host filesystem

Explanation

"docker cp <container>:<path> <hostpath>" (or vice versa) copies files between a running or stopped container and the host filesystem.

18

Why might "RUN apt-get update && apt-get install -y <package>" be written on a single RUN line rather than two separate RUN lines?

B

Correct Answer

If "apt-get update" is cached from a previous build but the package list has changed upstream, a separate "apt-get install" could install outdated or missing packages; combining them ensures the update and install always run together as one cached unit

Explanation

If "apt-get update" is its own cached layer, a later "apt-get install" might use a stale package index from the cached update step; chaining them with "&&" ensures both run together whenever either changes, avoiding "package not found" errors.

19

What is a "named volume" in Docker, and how does it differ from an anonymous volume?

B

Correct Answer

A named volume is created with a specific, reusable identifier (e.g. "docker volume create mydata") that persists and can be referenced by multiple containers, while an anonymous volume gets a random ID and is harder to reference later

Explanation

Named volumes have a human-readable identifier that makes them easy to reuse and reference across containers/restarts, while anonymous volumes are given a generated hash name and are harder to manage explicitly.

20

What does "docker stats" provide?

B

Correct Answer

A live, continuously updating stream of resource usage statistics (CPU, memory, network I/O) for running containers

Explanation

"docker stats" shows a real-time stream of resource usage metrics for one or more containers, useful for monitoring performance.

21

What problem does setting a non-root "USER" instruction in a Dockerfile address?

B

Correct Answer

By default, containers run as root, which poses a security risk if the application is compromised; switching to a non-root user limits the potential damage from container escapes or vulnerabilities

Explanation

Running as root inside a container increases the blast radius of a potential vulnerability, especially if container isolation is somehow bypassed; the USER instruction switches to a less-privileged user for defense in depth.

22

What is the purpose of an "init" system or "tini" in some Docker containers?

B

Correct Answer

To act as PID 1 in the container, properly reaping zombie processes and forwarding signals to the main application, which a simple application process might not handle correctly

Explanation

PID 1 has special responsibilities (reaping zombie child processes, handling signals); lightweight init systems like tini handle these correctly when the main application isn't designed to run as PID 1.

23

How does Docker determine which platform/architecture (e.g. amd64 vs arm64) an image is built for, and why does this matter for multi-platform builds?

B

Correct Answer

Images are built for a specific CPU architecture/OS combination; tools like "docker buildx" can build and push a single manifest referencing multiple architecture-specific images, so the correct one is automatically pulled based on the host's platform

Explanation

buildx with QEMU emulation can build images for architectures different from the host, and a multi-arch manifest list lets "docker pull" automatically select the image variant matching the pulling host's architecture.

24

What does the "--network host" option do when running a container?

B

Correct Answer

It removes network isolation between the container and the host, so the container shares the host's network stack directly, including its IP address and ports

Explanation

"--network host" makes the container use the host's network namespace directly — ports opened in the container are immediately available on the host without explicit "-p" mapping, but this reduces isolation.

25

What is the purpose of "docker volume create" with a specified driver, e.g. for cloud storage?

B

Correct Answer

Volume drivers allow Docker volumes to be backed by different storage backends (such as NFS, cloud block storage, or distributed filesystems), abstracting where the data is actually stored

Explanation

Volume plugins/drivers let Docker volumes be backed by various storage systems (e.g. cloud-based or networked storage), enabling persistent data to survive even if the host itself is replaced.

26

What does "restart: unless-stopped" mean in a docker-compose service definition?

B

Correct Answer

The container automatically restarts if it stops/crashes or on daemon restart, unless it was explicitly stopped by the user

Explanation

"unless-stopped" restarts the container on failure or Docker daemon restart, but respects an explicit "docker stop" — the container will not be automatically restarted after that until manually started again.

27

Why might you use "COPY --from=<stage>" in a multi-stage Dockerfile?

B

Correct Answer

To copy specific files or build artifacts produced in an earlier build stage into the current stage, without bringing along that stage's build tools or intermediate files

Explanation

"COPY --from=builder /app/dist ./dist" lets a final, minimal stage include only compiled output from an earlier (often larger) build stage, keeping the final image small.

28

What is the difference between "docker stop" and "docker kill"?

B

Correct Answer

"docker stop" sends SIGTERM and waits a grace period before sending SIGKILL, allowing graceful shutdown, while "docker kill" sends SIGKILL (or a specified signal) immediately, forcefully terminating the container

Explanation

docker stop gives the process a chance to clean up (close connections, flush data) before forcing termination, whereas docker kill terminates immediately without that grace period.

29

What is the purpose of "docker-compose.override.yml"?

B

Correct Answer

Compose automatically merges it with "docker-compose.yml" by default, commonly used to provide local development overrides (like exposing extra ports or mounting source code) without modifying the base file

Explanation

Compose automatically loads "docker-compose.override.yml" alongside "docker-compose.yml" if present, letting developers customize behavior locally (e.g. enabling debug ports or live-reload mounts) without altering the shared base configuration.

30

What does "docker build --no-cache" do, and when might it be needed?

B

Correct Answer

It forces every instruction in the Dockerfile to be re-executed from scratch, ignoring any cached layers — useful when cached layers might be stale, e.g. if a RUN command fetches external resources that have changed

Explanation

"--no-cache" ensures a completely fresh build, useful when cached layers (like "apt-get update" results or downloaded dependencies) might no longer reflect the current state of external resources.

31

What is the significance of the "PID 1" process inside a container regarding "docker stop"?

B

Correct Answer

"docker stop" sends SIGTERM to PID 1 inside the container; if PID 1 does not handle or forward this signal properly (e.g. when using shell form CMD), the application may not shut down gracefully and Docker eventually sends SIGKILL

Explanation

Since signals from "docker stop" target PID 1, applications (or wrapper scripts) that don't correctly handle SIGTERM as PID 1 may be forcefully killed after the timeout instead of shutting down cleanly.

32

What does the ".env" file do in a docker-compose project by default?

B

Correct Answer

Compose automatically reads variables from a ".env" file in the project directory and substitutes them into the docker-compose.yml file (e.g. "${DB_PASSWORD}")

Explanation

Compose automatically loads a ".env" file from the project root and substitutes its variables into the compose file using "${VAR}" syntax, useful for keeping configuration/secrets out of version control.

33

Why might a containerized application behave differently regarding available memory than expected, even with "--memory" not set?

B

Correct Answer

Without an explicit limit, a container can see and potentially use the host's total memory, which can mislead applications (especially JVM-based ones) that auto-tune based on detected available memory, sometimes causing them to over-allocate

Explanation

Without cgroup memory limits, "/proc/meminfo" inside a container can report the host's total memory, which can cause memory-aware applications to size caches or heaps based on incorrect assumptions about available resources.

34

What is the purpose of "docker save" and "docker load"?

B

Correct Answer

"docker save" exports an image to a tar archive file, and "docker load" imports an image from such a tar archive — useful for transferring images without a registry

Explanation

"docker save <image> > image.tar" and "docker load < image.tar" allow moving images between systems offline, e.g. via a USB drive or air-gapped environment, without needing a registry.

35

What is the role of "buildkit" in modern Docker builds?

B

Correct Answer

BuildKit is an improved build engine offering features like better caching, parallel build stage execution, and build secrets/SSH forwarding, and is enabled by default in modern Docker versions

Explanation

BuildKit, the default builder in recent Docker versions, improves on the legacy builder with more efficient caching, concurrent stage builds, and additional features like "--secret" for securely passing build-time credentials.

36

What is the difference between scaling a service with "docker-compose up --scale web=3" and defining 3 separate services in the compose file?

B

Correct Answer

"--scale" runs multiple replicas of the same service definition (sharing the same image/config), useful for load distribution, while defining separate services allows each to have distinct configurations

Explanation

"--scale" creates multiple container instances from the same service definition (useful with a load balancer in front), whereas defining separate services is appropriate when each instance needs different configuration.

37

What is the purpose of "docker logout" and credential storage when working with private registries?

B

Correct Answer

"docker login" stores registry credentials (often via a credential helper or in a config file) so subsequent pulls/pushes are authenticated automatically; "docker logout" removes these stored credentials for a registry

Explanation

After "docker login", credentials are cached (ideally via a secure credential helper) so future operations against that registry don't require re-authentication; "docker logout" clears those cached credentials.

38

What does "docker run --env-file <file>" allow you to do?

A

Correct Answer

Load multiple environment variables from a file into the container, instead of specifying each with individual "-e" flags

Explanation

"--env-file" reads key=value pairs from a file and sets them as environment variables in the container, convenient for managing many variables without long command lines.

39

Why might you use "docker-compose config" before running "docker-compose up"?

B

Correct Answer

It validates and resolves the final merged Compose configuration (including variable substitution and merged override files), helping catch syntax errors or misconfigurations before starting containers

Explanation

"docker-compose config" prints the fully resolved configuration (after merging files and substituting variables), useful for debugging what Compose will actually apply.

40

What is the effect of setting "read_only: true" for a service in docker-compose?

A

Correct Answer

The container's root filesystem is mounted as read-only, preventing writes anywhere except explicitly mounted writable volumes/tmpfs

Explanation

A read-only root filesystem prevents an application (or attacker) from writing to most of the container's filesystem, a hardening technique; applications needing to write temporary files must be given explicit writable volumes or tmpfs mounts.

1

How do Linux namespaces contribute to container isolation, and name at least the type that isolates process IDs?

B

Correct Answer

Namespaces partition kernel resources so one set of processes sees one view of a resource while others see a different view; the PID namespace, for example, makes a container's process appear as PID 1 even though it has a different host PID

Explanation

Linux namespaces (PID, network, mount, UTS, IPC, user) give each container an isolated view of system resources; the PID namespace specifically isolates the process tree so containers have their own PID 1.

2

What is the purpose of "cgroups" (control groups) in the context of Docker, distinct from namespaces?

B

Correct Answer

Cgroups limit, account for, and isolate the resource usage (CPU, memory, disk I/O, etc.) of a group of processes, enforcing resource constraints like "--memory" and "--cpus"

Explanation

While namespaces provide isolated views of resources, cgroups enforce limits on how much of those resources (CPU, memory, I/O bandwidth) a group of processes can consume, preventing one container from starving others.

3

What is the difference between the "overlay2" storage driver and using bind mounts for a container's root filesystem?

B

Correct Answer

overlay2 layers image filesystems, combining read-only image layers with a writable container layer via union mounts; bind mounts instead share specific host directories directly with a container, independent of image layering

Explanation

overlay2 implements the union filesystem that stacks image layers and a container's writable layer transparently, whereas bind mounts are a separate mechanism for exposing specific host paths inside the container, often used for persistent or shared data.

4

What security concern arises from mounting the Docker socket ("/var/run/docker.sock") into a container, and why is this sometimes called "Docker-in-Docker via socket mounting"?

B

Correct Answer

A container with access to the host's Docker socket can issue commands to the host's Docker daemon, effectively granting it root-equivalent control over the host — a container escape vector if the application is compromised

Explanation

The Docker daemon runs as root, so any process that can talk to its socket can create privileged containers, mount the host filesystem, and effectively gain root on the host — making this a significant privilege escalation risk if exposed to untrusted code.

5

What does "docker exec" rely on internally to enter a running container's namespaces, and how does this differ conceptually from starting a new container?

B

Correct Answer

"docker exec" uses "setns" to join the existing namespaces (PID, network, mount, etc.) of an already-running container's init process, running a new process in that same isolated environment rather than creating a new one

Explanation

Unlike "docker run" which sets up new namespaces, "docker exec" enters the namespaces already established for the target container's init process, so the new process shares that container's filesystem, network, and process tree view.

6

What is "container escape", and what are common mitigations?

B

Correct Answer

A container escape is when a process gains access to host resources outside its isolation (via a kernel bug, privileged mode, or bad mounts); mitigations include avoiding "--privileged", running as non-root, using seccomp/AppArmor, and patching the kernel

Explanation

Because containers share the host kernel, a vulnerability in the kernel or an overly permissive configuration (privileged mode, dangerous capabilities, exposed sockets) can allow a process to break out of its container boundary and affect the host or other containers.

7

What does the "--cap-add" and "--cap-drop" flags control, and why might dropping capabilities improve security?

B

Correct Answer

Linux capabilities split root's privileges into distinct units (e.g. NET_ADMIN, SYS_ADMIN); Docker grants a limited default set, and "--cap-drop"/"--cap-add" let you remove or add specific capabilities, reducing a compromised container's attack surface

Explanation

By default containers run with a reduced capability set rather than full root privileges; explicitly dropping further unneeded capabilities (like "ALL" then adding back only what's required) follows the principle of least privilege, limiting what an attacker could do if the container is compromised.

8

How does Docker's "seccomp" default profile improve container security?

B

Correct Answer

It restricts the set of system calls (syscalls) a containerized process can make to the kernel, blocking dangerous or unnecessary syscalls that could be used to exploit kernel vulnerabilities or escalate privileges

Explanation

seccomp (secure computing mode) filters allow only a whitelisted set of syscalls; Docker's default profile blocks dangerous syscalls (like certain kernel module operations) that most containerized applications never legitimately need, reducing the kernel attack surface.

9

What is the significance of "OCI" (Open Container Initiative) specifications for the Docker ecosystem?

B

Correct Answer

OCI defines open standards for container image formats and runtimes, allowing images built by Docker to run on other OCI-compliant runtimes (like containerd or CRI-O) and vice versa, promoting interoperability across the container ecosystem

Explanation

The OCI Image Specification and Runtime Specification standardize how container images are packaged and how runtimes execute them, enabling tools across the ecosystem (Docker, Kubernetes/containerd, Podman) to interoperate.

10

Why can excessive image layers (from many separate RUN/COPY instructions) negatively affect both image size and build performance, and how do multi-stage builds and combining commands address this?

B

Correct Answer

Each layer can retain files even if a later layer "deletes" them, since earlier layers are immutable; combining commands into fewer RUN instructions with cleanup in the same step avoids this, and multi-stage builds discard build-only layers entirely

Explanation

Because layers are immutable and stacked, deleting a file in a later layer doesn't remove it from the image's total size — it just hides it; combining install-and-cleanup into a single RUN avoids ever persisting the unwanted files, and multi-stage builds avoid shipping build-only layers altogether.

11

How does Docker's default bridge network differ from user-defined bridge networks regarding inter-container communication, particularly around "--link" (legacy) versus modern approaches?

B

Correct Answer

On the default bridge network, containers can only communicate via IP addresses (no automatic DNS) and the legacy "--link" flag was needed for name-based linking; user-defined bridge networks provide automatic DNS-based service discovery without "--link"

Explanation

The default bridge network lacks automatic DNS resolution between containers (historically requiring "--link", now deprecated), while user-defined networks automatically register container names in an embedded DNS server, making "--link" unnecessary.

12

What is the purpose of "docker manifest" and manifest lists in supporting multi-architecture images?

B

Correct Answer

A manifest list is a "fat manifest" that references multiple platform-specific image manifests (e.g. amd64, arm64) under a single tag, allowing "docker pull" to automatically select the correct image variant for the host's architecture

Explanation

A manifest list (image index) groups multiple architecture-specific manifests under one tag/reference; the client's platform determines which underlying manifest (and thus image) is actually pulled, enabling a single tag to work across architectures.

13

Why might setting "ulimits" be necessary for certain containerized applications, and what is an example of a ulimit relevant to containers?

B

Correct Answer

ulimits set per-process resource limits, such as the maximum open file descriptors ("nofile"); applications opening many connections or files may hit default limits inherited from the container runtime and need these raised explicitly

Explanation

ulimits (like "nofile" for open file descriptors, or "nproc" for processes) are a Linux mechanism for per-process resource limits; containers inherit defaults that may be too low for high-concurrency applications, so they can be explicitly raised via "--ulimit".

14

What does "docker build --secret" address, and what problem does it solve compared to using "ARG" for sensitive values like API keys?

B

Correct Answer

"--secret" mounts a secret file only during a specific RUN instruction without persisting it in any layer, whereas "ARG" values can end up cached in build history/layers and be extracted from the final image, leaking sensitive data

Explanation

Build arguments (ARG) can be inspected via "docker history" or remain in intermediate layers, risking credential leakage; BuildKit's "--secret" mounts sensitive files transiently during a build step without writing them into any layer.

15

What is the difference between "docker run --restart=always" and an orchestrator (like Kubernetes or Swarm) restarting a failed container?

B

Correct Answer

"--restart=always" restarts a container on the same host if it stops, with no cross-host failover or scaling — an orchestrator can reschedule containers onto healthy hosts, scale replicas, and manage rolling updates cluster-wide

Explanation

Docker's restart policies operate within a single host's Docker daemon, while orchestrators provide cluster-wide scheduling, health-based rescheduling across nodes, scaling, and rolling updates — a fundamentally larger scope of "self-healing".

16

How does the choice of base image affect the security and size trade-offs of a production image, particularly regarding "distroless" images?

B

Correct Answer

Distroless images contain only the application and its runtime dependencies, deliberately excluding package managers, shells, and other OS utilities — this reduces size and attack surface but complicates debugging since shell-based tools are unavailable

Explanation

Distroless images strip out shells, package managers, and other binaries not needed at runtime, minimizing both size and the tools available to an attacker who gains code execution, at the cost of making interactive debugging ("docker exec ... sh") harder.

17

What is "BuildKit's" cache mount feature (e.g. "RUN --mount=type=cache,target=/root/.cache") used for?

B

Correct Answer

It persists a directory (like a package manager cache) across builds without including it in the final image layer, speeding up repeated builds (e.g. avoiding re-downloading dependencies) while keeping the image itself free of cache artifacts

Explanation

Cache mounts let build steps (like "npm install" or "pip install") reuse downloaded packages between builds via a persistent cache directory, without that cache becoming part of any image layer, combining fast rebuilds with small final images.

18

Why is pinning exact image digests (e.g. "FROM node@sha256:abcd...") sometimes preferred over tags like "FROM node:20" in production Dockerfiles?

B

Correct Answer

A tag like "node:20" can be reassigned by its publisher to point to different content over time (mutable), while a digest uniquely and immutably identifies exact image content, ensuring reproducible builds and guarding against supply-chain tampering

Explanation

Tags are mutable pointers that can be reassigned by the image publisher, so the same tag might resolve to different content over time; a content-addressed digest guarantees you always get the exact same bytes, important for reproducibility and supply-chain security.

19

What does "docker events" allow you to do, and how might it be used in monitoring or automation?

B

Correct Answer

It streams real-time events from the Docker daemon (container start/stop/die, image pull, network create, etc.), which can be consumed by external tools to trigger automated responses, logging, or alerting based on Docker lifecycle changes

Explanation

"docker events" provides a live stream of daemon-level events, which monitoring/automation tools can subscribe to in order to react to container lifecycle changes (e.g. automatically updating a reverse proxy configuration when containers start/stop).

20

In a CI/CD pipeline, why might "docker build" results vary between runs even with an identical Dockerfile and source code, and what techniques help ensure reproducibility?

B

Correct Answer

Non-determinism can arise from unpinned image tags or package versions resolving to newer releases over time, embedded timestamps, or network-dependent steps; pinning images by digest and locking dependency versions improves reproducibility

Explanation

Mutable references (tags, "latest" dependency versions) and non-deterministic build steps (timestamps, network calls returning different data over time) can cause the same Dockerfile to produce different images on different days; pinning versions/digests and using lockfiles reduces this variability.