Title: Docker Containers — LearnCoachAssist

Q: What is Docker?
A: Docker is an open-source platform that automates the deployment of applications inside lightweight, portable containers. Containers package an application with all its dependencies, ensuring it runs consistently across different environments.

Q: What is a Docker container?
A: A Docker container is a runnable instance of a Docker image. It is an isolated process that shares the host OS kernel but has its own filesystem, networking, and process space. Containers are ephemeral by default.

Q: What is a Docker image?
A: A Docker image is a read-only template used to create containers. It consists of layered filesystems built from a Dockerfile. Images are stored in registries and can be tagged with versions like myapp:1.0.

Q: What does the FROM instruction do in a Dockerfile?
A: FROM sets the base image for subsequent instructions. It must be the first instruction in a Dockerfile (aside from ARG).
Example: FROM python:3.11-slim
You can also use FROM scratch to start with an empty image.

Q: What does the RUN instruction do in a Dockerfile?
A: RUN executes a command during the image build process and commits the result as a new layer.
Example: RUN apt-get update && apt-get install -y curl
Best practice: chain commands with && to reduce layers.

Q: What is the difference between COPY and ADD in a Dockerfile?
A: COPY simply copies files/directories from the build context into the image. ADD does the same but also supports:
- Automatic extraction of local .tar archives
- Fetching files from remote URLs
Best practice: prefer COPY unless you need ADD's extra features.

Q: What is the difference between CMD and ENTRYPOINT?
A: CMD provides default arguments that can be overridden at runtime. ENTRYPOINT sets the main executable that always runs.
When both are used, CMD supplies default arguments to ENTRYPOINT:
ENTRYPOINT ["python"]
CMD ["app.py"]

Q: What does the EXPOSE instruction do?
A: EXPOSE documents which ports the container listens on at runtime. It does not actually publish the port.
Example: EXPOSE 8080
To publish ports, use docker run -p 8080:8080 at runtime.

Q: What does the WORKDIR instruction do?
A: WORKDIR sets the working directory for subsequent RUN, CMD, ENTRYPOINT, COPY, and ADD instructions.
Example: WORKDIR /app
If the directory doesn't exist, it is created automatically.

Q: What is the difference between ENV and ARG in a Dockerfile?
A: ENV sets environment variables that persist in the running container.
ARG defines build-time variables available only during the build.
Example:
ARG VERSION=1.0
ENV APP_ENV=production

Q: What does the LABEL instruction do?
A: LABEL adds metadata to an image as key-value pairs.
Example: LABEL maintainer="dev@example.com" version="1.0"
Labels can be inspected with docker inspect and are useful for automation and documentation.

Q: What does the VOLUME instruction do in a Dockerfile?
A: VOLUME creates a mount point and marks it as holding externally mounted volumes.
Example: VOLUME /data
Data in volumes persists beyond the container lifecycle and is managed by Docker on the host filesystem.

Q: What does the USER instruction do?
A: USER sets the user and optionally the group for running subsequent instructions and the container process.
Example: USER appuser:appgroup
This is a security best practice to avoid running containers as root.

Q: What does the HEALTHCHECK instruction do?
A: HEALTHCHECK tells Docker how to test if a container is still working.
Example:
HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -f http://localhost/ || exit 1
Container status shows as healthy, unhealthy, or starting.

Q: What is a Docker volume?
A: A Docker volume is a persistent storage mechanism managed by Docker, stored outside the container's writable layer.
Types:
- Named volumes: docker volume create mydata
- Bind mounts: map a host path directly
- tmpfs mounts: stored in memory only

Q: What are Docker image layers?
A: Each instruction in a Dockerfile (FROM, RUN, COPY, etc.) creates a read-only layer. Layers are stacked and cached. When a container runs, a thin writable layer is added on top. Unchanged layers are shared across images to save disk space.

Q: How does Docker build caching work?
A: Docker caches each layer during a build. If an instruction and its context haven't changed, the cached layer is reused.
Best practices:
- Put rarely-changing instructions (e.g., RUN apt-get) early
- Put frequently-changing files (e.g., COPY . .) late

Q: What is a multi-stage build in Docker?
A: A multi-stage build uses multiple FROM statements in one Dockerfile. Each stage can use a different base image. You copy only needed artifacts from earlier stages into the final image, resulting in smaller production images.
Example:
FROM node:18 AS builder
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html

Q: What is Docker Hub?
A: Docker Hub is Docker's official public registry for storing and distributing container images. It offers:
- Official images (e.g., nginx, postgres)
- Automated builds from GitHub/Bitbucket
- Public and private repositories
- Image vulnerability scanning

Q: How do you use a private Docker registry?
A: You can run a private registry with docker run -d -p 5000:5000 registry:2. To push images:
docker tag myapp localhost:5000/myapp
docker push localhost:5000/myapp
For authentication, configure TLS and docker login.

Q: What is a .dockerignore file?
A: A .dockerignore file excludes files and directories from the build context sent to the Docker daemon. This speeds up builds and prevents sensitive files from being included.
Example:
node_modules
.git
*.md
.env

Q: What does docker run do?
A: docker run creates and starts a new container from an image.
Common flags:
- -d: detached mode (background)
- -p 8080:80: port mapping
- -v data:/app: volume mount
- --name myapp: assign a name
- -e KEY=val: set env variable

Q: What does docker build do?
A: docker build creates an image from a Dockerfile.
Example: docker build -t myapp:1.0 .
Key flags:
- -t: tag the image
- -f: specify Dockerfile path
- --no-cache: ignore cache
- --build-arg: pass build arguments

Q: What does docker exec do?
A: docker exec runs a command inside a running container.
Example: docker exec -it mycontainer bash
Flags:
- -i: interactive (keep STDIN open)
- -t: allocate a pseudo-TTY
- -u root: run as specific user

Q: What does docker ps do?
A: docker ps lists running containers.
Key flags:
- -a: show all containers (including stopped)
- -q: show only container IDs
- --filter: filter output (e.g., --filter status=exited)

Q: What does docker logs do?
A: docker logs fetches the stdout/stderr output of a container.
Key flags:
- -f: follow log output in real time
- --tail 100: show last 100 lines
- --since 1h: logs from the last hour
- -t: show timestamps

Q: How do you stop and remove a container?
A: Stop a running container gracefully:
docker stop <container> (sends SIGTERM, then SIGKILL after timeout)
Remove a stopped container:
docker rm <container>
Force remove a running container:
docker rm -f <container>
Remove all stopped containers:
docker container prune

Q: What do docker pull and docker push do?
A: docker pull downloads an image from a registry:
docker pull nginx:latest
docker push uploads a tagged image to a registry:
docker push myrepo/myapp:1.0
You must be logged in via docker login to push to most registries.

Q: What does docker inspect do?
A: docker inspect returns detailed JSON metadata about Docker objects (containers, images, volumes, networks).
Example: docker inspect mycontainer
Use --format to extract specific fields:
docker inspect --format '{{.NetworkSettings.IPAddress}}' mycontainer

Q: What is Docker networking?
A: Docker provides several network drivers for container communication:
- bridge: default; isolated network on a single host
- host: shares the host's network stack
- overlay: multi-host networking for Swarm
- none: no networking

Q: What is the bridge network in Docker?
A: The bridge network is Docker's default network driver. Containers on the same bridge can communicate by IP. User-defined bridges also support DNS resolution by container name.
Create one with: docker network create mynet
Connect a container: docker run --network mynet myapp

Q: What is the host network driver in Docker?
A: The host network driver removes network isolation and lets the container share the host's network namespace directly.
Usage: docker run --network host myapp
The container uses the host's IP and ports. Useful for performance but reduces isolation. Only works on Linux.

Q: What is the overlay network in Docker?
A: The overlay network enables communication between containers running on different Docker hosts in a Swarm cluster. It uses VXLAN encapsulation to create a distributed network.
Create with: docker network create --driver overlay myoverlay

Q: What is Docker Compose?
A: Docker Compose is a tool for defining and running multi-container applications using a YAML file (docker-compose.yml). It manages services, networks, and volumes together.
Key commands:
- docker compose up -d
- docker compose down
- docker compose logs

Q: How do you define services in Docker Compose?
A: Services are defined under the services key in docker-compose.yml:
services:
  web:
    build: .
    ports:
      - "8080:80"
  db:
    image: postgres:15
    volumes:
      - pgdata:/var/lib/postgresql/data

Q: How does depends_on work in Docker Compose?
A: depends_on controls service startup order. It ensures a service starts only after its dependencies.
Example:
services:
  web:
    depends_on:
      - db
Note: it only waits for the container to start, not for the service to be "ready." Use healthchecks for readiness.

Q: How do you set environment variables in Docker Compose?
A: There are multiple ways:
- Inline: environment:
  - DB_HOST=db
- From file: env_file:
  - .env
- Shell variables: ${VARIABLE} syntax in the YAML
The .env file in the project root is loaded automatically.

Q: How do you define networks in Docker Compose?
A: Networks are declared at the top level and referenced by services:
services:
  web:
    networks:
      - frontend
  api:
    networks:
      - frontend
      - backend
networks:
  frontend:
  backend:
Services on the same network can resolve each other by name.

Q: How do you define volumes in Docker Compose?
A: Named volumes are declared at the top level and mounted in services:
services:
  db:
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:
You can also use bind mounts: ./local/path:/container/path

Q: What is the container lifecycle in Docker?
A: A container goes through these states:
- Created: docker create
- Running: docker start / docker run
- Paused: docker pause
- Stopped: docker stop (SIGTERM → SIGKILL)
- Removed: docker rm

Q: How do you set resource limits on a Docker container?
A: Use flags with docker run:
- Memory: --memory=512m
- CPU: --cpus=1.5
- Memory swap: --memory-swap=1g
In Compose:
deploy:
  resources:
    limits:
      memory: 512M
      cpus: "1.5"

Q: What are Docker security best practices?
A: Key security practices:
- Run containers as a non-root user (USER instruction)
- Use minimal base images (e.g., alpine, distroless)
- Scan images for vulnerabilities (docker scout)
- Don't store secrets in images; use Docker secrets or env vars
- Enable read-only filesystems: --read-only
- Drop unnecessary Linux capabilities

Q: How do you pass environment variables to a container at runtime?
A: Use the -e flag or --env-file:
docker run -e DB_HOST=localhost -e DB_PORT=5432 myapp
docker run --env-file .env myapp
Variables set with -e override those defined in the Dockerfile's ENV instruction.

Q: What is the best practice for ordering Dockerfile instructions?
A: Order instructions from least to most frequently changing to maximize cache hits:
1. FROM base image
2. RUN install system dependencies
3. COPY dependency files (e.g., package.json)
4. RUN install app dependencies
5. COPY application source code
6. CMD / ENTRYPOINT

Q: Why should you use minimal base images?
A: Minimal base images like alpine (5 MB) or distroless images reduce:
- Attack surface: fewer packages = fewer vulnerabilities
- Image size: faster pulls and deployments
- Build time: smaller layers to transfer
Example: FROM python:3.11-slim instead of FROM python:3.11.

Q: How do you manage Docker networks with the CLI?
A: Key network commands:
- docker network ls — list networks
- docker network create mynet — create a network
- docker network connect mynet container1 — attach a running container
- docker network disconnect mynet container1 — detach
- docker network inspect mynet — view details
- docker network rm mynet — remove

Q: How do you manage Docker volumes with the CLI?
A: Key volume commands:
- docker volume create mydata — create a named volume
- docker volume ls — list all volumes
- docker volume inspect mydata — view details
- docker volume rm mydata — remove a volume
- docker volume prune — remove all unused volumes

Q: What is the exec form vs shell form in Dockerfile?
A: Exec form (preferred): CMD ["python", "app.py"] — runs directly without a shell, receives signals properly.
Shell form: CMD python app.py — runs via /bin/sh -c, which wraps the process and may not forward signals correctly.
Always use exec form for CMD and ENTRYPOINT.

Q: How do you clean up unused Docker resources?
A: Use prune commands to reclaim disk space:
- docker system prune — remove all unused data
- docker image prune — remove dangling images
- docker container prune — remove stopped containers
- docker volume prune — remove unused volumes
Add -a to remove all unused images, not just dangling ones.

Q: What is the difference between docker stop and docker rm?
A: docker stop sends SIGTERM to gracefully shut down a running container, then SIGKILL after a timeout (default 10 seconds). The container still exists in a stopped state.
docker rm permanently deletes a stopped container and its writable layer. Use docker rm -f to force-remove a running container.

Q: What is the difference between a container and a virtual machine?
A: Containers share the host OS kernel and run as isolated processes; VMs include a full guest OS and hypervisor. Containers are measured in MB and start in milliseconds; VMs are measured in GB and boot in seconds/minutes. VMs provide stronger hardware-level isolation; containers provide higher density and faster startup.

Q: What is the Docker Engine architecture?
A: Docker Engine consists of three components: the daemon (dockerd) that manages images, containers, networks, and volumes; a REST API that the daemon exposes; and the CLI client (docker) that talks to the daemon via the API. The daemon and client can run on the same host or on different machines.

Q: What is containerd?
A: containerd is an industry-standard core container runtime that manages the complete container lifecycle: image transfer/storage, container execution, network attachment, and storage. Docker Engine uses containerd under the hood, and Kubernetes can use it directly via the CRI plugin.

Q: What is the difference between the Docker daemon and the Docker CLI?
A: The daemon (dockerd) is a long-running background service that does the actual work (building, running, distributing images). The CLI (docker) is a client that sends commands to the daemon over a REST API. They communicate via a Unix socket (/var/run/docker.sock) by default.

Q: What is a Linux namespace in Docker?
A: Namespaces provide process isolation by giving containers their own views of system resources: PID, network, mount, UTS, IPC, and user namespaces. Each container gets its own set, so processes inside cannot see or interact with resources in other containers or the host (by default).

Q: What are cgroups and what do they do in Docker?
A: Control groups (cgroups) limit and account for resource usage (CPU, memory, disk I/O, network) of container processes. Docker uses cgroups to enforce limits set via flags like --memory and --cpus, and to prevent a single container from exhausting host resources.

Q: What is the difference between a Docker image and a Docker layer?
A: An image is the complete, ready-to-run filesystem blueprint. A layer is an individual read-only diff produced by a Dockerfile instruction. Images are composed by stacking layers in order; layers are shared across images to save space and speed up pulls.

Q: What is a dangling image in Docker?
A: A dangling image is an untagged image that is not referenced by any tag, usually created when you rebuild an image with the same tag. The old image becomes <none>:<none> in docker images. Remove with docker image prune.

Q: What is docker system df?
A: docker system df shows Docker's overall disk usage, broken down by images, containers, local volumes, and build cache. Use docker system df -v for per-item details. Helpful before running prune to estimate reclaimable space.

Q: What is a Docker context?
A: A Docker context stores connection settings (daemon endpoint, TLS certs, orchestrator) for one or more Docker hosts. Switch between them with docker context use <name>. Useful for managing local, staging, and production daemons from a single CLI.

Q: What does docker cp do?
A: docker cp copies files or directories between a container and the host filesystem (in either direction).
Example: docker cp mycontainer:/app/logs ./logs
It works on running or stopped containers and does not require the container to be running.

Q: What does docker diff do?
A: docker diff shows changes made to a container's filesystem since it was created: A (added file), C (changed file), D (deleted file). Useful for debugging or for understanding what a process modified at runtime.

Q: What does docker top do?
A: docker top <container> displays the running processes inside a container, similar to the host top command. You can pass ps flags to filter output, e.g., docker top mycontainer aux.

Q: What does docker port do?
A: docker port <container> shows the current port mappings between the host and the container, e.g., 80/tcp -> 0.0.0.0:8080. Handy for quickly verifying what is exposed after a docker run -p.

Q: What does docker stats do?
A: docker stats shows a live stream of resource usage per container: CPU %, memory usage/limit, network I/O, and block I/O. Add --no-stream to print once and exit, or --format to customize output.

Q: What does docker rename do?
A: docker rename <old> <new> changes the name of an existing container. Container names must be unique on a host. Useful when reusing names in scripted environments.

Q: What does docker update do?
A: docker update changes resource limits of a running container without restarting it. Example: docker update --memory=1g --cpus=2 mycontainer. Works for memory, CPU shares, restart policy, and a few other settings.

Q: What does docker wait do?
A: docker wait <container> blocks until the specified container stops, then prints its exit code. Useful in scripts that need to chain commands after a container completes.

Q: What does docker kill do, and how is it different from docker stop?
A: docker kill sends a signal (default SIGKILL) to a running container's main process, terminating it immediately. docker stop first sends SIGTERM and waits for graceful shutdown before sending SIGKILL. Use docker kill -s SIGTERM ctr to send a specific signal.

Q: What is the default timeout for docker stop?
A: The default grace period is 10 seconds. After this, Docker sends SIGKILL. Override with -t or --time: docker stop -t 30 mycontainer gives the process 30 seconds to shut down cleanly.

Q: What does docker pause do, and what kernel feature does it use?
A: docker pause suspends all processes in a container using the cgroup freezer. Paused containers still consume memory but use almost no CPU. Resume with docker unpause. Useful for diagnostics or temporarily freezing a workload.

Q: What does docker commit do?
A: docker commit <container> <new-image:tag> creates a new image from a container's current state, including any changes to its filesystem. Anti-pattern: this bypasses Dockerfile reproducibility. Use only for debugging or as a last resort.

Q: What does docker save do?
A: docker save -o file.tar myimage:1.0 exports one or more images to a tarball, including all layers and tags. Used to transfer images without a registry, e.g., to air-gapped environments. The counterpart is docker load.

Q: What does docker load do?
A: docker load -i file.tar imports images from a tarball created by docker save. Layers are restored, tags reapplied, and the image becomes runnable as if it had been pulled from a registry.

Q: What does docker export do, and how does it differ from docker save?
A: docker export produces a tarball of a container's flattened filesystem (no layers, no metadata). docker save produces a tarball of an image with all its layers and metadata. docker export output must be docker imported, losing history.

Q: What does docker import do?
A: docker import file.tar newimage:tag creates an image from a tarball (typically from docker export). The resulting image has no history or layers — it is a single flat layer. Useful for bootstrapping base images from root filesystems.

Q: What does docker tag do?
A: docker tag <source> <target> creates a new tag pointing at an existing image. It does not create a new image or copy data; it is just a label. Example: docker tag myapp:latest myrepo/myapp:v1.0.

Q: How do you remove an image?
A: Use docker rmi <image> to delete an image by ID or tag. If the image is used by a container, force with -f, but you will lose the image's history. docker image rm is the modern, preferred form.

Q: How does docker login work?
A: docker login [registry] authenticates with a registry and stores credentials in ~/.docker/config.json (or the OS keychain on Windows/macOS). After login, docker pull and docker push can access private repos. Use docker logout to clear credentials.

Q: What is docker search?
A: docker search <term> queries Docker Hub for public images matching the term. Output shows name, description, stars, official/automated status. You can filter with --filter is-official=true or --stars=10.

Q: What are the standard Docker Hub image tag conventions?
A: Tags convey meaning beyond versions:
- :latest — most recent build, not a real "latest" guarantee
- :3.12 — major.minor of the upstream
- :3.12-slim — minimal variant
- :3.12-alpine — Alpine-based
- :3.12-slim-bullseye — slim on a specific Debian release
Pin to specific tags in production; avoid :latest.

Q: What is an official image on Docker Hub?
A: Official images are curated and maintained by Docker in partnership with the upstream project (e.g., nginx, postgres, python, node). They live under a single namespace (no user prefix), follow best practices, and are regularly scanned for vulnerabilities.

Q: What is a verified publisher on Docker Hub?
A: A verified publisher is a vendor whose identity has been confirmed by Docker. Their images are listed under a verified namespace, reducing the risk of typosquatting or impersonation compared to random community images.

Q: What is the OCI image format?
A: The Open Container Initiative (OCI) image-spec defines a standard, vendor-neutral format for container images. Docker images are OCI-compliant, which is why images built with Docker can run in Podman, containerd, CRI-O, and other runtimes without conversion.

Q: What is the OCI distribution spec?
A: The OCI distribution-spec standardizes how images are pushed and pulled from registries. Any registry implementing the spec (Docker Hub, GitHub Container Registry, Harbor, AWS ECR, Quay) can serve images to any compliant client (Docker, Podman, Buildah, etc.).

Q: What is BuildKit?
A: BuildKit is Docker's next-generation build engine, enabled by default in recent Docker versions. Benefits include parallel build steps, better caching, rootless builds, secret mounting, and SSH forwarding. Enable explicitly with DOCKER_BUILDKIT=1 or in /etc/docker/daemon.json.

Q: What is the --mount=type=cache option in BuildKit?
A: The --mount=type=cache BuildKit option mounts a persistent build cache at a path inside the build container. Unlike a normal RUN layer, the cache survives across builds even if subsequent instructions change. Common use: package manager caches like /root/.cache/pip.

Q: How do you use BuildKit secrets in a build?
A: Use --mount=type=secret in a RUN step to mount a secret (e.g., npm token) without baking it into the image:
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm install
Pass the secret at build time with --secret id=npmrc,src=.npmrc. The secret never appears in any image layer.

Q: How do you forward SSH keys to a build with BuildKit?
A: Use --mount=type=ssh in a RUN step to make the host's SSH agent available inside the build:
RUN --mount=type=ssh mkdir -p ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts && pip install git+ssh://...
Build with --ssh default=$SSH_AUTH_SOCK. The keys are never written into the image.

Q: What is a build target in a multi-stage Dockerfile?
A: A named FROM ... AS <name> stage can be built independently with docker build --target <name>. Common pattern: a builder target for CI and a final minimal target for production. Other stages are built but pruned from the final image.

Q: What is the difference between docker image history and docker history?
A: They are the same command (alias). docker history <image> shows the layer history of an image: size, creator, and comment for each layer. Use --no-trunc to see full commands. Helps explain why an image is large.

Q: What is docker image prune vs docker image prune -a?
A: docker image prune removes dangling images (untagged). docker image prune -a removes all unused images — including tagged images not referenced by any container. Use -a carefully in CI/build hosts.

Q: What is a Docker build context?
A: The build context is the set of files and directories sent from the CLI to the daemon when you run docker build. By default it is the current directory (.). Large contexts slow builds; use .dockerignore to exclude unnecessary files.

Q: How do you pass a different build context to docker build?
A: You can use a named build context with BuildKit: docker build --build-context myrepo=git://github.com/foo/bar.git .. Inside the Dockerfile, COPY --from=myrepo ./some/path refers to that context. Replaces the older "build from URL" syntax.

Q: What is docker buildx?
A: docker buildx is an extended build CLI that ships with Docker. It supports BuildKit features, building for multiple platforms in a single command, advanced caching backends (registry, S3, local), and custom builders. It is the recommended way to build today.

Q: How do you build a multi-platform image?
A: With buildx:
docker buildx build --platform linux/amd64,linux/arm64 -t myapp:1.0 --push .
Multi-platform builds require either QEMU emulation or native builders on each target architecture. The result is a manifest list (image index) that the runtime picks the correct architecture from.

Q: What is a manifest list (image index) in Docker?
A: A manifest list is a single image reference that points to multiple platform-specific images. Clients query it and pull the variant matching their architecture. Created automatically by multi-platform builds; inspect with docker manifest inspect myapp:1.0.

Q: What is a scratch image?
A: FROM scratch creates a Dockerfile with no parent layer — the resulting image contains only what you explicitly add. It is the smallest possible base and is used for statically linked binaries, minimal OS images, and language runtimes that ship their own runtime.

Q: What is a distroless image?
A: Distroless images (e.g., gcr.io/distroless/base, distroless/java17) contain only your application and its language runtime — no shell, no package manager, no utilities. This drastically reduces attack surface. They cannot be exec bashed into, which is intentional.

Q: What is the Alpine base image, and what is its trade-off?
A: alpine is a ~5 MB base built on musl libc and BusyBox. It yields tiny images and fast pulls, but binary compatibility with glibc-based software can be an issue. Some prebuilt wheels and node-sass binaries fail on musl; use slim Debian-based images when compatibility is critical.

Q: What is the default storage driver for Docker on modern Linux?
A: On modern Docker with overlay2-supported filesystems (ext4, xfs), the default is overlay2. It is the recommended driver for production. Older drivers like aufs and devicemapper are deprecated; Docker on Windows defaults to windowsfilter.

Q: What is docker info?
A: docker info shows the daemon's configuration: server version, storage driver, cgroup driver, number of images/containers, security options, and registry mirrors. Useful as a first step when debugging "why doesn't this work?".

Q: What is the docker-compose.yml schema version field?
A: The version top-level key (e.g., "3.8") historically selected the Compose file schema. With Compose Spec (now the standard), version is deprecated and ignored. Modern Compose files omit it.

Q: What is the Compose Spec?
A: The Compose Specification is an open standard maintained by the Compose community that unifies the docker-compose.yml format across Docker, AWS ECS, Microsoft ACI, Kubernetes (via kompose), and others. A single file is portable to all these platforms.

Q: How does docker compose up -d --build work?
A: docker compose up -d --build builds (or rebuilds) images defined with build: in the Compose file, then starts all services in detached mode. Add --force-recreate to discard existing containers, or --no-deps to skip dependent services.

Q: How do you scale a service in Docker Compose?
A: Use docker compose up -d --scale web=3 to run 3 replicas of the web service. For long-running scaling in a Compose file, use the deploy.replicas key (requires docker compose --compatibility / Swarm mode). In modern Compose, scale works directly for non-deploy keys.

Q: What is a profile in Docker Compose?
A: A profile groups services so they only start when explicitly requested. Define with profiles: ["debug"] on a service, then run docker compose --profile debug up. Useful for dev-only services like debuggers, load generators, or admin UIs.

Q: How do you wait for a service to be ready in Compose?
A: depends_on with a condition: service_healthy clause:
web:
  depends_on:
    db:
      condition: service_healthy
This requires the db service to define a healthcheck and to be reported as healthy before web starts.

Q: What is the difference between extends and include in Compose?
A: extends lets a service inherit configuration from another service in the same or referenced file. include is newer (Compose Spec) and merges whole YAML files into the project. include is the modern way to split Compose configurations across files.

Q: What is the YAML anchor/alias pattern in Compose?
A: YAML anchors (&) and aliases (*) let you define a fragment once and reuse it:
x-common: &common
  restart: always
  logging:
    driver: json-file
services:
  web:
    <<: *common
Reduces duplication in large Compose files.

Q: What is the .env file in a Compose project?
A: A .env file in the same directory as docker-compose.yml is loaded automatically. Keys become variables you can reference as ${VAR} in the Compose file. It is not the same as env_file:, which is per-service and loaded inside containers.

Q: What is a network alias in Docker?
A: A network alias is an extra DNS name a container is reachable by on a specific network. Set with docker run --network-alias db mydb or networks: frontend: aliases: [api] in Compose. Other containers on the same network can resolve that alias.

Q: How do containers resolve each other's names?
A: On a user-defined bridge network, Docker's embedded DNS server (127.0.0.11 within containers) resolves container names, network aliases, and service names. On the default bridge, only IPs work — no name resolution.

Q: What is the macvlan network driver?
A: macvlan assigns a container a unique MAC address on the physical network, making it appear as a physical host. Useful for legacy applications that need a real LAN IP, or for low-latency networking. Cannot talk to the host by default — you need a macvlan sub-interface.

Q: What is the ipvlan network driver?
A: ipvlan is similar to macvlan but shares the host's MAC address and uses L3/L4 separation. It works in environments that restrict MAC addresses (e.g., some cloud providers). docker network create -d ipvlan ....

Q: What is the none network driver?
A: docker run --network none attaches only a loopback interface. The container has no external network connectivity. Useful for batch jobs, isolated sandboxes, or security-sensitive workloads.

Q: What is the difference between EXPOSE and docker run -p?
A: EXPOSE in a Dockerfile is pure documentation — a hint to humans and tools. It does not actually publish ports. docker run -p 8080:80 (or -P to publish all EXPOSEd ports) creates the real iptables forwarding rule that makes the port reachable from the host.

Q: What is the difference between docker run -p and docker run -P?
A: -p HOST:CONTAINER publishes a specific port (e.g., -p 8080:80). -P (uppercase) publishes all EXPOSEd ports to random host ports; you can find the mapping with docker port. -P is convenient in development but rarely used in production.

Q: What is a user-defined bridge vs the default bridge?
A: The default bridge (bridge) is auto-created, lacks DNS-based name resolution, and is shared by all uncustomized containers. User-defined bridges provide automatic DNS resolution by name, allow attaching/detaching on the fly, and are configurable. Best practice: always use user-defined bridges.

Q: How do you attach a running container to another network?
A: docker network connect mynet mycontainer attaches a running container to an additional network. The container then has an interface on both networks. docker network disconnect mynet mycontainer removes it.

Q: What is the default IP range for Docker bridge networks?
A: By default, the default bridge uses 172.17.0.0/16 with the Docker host at 172.17.0.1. User-defined bridges get the next available 172.x.0.0/16. Override per-network with --subnet and --gateway flags on docker network create.

Q: What is a tmpfs mount?
A: A tmpfs mount is a volume backed by the host's RAM (and swap). It is extremely fast but non-persistent and limited in size. Use for sensitive data (secrets, keys) or for caches that should not survive a restart. Example: docker run --tmpfs /tmp:size=100m.

Q: What is the difference between a bind mount and a named volume?
A: Bind mounts map an arbitrary host path (-v /host/path:/container/path) — useful for development with live-reload. Named volumes are managed by Docker in /var/lib/docker/volumes/, are portable across hosts, and are the recommended way to persist data in production.

Q: What is the propagation mode in a bind mount?
A: Bind mount propagation controls how mounts created inside the mount are propagated to the host and vice versa. Options: rprivate (default), private, rshared, shared, slave, rslave. Most users should leave the default.

Q: What is the docker volume plugin model?
A: A volume driver/plugin extends Docker to mount storage from external systems (NFS, AWS EBS, Azure Disk, GCE PD, Ceph, etc.). Specify per-volume: docker volume create --driver local --opt type=nfs .... The local driver is built-in; others are installed separately.

Q: What is the difference between an anonymous and a named volume?
A: An anonymous volume is created without a name (e.g., -v /data in a Dockerfile). Docker generates a random name; it is hard to reference. Named volumes (myvolume:/data) are explicit, easy to back up, list, and reuse. Prefer named volumes.

Q: What is a volume label?
A: Volume labels are key-value metadata attached to a volume, used by the volume driver or external tooling. Set with docker volume create --label env=prod. The local driver reserves opt-prefixed keys for options.

Q: What happens to a volume when a container is removed?
A: By default, volumes are not removed when a container using them is removed — this protects data. To remove a volume automatically, use --rm with a container that created an anonymous volume, or use docker run --volumes-from patterns. Use docker volume prune to clean unused volumes.

Q: What is a Dockerfile .dockerignore pattern syntax?
A: Patterns use Go's filepath.Match plus some extras: * matches any sequence of non-separator chars, ** matches across directories, ? matches a single char, [abc] matches a set, ! negates a pattern. A leading **/ matches at any depth.

Q: What is the difference between a Docker image's CMD and a runtime argument?
A: When you run docker run myimage echo hi, the argument echo hi overrides the CMD in the Dockerfile. If the Dockerfile has an ENTRYPOINT, the extra arguments are appended to the ENTRYPOINT (in exec form) or replace CMD (in shell form). This is the standard override behavior.

Q: What is the --entrypoint flag?
A: docker run --entrypoint /bin/sh myimage overrides the image's ENTRYPOINT for that container only. Useful for debugging an image whose ENTRYPOINT is broken. Combine with extra args to run a shell inside.

Q: What does the STOPSIGNAL instruction do?
A: STOPSIGNAL sets the system signal sent to the container when docker stop is invoked. Default is SIGTERM. Example: STOPSIGNAL SIGINT for applications that handle SIGINT more gracefully than SIGTERM.

Q: What does the ONBUILD instruction do?
A: ONBUILD registers a trigger that runs in a downstream image's build, not in the current one. Useful for base images: ONBUILD COPY . /app means any image built FROM this base will copy its context into /app. Deprecated for new designs in favor of multi-stage builds.

Q: What does the SHELL instruction do?
A: SHELL overrides the default shell (["/bin/sh", "-c"]) used for shell-form RUN, CMD, and ENTRYPOINT instructions. Example: SHELL ["powershell", "-command"] on Windows. Does not affect exec-form commands.

Q: What is a build cache invalidation in Docker?
A: Any change to a Dockerfile instruction or to files referenced by COPY/ADD invalidates the cache from that instruction downward. Earlier instructions and unchanged files keep their cached layers. Use the --cache-from flag to share caches across CI runs.

Q: What is --cache-from in Docker?
A: --cache-from myimage:previous tells the builder to reuse layers from the named image's cache when building. Critical in CI to avoid rebuilding from scratch on every commit. Combine with registry-based caching in buildx: --cache-to=type=registry.

Q: What is an inline ignore cache option in BuildKit?
A: With RUN --mount=type=cache,target=/go/pkg/mod, BuildKit mounts a persistent cache directory across builds. Unlike a normal RUN layer, the cache is reused even if the surrounding RUN changes — making Go module downloads and similar workflows fast.

Q: What is the difference between --link and user-defined networks?
A: docker run --link is the legacy way to link containers by injecting environment variables and /etc/hosts entries. It only works on the default bridge. User-defined networks with embedded DNS are the modern, supported replacement.

Q: What is a container's PID 1 problem?
A: The PID 1 of a container is the main process, and Linux kernel signals default to ignoring SIGTERM/SIGPIPE for PID 1. If your CMD runs a script that doesn't exec the real binary, docker stop may take 10 seconds (the SIGKILL grace period). Use exec form CMD ["app"] to fix.

Q: What is tini in Docker contexts?
A: tini is a tiny init (a few hundred KB) designed to be container PID 1. It reaps zombie processes and forwards signals correctly. Pass it via --init to docker run, or include it in your image as ENTRYPOINT ["/sbin/tini", "--"].

Q: What does docker run --init do?
A: --init injects a small init process (tini) as PID 1 inside the container. Solves the zombie-reaping and signal-forwarding problem when your main process isn't signal-aware. Adds negligible overhead and is a recommended default for most images.

Q: What are Linux capabilities, and how do they affect containers?
A: Capabilities split root's traditional powers into discrete units (e.g., NET_ADMIN, SYS_TIME, SYS_PTRACE). By default, Docker drops most capabilities and keeps a small safe set. Add back with --cap-add, drop more with --cap-drop.

Q: What is docker run --privileged?
A: --privileged gives the container almost all host capabilities, access to all host devices, and disables most security barriers. Useful for nested Docker (DinD), but a major security risk in production. Avoid unless absolutely required.

Q: What is the --security-opt flag in Docker?
A: --security-opt configures security profiles. Common uses: --security-opt no-new-privileges (prevents setuid binaries from gaining new privileges), --security-opt seccomp=profile.json (apply custom seccomp), --security-opt apparmor=profile (apply AppArmor).

Q: What is the default seccomp profile in Docker?
A: Docker applies a default seccomp profile that allows ~300 syscalls and blocks the rest. You can run with the unconfined profile (--security-opt seccomp=unconfined) for debugging, or supply a custom JSON profile. Tools like docker run --cap-drop=ALL ... tighten the surface further.

Q: What is --read-only filesystem in Docker?
A: docker run --read-only mounts the container's root filesystem as read-only. Combined with tmpfs mounts for /tmp and volumes for data dirs, it prevents the container from persisting unwanted writes — a strong hardening technique. The container's writable layer is the only mutable area.

Q: What is the user namespace remapping feature in Docker?
A: With userns-remap enabled in daemon.json, the Docker daemon maps container UIDs to a range of host UIDs (default 65,536 IDs). Container root (UID 0) maps to an unprivileged host user, so a container escape does not yield host root.

Q: What is the difference between docker stop and docker kill regarding exit codes?
A: docker stop on a normally-exited container preserves its exit code 0. If SIGTERM/SIGKILL is required, the exit code is 143 (128 + 15 for SIGTERM) or 137 (128 + 9 for SIGKILL). docker wait and docker inspect expose the exit code programmatically.

Q: What is docker run --restart and what are its policies?
A: --restart controls what Docker does when a container exits:
- no (default): do not restart
- on-failure[:max]: restart only on non-zero exit
- always: always restart, even on docker stop
- unless-stopped: like always, but don't restart if manually stopped
Use unless-stopped in production unless you need a fixed restart count.

Q: What is a Docker healthcheck and its options?
A: A HEALTHCHECK instruction in a Dockerfile runs a command periodically to determine the container's health. Options: --interval (default 30s), --timeout (default 30s), --start-period (grace period on first start, default 0s), --retries (default 3). The status appears in docker ps.

Q: What is the difference between a container being "running" and "healthy"?
A: A running container's main process is alive (PID 1 is executing). A healthy container additionally has its healthcheck reporting 0. A running-but-unhealthy container still serves traffic unless an orchestrator is checking the healthcheck. Healthy is the correct state to gate dependent services on.

Q: What is the default ulimit for open files in Docker containers?
A: By default, Docker sets ulimit -n to 1024 open file descriptors per container. Many services (databases, web servers) need more. Override with --ulimit nofile=65535:65535 on docker run, or in Compose under ulimits:.

Q: What is the default size of /dev/shm in Docker containers?
A: By default, Docker sets /dev/shm to 64 MB. Some applications (notably Python with multiprocessing and some ML libraries) fail with shared-memory errors. Workaround: docker run --shm-size=1g ... or mount a tmpfs at /dev/shm.

Q: How do you limit a container's PIDs?
A: Use --pids-limit to cap the number of processes a container can spawn (default is usually 4096). Useful for defending against fork bombs and runaway process creation. docker run --pids-limit=100 stress-container.

Q: What is docker logs and what drivers does it support?
A: docker logs works with the json-file driver (default) and others. Other drivers: journald, syslog, fluentd, gelf, awslogs, splunk. Configure per-container with --log-driver or globally in daemon.json.

Q: How do you configure log rotation for Docker logs?
A: By default, the json-file driver has no rotation and can fill the disk. Configure in daemon.json:
{ "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" } }
This keeps up to 3 files of 10 MB each per container.

Q: What is the difference between a stopped and a paused container?
A: A stopped container has its main process terminated; memory is freed. A paused container has its processes frozen (cgroup freezer); memory is preserved and CPU usage drops to zero. Resume a paused container instantly with docker unpause.

Q: What is docker rm -v?
A: docker rm -v <container> also removes anonymous volumes associated with the container. Named volumes are kept. Useful during development when iterating on data layouts.

Q: What is docker run --rm?
A: --rm automatically removes the container when it exits. Convenient for one-off tasks: docker run --rm alpine echo hello. The container never accumulates in docker ps -a.

Q: What is the difference between docker attach and docker exec?
A: docker attach connects your terminal to the container's main process's STDIN/STDOUT. You see the same stream as the application, and signals go to the main process. docker exec runs a new process inside the container. Use exec for side tasks (debugging, inspection).

Q: What is the default root user inside a container?
A: By default, processes inside a container run as root (UID 0) — but this UID maps to a user on the host. If userns-remap is enabled, container root is unprivileged on the host. Otherwise, a container-root process can affect the host's root-owned files if paths are shared.

Q: What is the WORKDIR inheritance in a Dockerfile?
A: Each WORKDIR sets the working directory for all following instructions and is inherited by subsequent stages in a multi-stage build (unless overridden). It is created with mkdir -p semantics, so nested paths like WORKDIR /app/src work in one step.

Q: What is the difference between ENV and runtime environment variables?
A: ENV in a Dockerfile sets defaults baked into the image. Runtime env vars (docker run -e or env_file) override them. If a variable is set in both, the runtime value wins. To inspect inside a running container, use docker exec mycontainer env.

Q: What is a Docker registry API token?
A: Modern registries (Docker Hub, GHCR, ECR) issue short-lived bearer tokens via the OAuth2-compatible /token endpoint after the client presents credentials. The token scopes the pull/push to specific repositories, and is cached for the duration returned in the response.

Q: What is the difference between a private image and a public image on Docker Hub?
A: Public images are visible to anyone; pulls do not require authentication. Private images are visible only to users/teams you grant access to, and pulls require a docker login with the right credentials. Docker Hub offers a small number of free private repos per account.

Q: What is the registry authentication token cache?
A: After docker login, the credential/token is stored in ~/.docker/config.json. The Docker CLI automatically uses it for subsequent pulls. Tokens for specific registries are stored in auths or credHelpers keys. Clear with docker logout.

Q: What is the docker manifest command?
A: docker manifest is a low-level subcommand to inspect, create, and annotate multi-platform image manifests. Commands: manifest create, manifest inspect, manifest annotate (to set per-platform os/arch metadata), and manifest push. Most users will use buildx instead.

Q: What is a Docker Content Trust signature?
A: Docker Content Trust (DCT) uses Notary to sign image tags. With DOCKER_CONTENT_TRUST=1, the daemon only pulls images signed by a trusted publisher. Provides integrity and authenticity guarantees. Often used in production and by Kubernetes admission controllers.

Q: What is the difference between docker CLI plugins?
A: CLI plugins are executables named docker-<name> on the PATH; they extend docker with new subcommands. Examples: docker compose, docker buildx, docker scan, docker scout. Install by dropping the binary into ~/.docker/cli-plugins or /usr/local/lib/docker/cli-plugins.

Q: What is a Docker trusted registry?
A: A Docker Trusted Registry (DTR) is a commercial, on-premises registry product from Mirantis (formerly Docker Enterprise). It adds role-based access control, image signing, scanning, and replication policies on top of a standard OCI distribution registry. Open-source alternatives include Harbor, Quay, and GitLab Container Registry.