InterviewTreedInterviewTreed

InterviewTreed Question Bank

Docker & Kubernetes Interview Questions and Answers

Prepare for Docker and Kubernetes interviews, covering containerization, images, networking, orchestration, deployments, scaling, security, monitoring, and production infrastructure.

Total Questions

99

Beginner

32

Intermediate

43

Advanced

24

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Containers

What is a container?

A container packages an application with its libraries and runtime dependencies so it can run consistently across environments.

Answer

A container packages an application with its libraries and runtime dependencies so it can run consistently across environments.

Syntax

docker run --rm hello-world

Example

docker run --rm hello-world

Code example

docker run --rm hello-world

Diagram

Containers → container/orchestrator operation → result

Key Points

  • Containers share the host kernel.
  • They are usually lighter than virtual machines.
Q2Docker fundamentals

What is Docker?

Docker is a platform and toolset for building, distributing, and running container images.

Answer

Docker is a platform and toolset for building, distributing, and running container images.

Syntax

docker --version
docker run --rm nginx:alpine

Example

docker --version docker run --rm nginx:alpine

Code example

docker --version
docker run --rm nginx:alpine

Diagram

Docker fundamentals → container/orchestrator operation → result

Key Points

  • Images are templates; containers are running instances.
Q3Images and containers

What is the difference between an image and a container?

An image is an immutable, layered template. A container is an instance created from an image with a writable runtime layer.

Answer

An image is an immutable, layered template. A container is an instance created from an image with a writable runtime layer.

Syntax

docker pull nginx:alpine
docker run -d --name web nginx:alpine

Example

docker pull nginx:alpine docker run -d --name web nginx:alpine

Code example

docker pull nginx:alpine
docker run -d --name web nginx:alpine

Diagram

Images and containers → container/orchestrator operation → result

Key Points

  • Multiple containers can use the same image.
Q4Dockerfiles

What is a Dockerfile?

A Dockerfile describes the steps used to build an image, including its base image, files, dependencies, and startup command.

Answer

A Dockerfile describes the steps used to build an image, including its base image, files, dependencies, and startup command.

Syntax

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["npm", "start"]

Example

FROM node:22-alpine WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . CMD ["npm", "start"]

Code example

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["npm", "start"]

Diagram

Dockerfiles → container/orchestrator operation → result

Key Points

  • Prefer explicit, reproducible build steps.
Q5Docker commands

How do you list running containers and view logs?

Use `docker ps` to list running containers and `docker logs` to inspect a container's standard output and error streams.

Answer

Use `docker ps` to list running containers and `docker logs` to inspect a container's standard output and error streams.

Syntax

docker ps
docker logs --tail 100 -f my-container

Example

docker ps docker logs --tail 100 -f my-container

Code example

docker ps
docker logs --tail 100 -f my-container

Diagram

Docker commands → container/orchestrator operation → result

Key Points

  • Use `docker ps -a` to include stopped containers.
Q6Ports

How do you publish a container port?

Use `-p HOST_PORT:CONTAINER_PORT` to map a host port to a port inside the container.

Answer

Use `-p HOST_PORT:CONTAINER_PORT` to map a host port to a port inside the container.

Syntax

docker run -d --name web -p 8080:80 nginx:alpine

Example

docker run -d --name web -p 8080:80 nginx:alpine

Code example

docker run -d --name web -p 8080:80 nginx:alpine

Diagram

Ports → container/orchestrator operation → result

Key Points

  • The application must listen on the container interface/port.
Q7Storage

What is a Docker volume?

A volume stores data outside a container's writable layer so it can persist after the container is removed.

Answer

A volume stores data outside a container's writable layer so it can persist after the container is removed.

Syntax

docker volume create app-data
docker run -d --mount source=app-data,target=/var/lib/app my-image

Example

docker volume create app-data docker run -d --mount source=app-data,target=/var/lib/app my-image

Code example

docker volume create app-data
docker run -d --mount source=app-data,target=/var/lib/app my-image

Diagram

Storage → container/orchestrator operation → result

Key Points

  • Use volumes for persistent application data.
Q8Networking

What is a Docker network?

A Docker network connects containers and controls how they communicate with each other and external networks.

Answer

A Docker network connects containers and controls how they communicate with each other and external networks.

Syntax

docker network create app-net
docker run -d --network app-net --name api my-api

Example

docker network create app-net docker run -d --network app-net --name api my-api

Code example

docker network create app-net
docker run -d --network app-net --name api my-api

Diagram

Networking → container/orchestrator operation → result

Key Points

  • Containers on a user-defined bridge network can resolve each other by name.
Q9Environment variables

How do you pass configuration to a container?

Pass runtime configuration with environment variables or an environment file; avoid baking environment-specific secrets into images.

Answer

Pass runtime configuration with environment variables or an environment file; avoid baking environment-specific secrets into images.

Syntax

docker run --rm -e ASPNETCORE_ENVIRONMENT=Production my-api
docker run --env-file .env my-api

Example

docker run --rm -e ASPNETCORE_ENVIRONMENT=Production my-api docker run --env-file .env my-api

Code example

docker run --rm -e ASPNETCORE_ENVIRONMENT=Production my-api
docker run --env-file .env my-api

Diagram

Environment variables → container/orchestrator operation → result

Key Points

  • Keep secrets out of source control and image layers.
Q10Image registry

What is a container registry?

A registry stores and distributes container images, often using tags or immutable digests.

Answer

A registry stores and distributes container images, often using tags or immutable digests.

Syntax

docker login registry.example.com
docker tag my-api:latest registry.example.com/team/my-api:1.0
docker push registry.example.com/team/my-api:1.0

Example

docker login registry.example.com docker tag my-api:latest registry.example.com/team/my-api:1.0 docker push registry.example.com/team/my-api:1.0

Code example

docker login registry.example.com
docker tag my-api:latest registry.example.com/team/my-api:1.0
docker push registry.example.com/team/my-api:1.0

Diagram

Image registry → container/orchestrator operation → result

Key Points

  • Use controlled access and scan images.
Q11Compose

What is Docker Compose?

Compose defines and runs a multi-container application using a YAML file, including services, networks, volumes, and configuration.

Answer

Compose defines and runs a multi-container application using a YAML file, including services, networks, volumes, and configuration.

Syntax

docker compose up -d
docker compose ps
docker compose down

Example

docker compose up -d docker compose ps docker compose down

Code example

docker compose up -d
docker compose ps
docker compose down

Diagram

Compose → container/orchestrator operation → result

Key Points

  • Useful for local development and integration testing.
Q12Kubernetes fundamentals

What is Kubernetes?

Kubernetes orchestrates containerized workloads by scheduling them, maintaining desired state, providing service discovery, and supporting rollouts.

Answer

Kubernetes orchestrates containerized workloads by scheduling them, maintaining desired state, providing service discovery, and supporting rollouts.

Syntax

kubectl get nodes
kubectl get pods -A

Example

kubectl get nodes kubectl get pods -A

Code example

kubectl get nodes
kubectl get pods -A

Diagram

Kubernetes fundamentals → container/orchestrator operation → result

Key Points

  • A cluster has a control plane and worker nodes.
Q13Kubernetes architecture

What is a Pod?

A Pod is the smallest deployable Kubernetes unit and can contain one or more tightly coupled containers sharing network identity and optionally volumes.

Answer

A Pod is the smallest deployable Kubernetes unit and can contain one or more tightly coupled containers sharing network identity and optionally volumes.

Syntax

kubectl get pods -n default

Example

kubectl get pods -n default

Code example

kubectl get pods -n default

Diagram

Kubernetes architecture → container/orchestrator operation → result

Key Points

  • Containers in one Pod share the Pod IP and port space.
Q14Workloads

What is a Deployment?

A Deployment manages ReplicaSets and provides declarative updates and rollback for stateless replicated Pods.

Answer

A Deployment manages ReplicaSets and provides declarative updates and rollback for stateless replicated Pods.

Syntax

kubectl create deployment web --image=nginx:alpine
kubectl get deployments

Example

kubectl create deployment web --image=nginx:alpine kubectl get deployments

Code example

kubectl create deployment web --image=nginx:alpine
kubectl get deployments

Diagram

Workloads → container/orchestrator operation → result

Key Points

  • Set replicas and rollout strategy in a manifest for production.
Q15Workloads

How do you declare a Deployment with two replicas?

A Deployment specifies the desired replica count and a selector/template that identifies the Pods it manages.

Answer

A Deployment specifies the desired replica count and a selector/template that identifies the Pods it manages.

Syntax

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.27-alpine
          ports:
            - containerPort: 80

Example

apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: nginx image: nginx:1.27-alpine ports: - containerPort: 80

Code example

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.27-alpine
          ports:
            - containerPort: 80

Diagram

Workloads → container/orchestrator operation → result

Key Points

  • Selector labels must match Pod-template labels.
Q16Services

What is a Kubernetes Service?

A Service provides a stable virtual IP and DNS name for a changing set of Pods selected by labels.

Answer

A Service provides a stable virtual IP and DNS name for a changing set of Pods selected by labels.

Syntax

kubectl expose deployment web --port=80 --target-port=80 --type=ClusterIP

Example

kubectl expose deployment web --port=80 --target-port=80 --type=ClusterIP

Code example

kubectl expose deployment web --port=80 --target-port=80 --type=ClusterIP

Diagram

Services → container/orchestrator operation → result

Key Points

  • ClusterIP is internal; NodePort and LoadBalancer expose service differently.
Q17Configuration

What is a ConfigMap?

A ConfigMap stores non-confidential configuration that can be exposed to Pods as environment variables, arguments, or mounted files.

Answer

A ConfigMap stores non-confidential configuration that can be exposed to Pods as environment variables, arguments, or mounted files.

Syntax

kubectl create configmap app-config --from-literal=LOG_LEVEL=Information

Example

kubectl create configmap app-config --from-literal=LOG_LEVEL=Information

Code example

kubectl create configmap app-config --from-literal=LOG_LEVEL=Information

Diagram

Configuration → container/orchestrator operation → result

Key Points

  • Do not store passwords or tokens in ConfigMaps.
Q18Secrets

What is a Kubernetes Secret?

A Secret represents sensitive configuration such as credentials or tokens. Access should be restricted with RBAC and encryption at rest configured.

Answer

A Secret represents sensitive configuration such as credentials or tokens. Access should be restricted with RBAC and encryption at rest configured.

Syntax

kubectl create secret generic db-secret --from-literal=username=app

Example

kubectl create secret generic db-secret --from-literal=username=app

Code example

kubectl create secret generic db-secret --from-literal=username=app

Diagram

Secrets → container/orchestrator operation → result

Key Points

  • Base64 encoding is not encryption.
Q19Namespaces

Why use Kubernetes namespaces?

Namespaces logically group resources and help apply access controls, quotas, and naming boundaries within a cluster.

Answer

Namespaces logically group resources and help apply access controls, quotas, and naming boundaries within a cluster.

Syntax

kubectl create namespace staging
kubectl get pods -n staging

Example

kubectl create namespace staging kubectl get pods -n staging

Code example

kubectl create namespace staging
kubectl get pods -n staging

Diagram

Namespaces → container/orchestrator operation → result

Key Points

  • Namespaces are not a strong security boundary by themselves.
Q20Health checks

What is a liveness probe?

A liveness probe detects a container that is running but cannot make progress; repeated failures can cause Kubernetes to restart it.

Answer

A liveness probe detects a container that is running but cannot make progress; repeated failures can cause Kubernetes to restart it.

Syntax

livenessProbe:
  httpGet:
    path: /health/live
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 10

Example

livenessProbe: httpGet: path: /health/live port: 8080 initialDelaySeconds: 10 periodSeconds: 10

Code example

livenessProbe:
  httpGet:
    path: /health/live
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 10

Diagram

Health checks → container/orchestrator operation → result

Key Points

  • Do not use liveness to check every downstream dependency.
Q21Health checks

What is a readiness probe?

A readiness probe indicates whether a Pod should receive Service traffic. A failed readiness probe removes it from ready endpoints without necessarily restarting it.

Answer

A readiness probe indicates whether a Pod should receive Service traffic. A failed readiness probe removes it from ready endpoints without necessarily restarting it.

Syntax

readinessProbe:
  httpGet:
    path: /health/ready
    port: 8080
  periodSeconds: 5

Example

readinessProbe: httpGet: path: /health/ready port: 8080 periodSeconds: 5

Code example

readinessProbe:
  httpGet:
    path: /health/ready
    port: 8080
  periodSeconds: 5

Diagram

Health checks → container/orchestrator operation → result

Key Points

  • Readiness should reflect ability to serve requests.
Q22Scaling

How do you scale a Deployment?

Change the replica count manually or use a Horizontal Pod Autoscaler when metrics and resource requests are configured.

Answer

Change the replica count manually or use a Horizontal Pod Autoscaler when metrics and resource requests are configured.

Syntax

kubectl scale deployment web --replicas=4
kubectl get deployment web

Example

kubectl scale deployment web --replicas=4 kubectl get deployment web

Code example

kubectl scale deployment web --replicas=4
kubectl get deployment web

Diagram

Scaling → container/orchestrator operation → result

Key Points

  • Scaling Pods also requires sufficient cluster capacity.
Q23Troubleshooting

How do you troubleshoot a failing Pod?

Start with Pod status and events, inspect logs, describe the Pod, and verify configuration, image access, probes, and resource limits.

Answer

Start with Pod status and events, inspect logs, describe the Pod, and verify configuration, image access, probes, and resource limits.

Syntax

kubectl get pods
kubectl describe pod <pod-name>
kubectl logs <pod-name> --all-containers=true

Example

kubectl get pods kubectl describe pod <pod-name> kubectl logs <pod-name> --all-containers=true

Code example

kubectl get pods
kubectl describe pod <pod-name>
kubectl logs <pod-name> --all-containers=true

Diagram

Troubleshooting → container/orchestrator operation → result

Key Points

  • Use `--previous` to inspect logs from a restarted container.
Q24Security

Why should containers run as non-root?

Running as a non-root user reduces the impact of a container compromise and supports least-privilege defense in depth.

Answer

Running as a non-root user reduces the impact of a container compromise and supports least-privilege defense in depth.

Syntax

USER 10001:10001

Example

USER 10001:10001

Code example

USER 10001:10001

Diagram

Security → container/orchestrator operation → result

Key Points

  • Combine with dropped Linux capabilities and a read-only filesystem where feasible.
Q25Architecture

Show a simple Kubernetes request flow.

A client reaches an exposed entry point, which routes to a Service; the Service forwards traffic to ready Pods managed by a Deployment.

Answer

A client reaches an exposed entry point, which routes to a Service; the Service forwards traffic to ready Pods managed by a Deployment.

Syntax

Client -> Ingress / LoadBalancer -> Service -> Pod replicas
                                      Deployment manages Pods

Example

Client -> Ingress / LoadBalancer -> Service -> Pod replicas Deployment manages Pods

Code example

Client -> Ingress / LoadBalancer -> Service -> Pod replicas
                                      Deployment manages Pods

Diagram

Architecture → container/orchestrator operation → result

Key Points

  • Services abstract changing Pod IP addresses.
Q76Docker Images

What are Docker image layers?

Docker images are built from layers that can be cached and reused. A changed instruction generally invalidates that layer and later layers, so st

Answer

Docker images are built from layers that can be cached and reused. A changed instruction generally invalidates that layer and later layers, so stable, expensive steps should usually appear earlier in a Dockerfile.

Example: Dockerfile instructions → cached image layers → final image

Diagram / flow: Base layer → dependencies layer → application source layer

Syntax

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .

Example

Dockerfile instructions → cached image layers → final image

Code example

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .

Diagram

Base layer → dependencies layer → application source layer

Key Points

  • Docker images are built from layers that can be cached and reused.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q77Docker Build

What is the Docker build context?

The build context is the set of files sent to the builder for a build. A focused context and .dockerignore reduce transfer time and avoid acciden

Answer

The build context is the set of files sent to the builder for a build. A focused context and .dockerignore reduce transfer time and avoid accidentally including secrets, dependencies, or generated files.

Example: Current directory → filtered by .dockerignore → build context → Docker builder

Diagram / flow: docker build context: source files + Dockerfile; excluded files are not sent

Syntax

docker build -t myapp:1.0 .

Example

Current directory → filtered by .dockerignore → build context → Docker builder

Code example

docker build -t myapp:1.0 .

Diagram

docker build context: source files + Dockerfile; excluded files are not sent

Key Points

  • The build context is the set of files sent to the builder for a build.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q78Docker Build

How does a .dockerignore file help?

A .dockerignore file excludes unnecessary or sensitive files from the build context. It improves build speed and reduces the chance of copying lo

Answer

A .dockerignore file excludes unnecessary or sensitive files from the build context. It improves build speed and reduces the chance of copying local artifacts or secrets into an image.

Example: Build context → .dockerignore filtering → smaller, safer context

Diagram / flow: Example .dockerignore: node_modules, .git, .env, coverage

Syntax

node_modules
.git
.env
coverage

Example

Build context → .dockerignore filtering → smaller, safer context

Code example

node_modules
.git
.env
coverage

Diagram

Example .dockerignore: node_modules, .git, .env, coverage

Key Points

  • A .
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q82Storage

How do named volumes differ from bind mounts?

Named volumes are managed by Docker and are useful for persistent container data. Bind mounts map a host path directly into a container and are u

Answer

Named volumes are managed by Docker and are useful for persistent container data. Bind mounts map a host path directly into a container and are useful for local development or when host files must be shared.

Example: Container data path → named volume → persists beyond container removal

Diagram / flow: Named volume: Docker-managed; bind mount: host path mapped into container

Syntax

docker volume create dbdata
docker run -v dbdata:/var/lib/postgresql/data postgres

Example

Container data path → named volume → persists beyond container removal

Code example

docker volume create dbdata
docker run -v dbdata:/var/lib/postgresql/data postgres

Diagram

Named volume: Docker-managed; bind mount: host path mapped into container

Key Points

  • Named volumes are managed by Docker and are useful for persistent container data.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q89Kubernetes Workloads

Why create a Deployment instead of a standalone Pod?

A Deployment manages ReplicaSets and keeps the desired number of Pods running. It supports declarative updates and rollbacks; a standalone Pod do

Answer

A Deployment manages ReplicaSets and keeps the desired number of Pods running. It supports declarative updates and rollbacks; a standalone Pod does not provide the same rollout controller behavior.

Example: Deployment → ReplicaSet → Pods

Diagram / flow: Deployment controller reconciles desired replicas

Syntax

kubectl create deployment web --image=nginx

Example

Deployment → ReplicaSet → Pods

Code example

kubectl create deployment web --image=nginx

Diagram

Deployment controller reconciles desired replicas

Key Points

  • A Deployment manages ReplicaSets and keeps the desired number of Pods running.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q90Kubernetes Networking

Compare ClusterIP, NodePort, and LoadBalancer Services.

ClusterIP exposes a service inside the cluster; NodePort exposes a port on cluster nodes; LoadBalancer requests an external load balancer when su

Answer

ClusterIP exposes a service inside the cluster; NodePort exposes a port on cluster nodes; LoadBalancer requests an external load balancer when supported by the environment. Ingress or Gateway API can provide HTTP routing.

Example: Clients → Service virtual IP → ready Pod endpoints

Diagram / flow: ClusterIP internal; NodePort node-level port; LoadBalancer external integration

Syntax

type: ClusterIP

Example

Clients → Service virtual IP → ready Pod endpoints

Code example

type: ClusterIP

Diagram

ClusterIP internal; NodePort node-level port; LoadBalancer external integration

Key Points

  • ClusterIP exposes a service inside the cluster; NodePort exposes a port on cluster nodes; LoadBalancer requests an external load balancer when supported by the environment.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q92Configuration

What are ConfigMaps and Secrets?

ConfigMaps store non-confidential configuration; Secrets are intended for sensitive values but require appropriate encryption-at-rest and access

Answer

ConfigMaps store non-confidential configuration; Secrets are intended for sensitive values but require appropriate encryption-at-rest and access controls. Avoid assuming that base64 encoding alone protects Secret data.

Example: Configuration object → Pod environment or mounted file

Diagram / flow: ConfigMap for settings; Secret for credentials with restricted RBAC

Syntax

kubectl create configmap app-config --from-literal=MODE=prod

Example

Configuration object → Pod environment or mounted file

Code example

kubectl create configmap app-config --from-literal=MODE=prod

Diagram

ConfigMap for settings; Secret for credentials with restricted RBAC

Key Points

  • ConfigMaps store non-confidential configuration; Secrets are intended for sensitive values but require appropriate encryption-at-rest and access controls.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q26Docker build

What is a multi-stage Docker build?

A multi-stage build uses separate stages for compilation and runtime so build tools and intermediate files do not need to be included in the final image.

Answer

A multi-stage build uses separate stages for compilation and runtime so build tools and intermediate files do not need to be included in the final image.

Syntax

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApi.dll"]

Example

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /out FROM mcr.microsoft.com/dotnet/aspnet:8.0 WORKDIR /app COPY --from=build /out . ENTRYPOINT ["dotnet", "MyApi.dll"]

Code example

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApi.dll"]

Diagram

Docker build → container/orchestrator operation → result

Key Points

  • Reduces final image size and attack surface.
Q27Docker layers

How do image layers and build cache work?

Docker caches instructions and their inputs. If a step and its dependencies are unchanged, Docker may reuse that layer; order stable dependency steps before frequently changing sou

Answer

Docker caches instructions and their inputs. If a step and its dependencies are unchanged, Docker may reuse that layer; order stable dependency steps before frequently changing source files.

Syntax

COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

Example

COPY package*.json ./ RUN npm ci COPY . . RUN npm run build

Code example

COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

Diagram

Docker layers → container/orchestrator operation → result

Key Points

  • A `.dockerignore` prevents irrelevant files entering the build context.
Q28Docker Compose

How can Compose run an API and database together?

Define each service and a named volume for database persistence. Use service DNS names for container-to-container traffic.

Answer

Define each service and a named volume for database persistence. Use service DNS names for container-to-container traffic.

Syntax

services:
  api:
    build: .
    ports: ["8080:8080"]
    environment:
      DB_HOST: db
  db:
    image: postgres:16
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

Example

services: api: build: . ports: ["8080:8080"] environment: DB_HOST: db db: image: postgres:16 environment: POSTGRES_DB: app POSTGRES_USER: app POSTGRES_PASSWORD: ${DB_PASSWORD} volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata:

Code example

services:
  api:
    build: .
    ports: ["8080:8080"]
    environment:
      DB_HOST: db
  db:
    image: postgres:16
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

Diagram

Docker Compose → container/orchestrator operation → result

Key Points

  • Use a secrets manager or secure secret injection for production credentials.
Q29Docker networking

Compare bridge, host, and overlay networks.

Bridge networks connect containers on one Docker host. Host networking shares the host network namespace on supported platforms. Overlay networks connect services across hosts in c

Answer

Bridge networks connect containers on one Docker host. Host networking shares the host network namespace on supported platforms. Overlay networks connect services across hosts in compatible Docker setups.

Syntax

docker network create --driver bridge app-net
docker network ls

Example

docker network create --driver bridge app-net docker network ls

Code example

docker network create --driver bridge app-net
docker network ls

Diagram

Docker networking → container/orchestrator operation → result

Key Points

  • Choose the network model based on isolation and deployment topology.
Q30Image security

How do you reduce Docker image vulnerabilities?

Use trusted minimal base images, pin versions or digests, update dependencies, scan images, avoid secrets in layers, and run with least privilege.

Answer

Use trusted minimal base images, pin versions or digests, update dependencies, scan images, avoid secrets in layers, and run with least privilege.

Syntax

docker scout quickview my-image:1.0
docker image inspect my-image:1.0

Example

docker scout quickview my-image:1.0 docker image inspect my-image:1.0

Code example

docker scout quickview my-image:1.0
docker image inspect my-image:1.0

Diagram

Image security → container/orchestrator operation → result

Key Points

  • Scanning helps; it does not prove an image is secure.
Q31Container limits

How do CPU and memory limits work in Docker?

Runtime flags constrain CPU scheduling and memory use. If memory exceeds its limit, the container may be killed by the kernel.

Answer

Runtime flags constrain CPU scheduling and memory use. If memory exceeds its limit, the container may be killed by the kernel.

Syntax

docker run --cpus=1.5 --memory=512m my-image

Example

docker run --cpus=1.5 --memory=512m my-image

Code example

docker run --cpus=1.5 --memory=512m my-image

Diagram

Container limits → container/orchestrator operation → result

Key Points

  • Test limits under realistic load.
Q32Kubernetes architecture

What are the main control-plane components?

The API server exposes the Kubernetes API; etcd stores cluster state; the scheduler places Pods; and controller managers reconcile desired state.

Answer

The API server exposes the Kubernetes API; etcd stores cluster state; the scheduler places Pods; and controller managers reconcile desired state.

Syntax

kubectl get componentstatuses  # legacy/deprecated in many clusters
kubectl get nodes

Example

kubectl get componentstatuses # legacy/deprecated in many clusters kubectl get nodes

Code example

kubectl get componentstatuses  # legacy/deprecated in many clusters
kubectl get nodes

Diagram

Kubernetes architecture → container/orchestrator operation → result

Key Points

  • Managed Kubernetes may hide the control-plane infrastructure.
Q33Kubernetes scheduling

How does the scheduler choose a node?

The scheduler filters nodes against Pod constraints and then scores feasible nodes; the selected node is bound to the Pod.

Answer

The scheduler filters nodes against Pod constraints and then scores feasible nodes; the selected node is bound to the Pod.

Syntax

spec:
  nodeSelector:
    workload: general

Example

spec: nodeSelector: workload: general

Code example

spec:
  nodeSelector:
    workload: general

Diagram

Kubernetes scheduling → container/orchestrator operation → result

Key Points

  • Affinity, taints/tolerations, resources, and topology can influence placement.
Q34Requests and limits

What is the difference between resource requests and limits?

Requests influence scheduling and represent expected resource needs. Limits cap resource use; CPU is throttled above its limit, while memory overage can trigger an OOM kill.

Answer

Requests influence scheduling and represent expected resource needs. Limits cap resource use; CPU is throttled above its limit, while memory overage can trigger an OOM kill.

Syntax

resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
  limits:
    cpu: "1"
    memory: "512Mi"

Example

resources: requests: cpu: "250m" memory: "256Mi" limits: cpu: "1" memory: "512Mi"

Code example

resources:
  requests:
    cpu: "250m"
    memory: "256Mi"
  limits:
    cpu: "1"
    memory: "512Mi"

Diagram

Requests and limits → container/orchestrator operation → result

Key Points

  • Set requests based on observed workload needs.
Q35Autoscaling

How does Horizontal Pod Autoscaler work?

HPA adjusts a workload's replica count based on observed metrics relative to targets, commonly CPU or memory utilization or custom metrics.

Answer

HPA adjusts a workload's replica count based on observed metrics relative to targets, commonly CPU or memory utilization or custom metrics.

Syntax

kubectl autoscale deployment api --min=2 --max=10 --cpu-percent=70
kubectl get hpa

Example

kubectl autoscale deployment api --min=2 --max=10 --cpu-percent=70 kubectl get hpa

Code example

kubectl autoscale deployment api --min=2 --max=10 --cpu-percent=70
kubectl get hpa

Diagram

Autoscaling → container/orchestrator operation → result

Key Points

  • CPU utilization targets generally require CPU requests.
Q36Ingress

What is an Ingress?

Ingress defines HTTP and HTTPS routing rules from outside the cluster to Services. An Ingress controller must implement those rules.

Answer

Ingress defines HTTP and HTTPS routing rules from outside the cluster to Services. An Ingress controller must implement those rules.

Syntax

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app
spec:
  ingressClassName: nginx
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

Example

apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: app spec: ingressClassName: nginx rules: - host: app.example.com http: paths: - path: / pathType: Prefix backend: service: name: web port: number: 80

Code example

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app
spec:
  ingressClassName: nginx
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

Diagram

Ingress → container/orchestrator operation → result

Key Points

  • Ingress is not itself the controller or load balancer.
Q37Service discovery

How do Pods discover other services?

Kubernetes DNS publishes names for Services. Clients use a Service DNS name rather than hard-coded Pod IPs.

Answer

Kubernetes DNS publishes names for Services. Clients use a Service DNS name rather than hard-coded Pod IPs.

Syntax

http://orders.default.svc.cluster.local:8080

Example

http://orders.default.svc.cluster.local:8080

Code example

http://orders.default.svc.cluster.local:8080

Diagram

Service discovery → container/orchestrator operation → result

Key Points

  • Short names are namespace-relative; cross-namespace calls should use the target namespace.
Q38Rolling updates

How do you perform and verify a rollout?

Update the image or manifest, monitor rollout status, and use rollout history or undo if the release is unhealthy.

Answer

Update the image or manifest, monitor rollout status, and use rollout history or undo if the release is unhealthy.

Syntax

kubectl set image deployment/api api=registry.example.com/api:2.0
kubectl rollout status deployment/api
kubectl rollout undo deployment/api

Example

kubectl set image deployment/api api=registry.example.com/api:2.0 kubectl rollout status deployment/api kubectl rollout undo deployment/api

Code example

kubectl set image deployment/api api=registry.example.com/api:2.0
kubectl rollout status deployment/api
kubectl rollout undo deployment/api

Diagram

Rolling updates → container/orchestrator operation → result

Key Points

  • Use immutable version tags or digests.
Q39Stateful workloads

When should you use a StatefulSet?

A StatefulSet provides stable Pod identities and ordered deployment/scaling semantics, commonly paired with persistent volume claims for stateful systems.

Answer

A StatefulSet provides stable Pod identities and ordered deployment/scaling semantics, commonly paired with persistent volume claims for stateful systems.

Syntax

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: database
spec:
  serviceName: database
  replicas: 3
  selector:
    matchLabels: {app: database}
  template:
    metadata:
      labels: {app: database}
    spec:
      containers:
        - name: db
          image: postgres:16

Example

apiVersion: apps/v1 kind: StatefulSet metadata: name: database spec: serviceName: database replicas: 3 selector: matchLabels: {app: database} template: metadata: labels: {app: database} spec: containers: - name: db image: postgres:16

Code example

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: database
spec:
  serviceName: database
  replicas: 3
  selector:
    matchLabels: {app: database}
  template:
    metadata:
      labels: {app: database}
    spec:
      containers:
        - name: db
          image: postgres:16

Diagram

Stateful workloads → container/orchestrator operation → result

Key Points

  • A StatefulSet alone does not make a database highly available.
Q40Persistent storage

How does PersistentVolumeClaim work?

A PVC requests storage capacity and access modes. Kubernetes binds it to a suitable PersistentVolume or provisions storage through a StorageClass.

Answer

A PVC requests storage capacity and access modes. Kubernetes binds it to a suitable PersistentVolume or provisions storage through a StorageClass.

Syntax

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: app-data
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 10Gi

Example

apiVersion: v1 kind: PersistentVolumeClaim metadata: name: app-data spec: accessModes: [ReadWriteOnce] resources: requests: storage: 10Gi

Code example

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: app-data
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 10Gi

Diagram

Persistent storage → container/orchestrator operation → result

Key Points

  • Storage semantics depend on the CSI driver and storage provider.
Q41Configuration rollout

What happens when a ConfigMap changes?

Environment variables sourced from a ConfigMap do not update inside existing processes automatically. Mounted ConfigMap files may update eventually, but the application must reload

Answer

Environment variables sourced from a ConfigMap do not update inside existing processes automatically. Mounted ConfigMap files may update eventually, but the application must reload them.

Syntax

kubectl rollout restart deployment/api

Example

kubectl rollout restart deployment/api

Code example

kubectl rollout restart deployment/api

Diagram

Configuration rollout → container/orchestrator operation → result

Key Points

  • Use a checksum annotation or controlled rollout to restart Pods after config changes.
Q42Secrets management

How should production credentials be supplied to Pods?

Use a managed secret store or a controlled Kubernetes Secret workflow, limit access with RBAC, enable encryption at rest, rotate credentials, and avoid logging them.

Answer

Use a managed secret store or a controlled Kubernetes Secret workflow, limit access with RBAC, enable encryption at rest, rotate credentials, and avoid logging them.

Syntax

kubectl create secret generic db-creds --from-file=password=./db-password.txt

Example

kubectl create secret generic db-creds --from-file=password=./db-password.txt

Code example

kubectl create secret generic db-creds --from-file=password=./db-password.txt

Diagram

Secrets management → container/orchestrator operation → result

Key Points

  • Never commit secret files or print them in CI logs.
Q43Network policy

What is a NetworkPolicy?

A NetworkPolicy specifies allowed ingress and egress traffic for selected Pods, but it requires a network plugin that enforces policies.

Answer

A NetworkPolicy specifies allowed ingress and egress traffic for selected Pods, but it requires a network plugin that enforces policies.

Syntax

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend

Example

apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-api spec: podSelector: matchLabels: app: api policyTypes: [Ingress] ingress: - from: - podSelector: matchLabels: app: frontend

Code example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend

Diagram

Network policy → container/orchestrator operation → result

Key Points

  • Policies are additive; verify default-deny and DNS needs.
Q44RBAC

How does Kubernetes RBAC work?

Roles define permissions on resources; RoleBindings grant those permissions within a namespace. ClusterRoles and ClusterRoleBindings can grant cluster-scoped permissions.

Answer

Roles define permissions on resources; RoleBindings grant those permissions within a namespace. ClusterRoles and ClusterRoleBindings can grant cluster-scoped permissions.

Syntax

kubectl create role pod-reader --verb=get,list,watch --resource=pods -n staging
kubectl create rolebinding reader-binding --role=pod-reader --user=developer -n staging

Example

kubectl create role pod-reader --verb=get,list,watch --resource=pods -n staging kubectl create rolebinding reader-binding --role=pod-reader --user=developer -n staging

Code example

kubectl create role pod-reader --verb=get,list,watch --resource=pods -n staging
kubectl create rolebinding reader-binding --role=pod-reader --user=developer -n staging

Diagram

RBAC → container/orchestrator operation → result

Key Points

  • Prefer least privilege and review service-account permissions.
Q45Probes

How do startup, readiness, and liveness probes differ?

Startup probes give slow-starting applications time to initialize. Readiness controls whether traffic is sent to a Pod. Liveness detects stuck processes and can trigger restarts.

Answer

Startup probes give slow-starting applications time to initialize. Readiness controls whether traffic is sent to a Pod. Liveness detects stuck processes and can trigger restarts.

Syntax

startupProbe:
  httpGet: {path: /health/startup, port: 8080}
  failureThreshold: 30
  periodSeconds: 5
livenessProbe:
  httpGet: {path: /health/live, port: 8080}
  periodSeconds: 10

Example

startupProbe: httpGet: {path: /health/startup, port: 8080} failureThreshold: 30 periodSeconds: 5 livenessProbe: httpGet: {path: /health/live, port: 8080} periodSeconds: 10

Code example

startupProbe:
  httpGet: {path: /health/startup, port: 8080}
  failureThreshold: 30
  periodSeconds: 5
livenessProbe:
  httpGet: {path: /health/live, port: 8080}
  periodSeconds: 10

Diagram

Probes → container/orchestrator operation → result

Key Points

  • A startup probe suppresses liveness/readiness until startup succeeds.
Q46Pod disruption

What is a PodDisruptionBudget?

A PDB limits voluntary disruptions by specifying a minimum available or maximum unavailable number of Pods during supported eviction workflows.

Answer

A PDB limits voluntary disruptions by specifying a minimum available or maximum unavailable number of Pods during supported eviction workflows.

Syntax

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api-pdb
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: api

Example

apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: api-pdb spec: minAvailable: 2 selector: matchLabels: app: api

Code example

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api-pdb
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: api

Diagram

Pod disruption → container/orchestrator operation → result

Key Points

  • A PDB does not prevent all involuntary failures.
Q47Jobs and CronJobs

When do you use Job and CronJob?

A Job runs Pods to completion. A CronJob creates Jobs on a schedule for recurring tasks such as reports, cleanup, or backups.

Answer

A Job runs Pods to completion. A CronJob creates Jobs on a schedule for recurring tasks such as reports, cleanup, or backups.

Syntax

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: cleanup
              image: busybox:1.36
              command: ["sh", "-c", "echo cleanup"]

Example

apiVersion: batch/v1 kind: CronJob metadata: name: cleanup spec: schedule: "0 2 * * *" jobTemplate: spec: template: spec: restartPolicy: OnFailure containers: - name: cleanup image: busybox:1.36 command: ["sh", "-c", "echo cleanup"]

Code example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: cleanup
              image: busybox:1.36
              command: ["sh", "-c", "echo cleanup"]

Diagram

Jobs and CronJobs → container/orchestrator operation → result

Key Points

  • Make scheduled tasks idempotent and consider concurrency policy.
Q48Helm

What is Helm?

Helm packages Kubernetes resources into charts with templates, values, and release history, helping teams configure and deploy applications consistently.

Answer

Helm packages Kubernetes resources into charts with templates, values, and release history, helping teams configure and deploy applications consistently.

Syntax

helm upgrade --install my-app ./chart -f values-prod.yaml
helm list -A

Example

helm upgrade --install my-app ./chart -f values-prod.yaml helm list -A

Code example

helm upgrade --install my-app ./chart -f values-prod.yaml
helm list -A

Diagram

Helm → container/orchestrator operation → result

Key Points

  • Review rendered manifests and secret handling before deploying.
Q49Observability

How do you monitor Kubernetes workloads?

Collect metrics, logs, and traces; monitor resource saturation, error rates, latency, restarts, scheduling failures, and rollout health.

Answer

Collect metrics, logs, and traces; monitor resource saturation, error rates, latency, restarts, scheduling failures, and rollout health.

Syntax

kubectl top nodes
kubectl top pods -A
kubectl get events -A --sort-by=.lastTimestamp

Example

kubectl top nodes kubectl top pods -A kubectl get events -A --sort-by=.lastTimestamp

Code example

kubectl top nodes
kubectl top pods -A
kubectl get events -A --sort-by=.lastTimestamp

Diagram

Observability → container/orchestrator operation → result

Key Points

  • `kubectl top` needs a functioning metrics pipeline.
Q50Troubleshooting

A Pod is stuck in CrashLoopBackOff. What do you check?

Inspect current and previous logs, Pod events, startup command, configuration, mounted files, probes, permissions, and memory limits. Fix the cause before repeatedly restarting it.

Answer

Inspect current and previous logs, Pod events, startup command, configuration, mounted files, probes, permissions, and memory limits. Fix the cause before repeatedly restarting it.

Syntax

kubectl logs <pod> --previous
kubectl describe pod <pod>
kubectl get events --sort-by=.lastTimestamp

Example

kubectl logs <pod> --previous kubectl describe pod <pod> kubectl get events --sort-by=.lastTimestamp

Code example

kubectl logs <pod> --previous
kubectl describe pod <pod>
kubectl get events --sort-by=.lastTimestamp

Diagram

Troubleshooting → container/orchestrator operation → result

Key Points

  • CrashLoopBackOff is a backoff status, not the root cause.
Q51Troubleshooting

A Pod is stuck in Pending. What do you check?

Check events for insufficient CPU or memory, unbound PVCs, node selectors, affinity, taints, quota, and unavailable nodes.

Answer

Check events for insufficient CPU or memory, unbound PVCs, node selectors, affinity, taints, quota, and unavailable nodes.

Syntax

kubectl describe pod <pod>
kubectl get nodes
kubectl get pvc -A

Example

kubectl describe pod <pod> kubectl get nodes kubectl get pvc -A

Code example

kubectl describe pod <pod>
kubectl get nodes
kubectl get pvc -A

Diagram

Troubleshooting → container/orchestrator operation → result

Key Points

  • Scheduling events usually point to the blocking constraint.
Q52Troubleshooting

A Service cannot reach its Pods. How do you debug it?

Verify selectors and Pod labels, EndpointSlices, target ports, readiness, DNS, network policies, and whether the application listens on the expected interface.

Answer

Verify selectors and Pod labels, EndpointSlices, target ports, readiness, DNS, network policies, and whether the application listens on the expected interface.

Syntax

kubectl get svc <service> -o yaml
kubectl get endpointslice -l kubernetes.io/service-name=<service>
kubectl get pods --show-labels

Example

kubectl get svc <service> -o yaml kubectl get endpointslice -l kubernetes.io/service-name=<service> kubectl get pods --show-labels

Code example

kubectl get svc <service> -o yaml
kubectl get endpointslice -l kubernetes.io/service-name=<service>
kubectl get pods --show-labels

Diagram

Troubleshooting → container/orchestrator operation → result

Key Points

  • A Service with no ready endpoints commonly indicates a selector or readiness issue.
Q53Image distribution

What causes ImagePullBackOff?

Typical causes include a wrong image name or tag, missing registry credentials, network/DNS issues, rate limits, or an unsupported architecture.

Answer

Typical causes include a wrong image name or tag, missing registry credentials, network/DNS issues, rate limits, or an unsupported architecture.

Syntax

kubectl describe pod <pod>
kubectl create secret docker-registry regcred --docker-server=registry.example.com --docker-username=<user> --docker-password=<token>

Example

kubectl describe pod <pod> kubectl create secret docker-registry regcred --docker-server=registry.example.com --docker-username=<user> --docker-password=<token>

Code example

kubectl describe pod <pod>
kubectl create secret docker-registry regcred --docker-server=registry.example.com --docker-username=<user> --docker-password=<token>

Diagram

Image distribution → container/orchestrator operation → result

Key Points

  • Attach registry credentials through imagePullSecrets or a service account.
Q54Deployment strategies

Compare Recreate and RollingUpdate strategies.

Recreate terminates existing Pods before creating new ones and may cause downtime. RollingUpdate gradually replaces Pods within configured surge and unavailable limits.

Answer

Recreate terminates existing Pods before creating new ones and may cause downtime. RollingUpdate gradually replaces Pods within configured surge and unavailable limits.

Syntax

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0

Example

strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0

Code example

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0

Diagram

Deployment strategies → container/orchestrator operation → result

Key Points

  • Capacity and readiness determine whether zero-downtime rollout is achievable.
Q55Docker and Kubernetes

Show the path from source code to running Pods.

A CI pipeline tests and builds the image, pushes it to a registry, then deployment automation applies Kubernetes manifests that create and manage Pods.

Answer

A CI pipeline tests and builds the image, pushes it to a registry, then deployment automation applies Kubernetes manifests that create and manage Pods.

Syntax

Source -> CI tests -> Docker build -> Image registry
                                  |
                                  v
Manifest / Helm -> Kubernetes API -> Deployment -> Pods

Example

Source -> CI tests -> Docker build -> Image registry | v Manifest / Helm -> Kubernetes API -> Deployment -> Pods

Code example

Source -> CI tests -> Docker build -> Image registry
                                  |
                                  v
Manifest / Helm -> Kubernetes API -> Deployment -> Pods

Diagram

Docker and Kubernetes → container/orchestrator operation → result

Key Points

  • Keep build and deployment permissions scoped separately.
Q79Docker Images

Why use a multi-stage Docker build?

Multi-stage builds separate compilation from the runtime image. Copy only required artifacts from the build stage to reduce image size and avoid

Answer

Multi-stage builds separate compilation from the runtime image. Copy only required artifacts from the build stage to reduce image size and avoid shipping compilers or build dependencies unnecessarily.

Example: SDK build stage → publish artifacts → lean runtime stage

Diagram / flow: Builder image → compiled/published output → runtime image

Syntax

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
# build app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
COPY --from=build /out .

Example

SDK build stage → publish artifacts → lean runtime stage

Code example

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
# build app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
COPY --from=build /out .

Diagram

Builder image → compiled/published output → runtime image

Key Points

  • Multi-stage builds separate compilation from the runtime image.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q80Container Security

Why should a container run as a non-root user?

A non-root process reduces the impact of a compromised application. Use an appropriate user in the image and ensure file permissions, mounted vol

Answer

A non-root process reduces the impact of a compromised application. Use an appropriate user in the image and ensure file permissions, mounted volumes, and required ports support that user.

Example: Image starts process as unprivileged user → reduced container-level privileges

Diagram / flow: Docker image → USER app → application process

Syntax

USER app

Example

Image starts process as unprivileged user → reduced container-level privileges

Code example

USER app

Diagram

Docker image → USER app → application process

Key Points

  • A non-root process reduces the impact of a compromised application.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q81Container Operations

How does Docker HEALTHCHECK work?

HEALTHCHECK runs a command to report container health. It can expose a failing application process even when the container is still running; orch

Answer

HEALTHCHECK runs a command to report container health. It can expose a failing application process even when the container is still running; orchestration behavior and restart decisions should be configured separately.

Example: Container running → health probe → healthy or unhealthy status

Diagram / flow: Docker engine executes probe → records health status

Syntax

HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/health || exit 1

Example

Container running → health probe → healthy or unhealthy status

Code example

HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/health || exit 1

Diagram

Docker engine executes probe → records health status

Key Points

  • HEALTHCHECK runs a command to report container health.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q83Networking

When would you use bridge, host, or none networking?

Bridge networking provides an isolated network with container connectivity; host networking shares the host network namespace on supported platfo

Answer

Bridge networking provides an isolated network with container connectivity; host networking shares the host network namespace on supported platforms; none disables normal network connectivity. Choose based on isolation and platform needs.

Example: Container → selected network mode → available interfaces and routes

Diagram / flow: Bridge: isolated network; host: host network; none: no standard network

Syntax

docker network create app-net
docker run --network app-net myapp

Example

Container → selected network mode → available interfaces and routes

Code example

docker network create app-net
docker run --network app-net myapp

Diagram

Bridge: isolated network; host: host network; none: no standard network

Key Points

  • Bridge networking provides an isolated network with container connectivity; host networking shares the host network namespace on supported platforms; none disables normal network connectivity.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q84Docker Compose

How can Compose wait for a dependency health check?

Compose can use a health check on a dependency and a condition such as service_healthy where supported. This helps startup ordering but does not

Answer

Compose can use a health check on a dependency and a condition such as service_healthy where supported. This helps startup ordering but does not replace application-level retries after startup.

Example: Database starts → health check passes → dependent service starts

Diagram / flow: Compose dependency graph + health status controls startup order

Syntax

depends_on:
  db:
    condition: service_healthy

Example

Database starts → health check passes → dependent service starts

Code example

depends_on:
  db:
    condition: service_healthy

Diagram

Compose dependency graph + health status controls startup order

Key Points

  • Compose can use a health check on a dependency and a condition such as service_healthy where supported.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q85Container Operations

How do CPU and memory limits protect a host?

Resource limits prevent one container from consuming unbounded host resources. Memory limits can lead to OOM termination; CPU limits throttle exe

Answer

Resource limits prevent one container from consuming unbounded host resources. Memory limits can lead to OOM termination; CPU limits throttle execution, so tune limits using measured workloads.

Example: Container workload → cgroup limits → bounded CPU/memory consumption

Diagram / flow: Configured limits → kernel enforcement → throttle or OOM behavior

Syntax

docker run --memory=512m --cpus=1.5 myapp

Example

Container workload → cgroup limits → bounded CPU/memory consumption

Code example

docker run --memory=512m --cpus=1.5 myapp

Diagram

Configured limits → kernel enforcement → throttle or OOM behavior

Key Points

  • Resource limits prevent one container from consuming unbounded host resources.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q87Container Security

How should secrets be supplied to containers?

Avoid baking credentials into image layers or committing them to source control. Use an appropriate secret manager or orchestrator secret mechani

Answer

Avoid baking credentials into image layers or committing them to source control. Use an appropriate secret manager or orchestrator secret mechanism, restrict access, rotate credentials, and avoid logging secret values.

Example: Secret manager → authorized runtime injection → application

Diagram / flow: Secret store → controlled delivery → process; never embed secret in image

Syntax

docker run --env-file local-dev.env myapp  # local development only

Example

Secret manager → authorized runtime injection → application

Code example

docker run --env-file local-dev.env myapp  # local development only

Diagram

Secret store → controlled delivery → process; never embed secret in image

Key Points

  • Avoid baking credentials into image layers or committing them to source control.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q88Observability

How should container logs be collected?

Applications should generally write structured logs to stdout/stderr, while a platform or logging driver collects, routes, and retains them. Set

Answer

Applications should generally write structured logs to stdout/stderr, while a platform or logging driver collects, routes, and retains them. Set retention and rotation limits to prevent disk exhaustion.

Example: Application stdout/stderr → runtime logging driver → central log platform

Diagram / flow: Container logs → collector/driver → searchable log store

Syntax

docker logs <container>
docker run --log-opt max-size=10m --log-opt max-file=3 myapp

Example

Application stdout/stderr → runtime logging driver → central log platform

Code example

docker logs <container>
docker run --log-opt max-size=10m --log-opt max-file=3 myapp

Diagram

Container logs → collector/driver → searchable log store

Key Points

  • Applications should generally write structured logs to stdout/stderr, while a platform or logging driver collects, routes, and retains them.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q91Kubernetes Operations

How do readiness, liveness, and startup probes differ?

Readiness controls whether a Pod receives traffic; liveness detects a stuck container and may trigger restart; startup gives slow-starting applic

Answer

Readiness controls whether a Pod receives traffic; liveness detects a stuck container and may trigger restart; startup gives slow-starting applications time before other probes begin. Probe endpoints should reflect distinct purposes.

Example: Startup probe succeeds → readiness gates traffic; liveness checks ongoing health

Diagram / flow: Startup → readiness for routing; liveness for restart decisions

Syntax

readinessProbe:
  httpGet: { path: /ready, port: 8080 }

Example

Startup probe succeeds → readiness gates traffic; liveness checks ongoing health

Code example

readinessProbe:
  httpGet: { path: /ready, port: 8080 }

Diagram

Startup → readiness for routing; liveness for restart decisions

Key Points

  • Readiness controls whether a Pod receives traffic; liveness detects a stuck container and may trigger restart; startup gives slow-starting applications time before other probes begin.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q93Kubernetes Scheduling

How do CPU and memory requests differ from limits?

Requests influence scheduling and represent expected resource allocation; limits cap usage. CPU excess is throttled, while exceeding a memory lim

Answer

Requests influence scheduling and represent expected resource allocation; limits cap usage. CPU excess is throttled, while exceeding a memory limit can cause OOM termination. Correct values require observation under load.

Example: Scheduler uses requests → kubelet/runtime enforces limits

Diagram / flow: Requests affect placement; limits constrain runtime use

Syntax

resources:
  requests: { cpu: "100m", memory: "128Mi" }
  limits: { cpu: "500m", memory: "512Mi" }

Example

Scheduler uses requests → kubelet/runtime enforces limits

Code example

resources:
  requests: { cpu: "100m", memory: "128Mi" }
  limits: { cpu: "500m", memory: "512Mi" }

Diagram

Requests affect placement; limits constrain runtime use

Key Points

  • Requests influence scheduling and represent expected resource allocation; limits cap usage.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q94Kubernetes Scaling

How does a Horizontal Pod Autoscaler work?

HPA adjusts workload replicas based on configured metrics such as CPU utilization or custom/external metrics. Resource requests and metrics avail

Answer

HPA adjusts workload replicas based on configured metrics such as CPU utilization or custom/external metrics. Resource requests and metrics availability matter; scaling policies and stabilization help avoid flapping.

Example: Metrics → HPA controller → desired replicas → Deployment/ReplicaSet

Diagram / flow: Metric target exceeded → increase replicas; below target → scale down subject to policy

Syntax

kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70

Example

Metrics → HPA controller → desired replicas → Deployment/ReplicaSet

Code example

kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70

Diagram

Metric target exceeded → increase replicas; below target → scale down subject to policy

Key Points

  • HPA adjusts workload replicas based on configured metrics such as CPU utilization or custom/external metrics.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q95Kubernetes Deployments

How do rolling updates reduce application downtime?

A Deployment gradually replaces old Pods with new ones based on maxSurge and maxUnavailable. Readiness probes and adequate capacity are important

Answer

A Deployment gradually replaces old Pods with new ones based on maxSurge and maxUnavailable. Readiness probes and adequate capacity are important; incompatible database changes can still break a rollout.

Example: Create new Pods → wait until ready → terminate old Pods

Diagram / flow: Deployment rollout uses readiness and surge/unavailable settings

Syntax

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0

Example

Create new Pods → wait until ready → terminate old Pods

Code example

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0

Diagram

Deployment rollout uses readiness and surge/unavailable settings

Key Points

  • A Deployment gradually replaces old Pods with new ones based on maxSurge and maxUnavailable.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q99Kubernetes Networking

What is the role of Ingress or Gateway API?

Ingress and Gateway API describe HTTP(S) routing from outside a cluster to services, subject to a compatible controller or implementation. They d

Answer

Ingress and Gateway API describe HTTP(S) routing from outside a cluster to services, subject to a compatible controller or implementation. They do not automatically provide routing without that implementation.

Example: External client → ingress/gateway controller → Service → Pods

Diagram / flow: Host/path rules → controller → backend service

Syntax

host: example.com
http:
  paths: ...

Example

External client → ingress/gateway controller → Service → Pods

Code example

host: example.com
http:
  paths: ...

Diagram

Host/path rules → controller → backend service

Key Points

  • Ingress and Gateway API describe HTTP(S) routing from outside a cluster to services, subject to a compatible controller or implementation.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q56Architecture

Design a highly available web service on Kubernetes.

Use multiple replicas across failure domains, a Service and ingress/load balancer, readiness checks, disruption budgets, resource requests, autoscaling, and observability. Make the

Answer

Use multiple replicas across failure domains, a Service and ingress/load balancer, readiness checks, disruption budgets, resource requests, autoscaling, and observability. Make the application stateless or externalize durable state.

Syntax

Client -> Load Balancer -> Ingress -> Service -> Pods across zones
                                      Deployment + HPA
Pods -> managed database / cache / queue

Example

Client -> Load Balancer -> Ingress -> Service -> Pods across zones Deployment + HPA Pods -> managed database / cache / queue

Code example

Client -> Load Balancer -> Ingress -> Service -> Pods across zones
                                      Deployment + HPA
Pods -> managed database / cache / queue

Diagram

Architecture → container/orchestrator operation → result

Key Points

  • Plan capacity, dependencies, failover, backups, and SLOs.
Q57Autoscaling

Why might HPA not scale a Deployment?

Check whether metrics are available, resource requests exist for utilization-based targets, the HPA targets the right workload, max replicas are reached, and cluster capacity is av

Answer

Check whether metrics are available, resource requests exist for utilization-based targets, the HPA targets the right workload, max replicas are reached, and cluster capacity is available.

Syntax

kubectl describe hpa api
kubectl top pods
kubectl get events -A --sort-by=.lastTimestamp

Example

kubectl describe hpa api kubectl top pods kubectl get events -A --sort-by=.lastTimestamp

Code example

kubectl describe hpa api
kubectl top pods
kubectl get events -A --sort-by=.lastTimestamp

Diagram

Autoscaling → container/orchestrator operation → result

Key Points

  • HPA scaling and cluster node scaling are separate control loops.
Q58Cluster scaling

How do HPA and Cluster Autoscaler differ?

HPA changes workload replica counts. Cluster Autoscaler adjusts node capacity when Pods cannot be scheduled or nodes are underutilized, subject to provider and configuration constr

Answer

HPA changes workload replica counts. Cluster Autoscaler adjusts node capacity when Pods cannot be scheduled or nodes are underutilized, subject to provider and configuration constraints.

Syntax

Traffic increase -> HPA adds Pods -> Pending Pods -> node autoscaler may add nodes

Example

Traffic increase -> HPA adds Pods -> Pending Pods -> node autoscaler may add nodes

Code example

Traffic increase -> HPA adds Pods -> Pending Pods -> node autoscaler may add nodes

Diagram

Cluster scaling → container/orchestrator operation → result

Key Points

  • Neither can fix application bottlenecks or quotas automatically.
Q59Security

How do you harden a Kubernetes workload?

Use non-root users, read-only root filesystems where possible, drop capabilities, seccomp, restrictive Pod Security settings, least-privilege RBAC, network policies, signed/scanned

Answer

Use non-root users, read-only root filesystems where possible, drop capabilities, seccomp, restrictive Pod Security settings, least-privilege RBAC, network policies, signed/scanned images, and secret rotation.

Syntax

securityContext:
  runAsNonRoot: true
  runAsUser: 10001
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]

Example

securityContext: runAsNonRoot: true runAsUser: 10001 allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: ["ALL"]

Code example

securityContext:
  runAsNonRoot: true
  runAsUser: 10001
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]

Diagram

Security → container/orchestrator operation → result

Key Points

  • Validate compatibility with application writes and platform requirements.
Q60Supply chain

How would you secure the container supply chain?

Use trusted build systems, dependency pinning, SBOMs, vulnerability scanning, image signing and verification, protected registries, and deployment policy enforcement.

Answer

Use trusted build systems, dependency pinning, SBOMs, vulnerability scanning, image signing and verification, protected registries, and deployment policy enforcement.

Syntax

docker build -t registry.example.com/api:1.2.3 .
docker push registry.example.com/api:1.2.3

Example

docker build -t registry.example.com/api:1.2.3 . docker push registry.example.com/api:1.2.3

Code example

docker build -t registry.example.com/api:1.2.3 .
docker push registry.example.com/api:1.2.3

Diagram

Supply chain → container/orchestrator operation → result

Key Points

  • Use immutable digests in deployment for reproducibility.
Q61Availability

How do you deploy across multiple availability zones?

Spread replicas across zones using topology spread constraints or pod anti-affinity, use multi-zone-capable storage and load balancing, and validate dependency resilience.

Answer

Spread replicas across zones using topology spread constraints or pod anti-affinity, use multi-zone-capable storage and load balancing, and validate dependency resilience.

Syntax

topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: api

Example

topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app: api

Code example

topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: api

Diagram

Availability → container/orchestrator operation → result

Key Points

  • Enough replicas and capacity must exist in each relevant zone.
Q62Scheduling

When would you use taints, tolerations, and affinity?

Taints repel Pods unless they tolerate the taint. Affinity attracts or constrains placement based on labels. Use them to isolate specialized workloads or express topology requireme

Answer

Taints repel Pods unless they tolerate the taint. Affinity attracts or constrains placement based on labels. Use them to isolate specialized workloads or express topology requirements.

Syntax

kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# Pod spec:
tolerations:
  - key: dedicated
    operator: Equal
    value: gpu
    effect: NoSchedule

Example

kubectl taint nodes node-1 dedicated=gpu:NoSchedule # Pod spec: tolerations: - key: dedicated operator: Equal value: gpu effect: NoSchedule

Code example

kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# Pod spec:
tolerations:
  - key: dedicated
    operator: Equal
    value: gpu
    effect: NoSchedule

Diagram

Scheduling → container/orchestrator operation → result

Key Points

  • Toleration permits placement but does not force it.
Q63Graceful shutdown

How do you safely terminate Pods during a rollout?

Handle termination signals, stop accepting new work, drain in-flight requests, configure a suitable termination grace period, and ensure readiness becomes false during shutdown.

Answer

Handle termination signals, stop accepting new work, drain in-flight requests, configure a suitable termination grace period, and ensure readiness becomes false during shutdown.

Syntax

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: api
      lifecycle:
        preStop:
          exec:
            command: ["sh", "-c", "sleep 5"]

Example

spec: terminationGracePeriodSeconds: 45 containers: - name: api lifecycle: preStop: exec: command: ["sh", "-c", "sleep 5"]

Code example

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: api
      lifecycle:
        preStop:
          exec:
            command: ["sh", "-c", "sleep 5"]

Diagram

Graceful shutdown → container/orchestrator operation → result

Key Points

  • A preStop sleep is only an example; implement app-level graceful shutdown.
Q64Reliability

How do you design safe retries and timeouts?

Set bounded timeouts, retry only transient failures, use exponential backoff with jitter, cap attempts, and make non-idempotent operations safe through idempotency keys or deduplic

Answer

Set bounded timeouts, retry only transient failures, use exponential backoff with jitter, cap attempts, and make non-idempotent operations safe through idempotency keys or deduplication.

Syntax

delay = min(maxDelay, baseDelay * 2**attempt) + randomJitter

Example

delay = min(maxDelay, baseDelay * 2**attempt) + randomJitter

Code example

delay = min(maxDelay, baseDelay * 2**attempt) + randomJitter

Diagram

Reliability → container/orchestrator operation → result

Key Points

  • Retries can amplify outages; coordinate retry budgets across layers.
Q65Service mesh

What does a service mesh provide?

A service mesh can centralize service-to-service traffic policy, mutual TLS, retries, telemetry, and traffic splitting through data-plane proxies and a control plane.

Answer

A service mesh can centralize service-to-service traffic policy, mutual TLS, retries, telemetry, and traffic splitting through data-plane proxies and a control plane.

Syntax

Service A -> sidecar/proxy == mTLS == sidecar/proxy -> Service B

Example

Service A -> sidecar/proxy == mTLS == sidecar/proxy -> Service B

Code example

Service A -> sidecar/proxy == mTLS == sidecar/proxy -> Service B

Diagram

Service mesh → container/orchestrator operation → result

Key Points

  • It adds operational complexity and does not replace application authorization.
Q66Networking

What is the difference between Ingress and Gateway API?

Ingress provides a comparatively simple HTTP routing model. Gateway API offers more expressive, role-oriented resources for listeners, routes, and policy, depending on controller s

Answer

Ingress provides a comparatively simple HTTP routing model. Gateway API offers more expressive, role-oriented resources for listeners, routes, and policy, depending on controller support.

Syntax

Gateway -> HTTPRoute -> Service -> Pods

Example

Gateway -> HTTPRoute -> Service -> Pods

Code example

Gateway -> HTTPRoute -> Service -> Pods

Diagram

Networking → container/orchestrator operation → result

Key Points

  • Check the installed controller's supported API versions and features.
Q67State and resilience

How do you run a stateful database on Kubernetes safely?

Use an operator or managed database where appropriate; plan persistent storage, backups, restore tests, replication, upgrades, fencing, monitoring, and failure recovery. StatefulSe

Answer

Use an operator or managed database where appropriate; plan persistent storage, backups, restore tests, replication, upgrades, fencing, monitoring, and failure recovery. StatefulSet alone is not sufficient.

Syntax

Application Pods -> Database Service -> primary / replicas
                              Persistent volumes + backups

Example

Application Pods -> Database Service -> primary / replicas Persistent volumes + backups

Code example

Application Pods -> Database Service -> primary / replicas
                              Persistent volumes + backups

Diagram

State and resilience → container/orchestrator operation → result

Key Points

  • Managed services may reduce operational risk for critical databases.
Q68Disaster recovery

How do you plan Kubernetes disaster recovery?

Define RPO and RTO, back up cluster configuration and persistent data, store backups outside the failure domain, test restores, and document regional recovery steps.

Answer

Define RPO and RTO, back up cluster configuration and persistent data, store backups outside the failure domain, test restores, and document regional recovery steps.

Syntax

Primary region -> encrypted backups -> secondary region restore -> validation -> traffic cutover

Example

Primary region -> encrypted backups -> secondary region restore -> validation -> traffic cutover

Code example

Primary region -> encrypted backups -> secondary region restore -> validation -> traffic cutover

Diagram

Disaster recovery → container/orchestrator operation → result

Key Points

  • A successful backup is not proven until a restore is tested.
Q69Capacity planning

How do you size requests and limits for a production service?

Measure representative load, estimate per-request CPU and memory, test bursts and concurrency, set requests to support scheduling, and apply limits after evaluating throttling and

Answer

Measure representative load, estimate per-request CPU and memory, test bursts and concurrency, set requests to support scheduling, and apply limits after evaluating throttling and OOM risk.

Syntax

required replicas ≈ peak sustainable workload / tested sustainable capacity per Pod

Example

required replicas ≈ peak sustainable workload / tested sustainable capacity per Pod

Code example

required replicas ≈ peak sustainable workload / tested sustainable capacity per Pod

Diagram

Capacity planning → container/orchestrator operation → result

Key Points

  • Include headroom, startup spikes, sidecars, and failure scenarios.
Q70Zero downtime

How do you achieve a low-downtime deployment?

Use readiness probes, rolling updates with appropriate surge/unavailable settings, backward-compatible database changes, graceful shutdown, and progressive delivery with metrics-ba

Answer

Use readiness probes, rolling updates with appropriate surge/unavailable settings, backward-compatible database changes, graceful shutdown, and progressive delivery with metrics-based rollback.

Syntax

Old Pods serve traffic -> New Pods become Ready -> traffic shifts -> old Pods drain

Example

Old Pods serve traffic -> New Pods become Ready -> traffic shifts -> old Pods drain

Code example

Old Pods serve traffic -> New Pods become Ready -> traffic shifts -> old Pods drain

Diagram

Zero downtime → container/orchestrator operation → result

Key Points

  • Database schema changes often need expand-and-contract sequencing.
Q71GitOps

What is GitOps for Kubernetes?

GitOps uses Git as the declarative source of truth and a controller reconciles cluster state toward the reviewed configuration stored in Git.

Answer

GitOps uses Git as the declarative source of truth and a controller reconciles cluster state toward the reviewed configuration stored in Git.

Syntax

Developer PR -> review/merge -> Git repository -> GitOps controller -> cluster reconciliation

Example

Developer PR -> review/merge -> Git repository -> GitOps controller -> cluster reconciliation

Code example

Developer PR -> review/merge -> Git repository -> GitOps controller -> cluster reconciliation

Diagram

GitOps → container/orchestrator operation → result

Key Points

  • Protect repositories and control who can change production manifests.
Q72Multi-tenancy

How do you isolate multiple teams in one cluster?

Combine namespaces with RBAC, quotas, limit ranges, network policies, Pod Security standards, admission policies, and separate node pools or clusters when stronger isolation is req

Answer

Combine namespaces with RBAC, quotas, limit ranges, network policies, Pod Security standards, admission policies, and separate node pools or clusters when stronger isolation is required.

Syntax

Team A namespace | Team B namespace
RBAC + quotas + network policies + admission controls

Example

Team A namespace | Team B namespace RBAC + quotas + network policies + admission controls

Code example

Team A namespace | Team B namespace
RBAC + quotas + network policies + admission controls

Diagram

Multi-tenancy → container/orchestrator operation → result

Key Points

  • Namespaces alone are not a hard security boundary.
Q73Observability

Which signals should trigger an alert for a Kubernetes API?

Use service-level indicators such as request latency, error rate, and traffic, alongside saturation signals such as CPU, memory, restarts, pending Pods, and dependency health.

Answer

Use service-level indicators such as request latency, error rate, and traffic, alongside saturation signals such as CPU, memory, restarts, pending Pods, and dependency health.

Syntax

Alert: error-rate SLI exceeds threshold for window
Correlate metrics + logs + traces + deployment events

Example

Alert: error-rate SLI exceeds threshold for window Correlate metrics + logs + traces + deployment events

Code example

Alert: error-rate SLI exceeds threshold for window
Correlate metrics + logs + traces + deployment events

Diagram

Observability → container/orchestrator operation → result

Key Points

  • Prefer actionable alerts tied to user impact and SLOs.
Q74Incident response

A rollout causes elevated 5xx errors. What do you do?

Pause or roll back the rollout, compare healthy and failing versions, inspect logs and traces, verify readiness and dependency behavior, then address the root cause and add a regre

Answer

Pause or roll back the rollout, compare healthy and failing versions, inspect logs and traces, verify readiness and dependency behavior, then address the root cause and add a regression test.

Syntax

kubectl rollout pause deployment/api
kubectl rollout undo deployment/api
kubectl rollout status deployment/api

Example

kubectl rollout pause deployment/api kubectl rollout undo deployment/api kubectl rollout status deployment/api

Code example

kubectl rollout pause deployment/api
kubectl rollout undo deployment/api
kubectl rollout status deployment/api

Diagram

Incident response → container/orchestrator operation → result

Key Points

  • Use incident procedures and verify recovery from user-facing metrics.
Q75Architecture

Draw a production Docker-to-Kubernetes delivery pipeline.

Developers commit source; CI tests and builds an image, scans and pushes it; GitOps or deployment automation applies versioned manifests; Kubernetes reconciles the desired state an

Answer

Developers commit source; CI tests and builds an image, scans and pushes it; GitOps or deployment automation applies versioned manifests; Kubernetes reconciles the desired state and monitoring feeds back health.

Syntax

Git commit -> CI tests -> Docker build -> Scan/SBOM -> Registry
    -> GitOps / deploy pipeline -> Kubernetes API
    -> Deployment -> Service -> Ready Pods
    <- Metrics / logs / traces / alerts

Example

Git commit -> CI tests -> Docker build -> Scan/SBOM -> Registry -> GitOps / deploy pipeline -> Kubernetes API -> Deployment -> Service -> Ready Pods <- Metrics / logs / traces / alerts

Code example

Git commit -> CI tests -> Docker build -> Scan/SBOM -> Registry
    -> GitOps / deploy pipeline -> Kubernetes API
    -> Deployment -> Service -> Ready Pods
    <- Metrics / logs / traces / alerts

Diagram

Architecture → container/orchestrator operation → result

Key Points

  • Use separate identities, approvals, immutable artifacts, and rollback procedures.
Q86Image Supply Chain

Why pin images by digest instead of relying only on tags?

Tags are mutable references, while a digest identifies exact image content. Digests improve reproducibility; update them through a controlled pat

Answer

Tags are mutable references, while a digest identifies exact image content. Digests improve reproducibility; update them through a controlled patching process to receive security fixes.

Example: Tag can move → digest identifies immutable image content

Diagram / flow: Deployment manifest → digest-pinned image → exact artifact

Syntax

image: registry.example.com/app@sha256:<digest>

Example

Tag can move → digest identifies immutable image content

Code example

image: registry.example.com/app@sha256:<digest>

Diagram

Deployment manifest → digest-pinned image → exact artifact

Key Points

  • Tags are mutable references, while a digest identifies exact image content.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q96Kubernetes Availability

What does a PodDisruptionBudget protect against?

A PodDisruptionBudget limits voluntary disruptions that can occur at once, such as certain drain operations. It does not prevent involuntary fail

Answer

A PodDisruptionBudget limits voluntary disruptions that can occur at once, such as certain drain operations. It does not prevent involuntary failures and cannot compensate for an insufficient replica count or poorly spread Pods.

Example: Drain request → PDB checks allowed disruptions → eviction proceeds or waits

Diagram / flow: PDB protects minimum available replicas during supported voluntary evictions

Syntax

kubectl drain node-1 --ignore-daemonsets

Example

Drain request → PDB checks allowed disruptions → eviction proceeds or waits

Code example

kubectl drain node-1 --ignore-daemonsets

Diagram

PDB protects minimum available replicas during supported voluntary evictions

Key Points

  • A PodDisruptionBudget limits voluntary disruptions that can occur at once, such as certain drain operations.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q97Kubernetes Scheduling

How do affinity and topology spread constraints help availability?

Affinity expresses placement preferences or requirements; topology spread constraints distribute Pods across zones or nodes. Overly strict rules

Answer

Affinity expresses placement preferences or requirements; topology spread constraints distribute Pods across zones or nodes. Overly strict rules can leave Pods pending when capacity is insufficient.

Example: Scheduler places replicas across zones/nodes to reduce correlated failure

Diagram / flow: Pods → topology domains → balanced distribution

Syntax

topologySpreadConstraints:
- maxSkew: 1
  topologyKey: topology.kubernetes.io/zone
  whenUnsatisfiable: ScheduleAnyway
  labelSelector:
    matchLabels: { app: web }

Example

Scheduler places replicas across zones/nodes to reduce correlated failure

Code example

topologySpreadConstraints:
- maxSkew: 1
  topologyKey: topology.kubernetes.io/zone
  whenUnsatisfiable: ScheduleAnyway
  labelSelector:
    matchLabels: { app: web }

Diagram

Pods → topology domains → balanced distribution

Key Points

  • Affinity expresses placement preferences or requirements; topology spread constraints distribute Pods across zones or nodes.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.
Q98Kubernetes Security

What is a Kubernetes NetworkPolicy?

NetworkPolicy declares allowed Pod traffic at the network layer when the installed CNI supports enforcement. Policies are commonly default-deny p

Answer

NetworkPolicy declares allowed Pod traffic at the network layer when the installed CNI supports enforcement. Policies are commonly default-deny plus explicit allow rules; selectors and namespace scope must be checked carefully.

Example: Default deny → allow only required namespace/Pod/port flows

Diagram / flow: Pod traffic → NetworkPolicy rules → allowed or blocked

Syntax

policyTypes: [Ingress, Egress]

Example

Default deny → allow only required namespace/Pod/port flows

Code example

policyTypes: [Ingress, Egress]

Diagram

Pod traffic → NetworkPolicy rules → allowed or blocked

Key Points

  • NetworkPolicy declares allowed Pod traffic at the network layer when the installed CNI supports enforcement.
  • Test the behavior in a representative environment.
  • Consider security, reliability, and operational impact.

Share this question bank

Send this page to someone preparing for an interview.