CoreHRx Jobs

Apply in one click, save jobs and take free mock tests.

Register free Log in
Hiring? Post jobs with CoreHRx
My account
user

View & update profile
Interview guide

Docker and Kubernetes Interview Questions and Answers: 60 Questions from Easy to Hard

This guide is for freshers in India preparing for DevOps, cloud or backend roles, and for experienced developers and SREs facing a Docker and Kubernetes round at a Pune IT services firm or a Bengaluru product company. It has 60 questions in three levels: easy questions on images, containers, Dockerfiles, Compose and the core Kubernetes objects; medium questions on multi-stage builds, probes, resources, autoscaling, rollouts, Helm and debugging failing pods; and hard questions on internals, scheduling, security, zero-downtime releases and cluster design. Versions are named wherever behaviour changed. Try each file and command on your laptop or a local cluster, then explain the answer aloud.

  • 60 questions, 3 levels
  • Updated
  • CoreHRx Jobs

What Docker and Kubernetes interviews cover

  • Docker basics: images and containers, Dockerfile instructions, layers and the build cache, multi-stage builds, volumes, networks and registries.
  • Docker Compose for multi-container apps: services, networks, volumes, healthchecks and settings for each environment.
  • Kubernetes objects: Pods, Deployments, Services, Ingress, ConfigMaps, Secrets, StatefulSets, Jobs and namespaces, and how labels tie them together.
  • Running workloads well: probes, requests and limits, autoscaling, rolling updates, and debugging states such as CrashLoopBackOff, ImagePullBackOff and Pending.
  • For senior roles: cluster internals, scheduling, security (RBAC, Pod Security, network policies, secrets), Helm and designing for zero downtime.

How to prepare (freshers and experienced)

  • Freshers: install Docker, containerise a small app you wrote and run it with a database using Compose, until you can explain every line of both files.
  • Then start a local cluster with kind or minikube, deploy the same app with a Deployment, a Service and a ConfigMap, and practise kubectl get, describe, logs and exec.
  • Break things on purpose: a wrong image tag, a failing probe, a memory limit that is too low. Reading the events for each failure is the fastest way to learn troubleshooting.
  • Experienced engineers: prepare two or three real stories, such as an outage you debugged, a rollout you made safe or an image you shrank, with numbers and what you changed.
  • Read the official Kubernetes documentation for the version your target company runs, because fields and defaults change between releases.

Common mistakes and interview-day tips

  • Saying Secrets are encrypted. By default they are only base64-encoded, and interviewers often check this.
  • Mixing up readiness and liveness probes, or saying EXPOSE publishes a port. Get these basics exactly right.
  • Answering with commands only. Explain what happens behind the command, such as the Deployment creating a new ReplicaSet during a rollout.
  • For a troubleshooting question, say your order of checks aloud: get, describe and events, logs including the previous container, then configuration.
  • Be honest about scale: say whether you used a managed cluster or your own and how many services it ran, rather than claiming experience you do not have.

Docker and Kubernetes interview questions: Easy questions (freshers)

20 questions

1. What is a container, and how is it different from a virtual machine?

A container is an isolated process on a Linux host that shares the host's kernel, while a virtual machine runs a full guest operating system with its own kernel on a hypervisor. Containers use kernel namespaces for isolation and cgroups for resource limits, so they start in seconds or less and add megabytes of overhead, not gigabytes. The trade-off is weaker isolation: a kernel bug can affect every container on the host, so teams often run containers inside VMs. On Windows or a Mac, Docker Desktop runs Linux containers inside a small Linux VM.

2. What is the difference between a Docker image and a container?

An image is a read-only, layered template: the application files, its libraries and metadata such as the default command. A container is a running or stopped instance of an image with a thin writable layer on top. One image can start many containers, just as one class creates many objects. In the example, two nginx containers come from the same image and share its layers on disk. Anything a container writes to its own layer is lost when the container is removed, so data that must survive belongs in a volume.

Example
docker pull nginx:1.27
docker run -d --name web1 -p 8080:80 nginx:1.27
docker run -d --name web2 -p 8081:80 nginx:1.27
docker images
docker ps

3. Walk through this Dockerfile. What does each instruction do?

FROM picks the base image, here Node 22 on Alpine Linux. WORKDIR sets the folder for later instructions and creates it if needed. COPY brings files from the build context into the image. RUN executes a command at build time, such as installing dependencies, and saves the result as a new layer. EXPOSE documents the port the app listens on but does not publish it. CMD is the default command when a container starts. A common mistake is mixing up RUN and CMD: RUN happens once while building, CMD runs every time a container starts.

Example
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

4. What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Both decide what runs when the container starts. ENTRYPOINT is the fixed executable and CMD supplies default arguments. In exec form, a JSON array, CMD is appended to ENTRYPOINT, and anything typed after the image name in docker run replaces only CMD; changing ENTRYPOINT needs the --entrypoint flag. Prefer exec form: the shell form runs the command under /bin/sh -c, so the shell is PID 1 and the app may never receive SIGTERM on docker stop. A shell-form ENTRYPOINT also ignores CMD completely.

Example
FROM python:3.12-slim
WORKDIR /app
COPY app.py .
ENTRYPOINT ["python3", "app.py"]
CMD ["--port", "8000"]
# docker run myapp              runs: python3 app.py --port 8000
# docker run myapp --port 9000  runs: python3 app.py --port 9000

5. What are image layers, and how does the Docker build cache work?

Each RUN, COPY and ADD instruction adds a filesystem layer, and the builder caches every step. A step is reused when the instruction and its inputs, such as the copied files, are unchanged; once one step changes, every step after it is rebuilt. So order a Dockerfile from what changes least to what changes most. Copying only the package files before npm ci means a code change rebuilds just the last COPY, and the dependencies come from cache. Putting COPY . . first makes every commit reinstall all the packages.

Example
FROM node:22-alpine
WORKDIR /app
# Changes rarely: this layer and npm ci stay cached
COPY package.json package-lock.json ./
RUN npm ci
# Changes on every commit: only layers from here rebuild
COPY . .
CMD ["node", "server.js"]

6. What is a .dockerignore file, and when should you use ADD instead of COPY?

A .dockerignore file lists what the builder must not send in the build context, much like .gitignore. Excluding .git, node_modules, logs and .env makes builds faster, keeps images smaller, stops secrets from being baked into a layer and stops the host's node_modules from overwriting the one built inside the image. On COPY versus ADD: COPY only copies local files, while ADD can also fetch a URL and automatically extracts a local tar archive. Use COPY unless you need those extras, because its behaviour is predictable.

Example
# .dockerignore
.git
node_modules
.env
*.log
coverage

7. What does -p 8080:3000 do, and how is it different from EXPOSE?

-p 8080:3000 publishes container port 3000 on host port 8080, so the app answers on the host's IP at port 8080. EXPOSE in a Dockerfile only records which port the app uses; it publishes nothing unless you run with -P, which maps every exposed port to a random high host port. By default -p binds on all host interfaces; prefix 127.0.0.1: to keep it local. A common bug: the app listens on 127.0.0.1 inside the container, so the published port gets no answer. It must listen on 0.0.0.0.

Example
docker run -d --name api -p 8080:3000 myorg/api:1.4.0
docker run -d --name api-local -p 127.0.0.1:8081:3000 myorg/api:1.4.0
docker port api

8. What is the difference between a Docker volume, a bind mount and a tmpfs mount?

A container's writable layer disappears with the container, so data that must last needs a mount. A named volume is storage managed by Docker that outlives any container, the right choice for a database. A bind mount maps a host folder into the container, handy in development so code edits show up at once, but it depends on host paths and permissions. A tmpfs mount lives only in memory. docker rm does not delete named volumes; docker volume rm and docker compose down -v do, so check before running them.

Example
docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=change-me \
  -v pgdata:/var/lib/postgresql/data postgres:16
docker run -it --rm -v "$(pwd)":/app -w /app node:22-alpine npm test

9. What is the difference between docker run, docker start and docker exec?

docker run creates a new container from an image and starts it. docker start restarts an existing stopped container, keeping its writable layer and settings. docker exec runs an extra process inside a container that is already running, which is how you open a shell or a client tool for debugging. Two common mistakes: calling docker run again and again, which leaves many stopped containers behind (see docker ps -a), and fixing things by hand through docker exec, because those changes are lost when the container is recreated.

Example
docker run -d --name cache redis:7
docker stop cache
docker start cache
docker exec -it cache redis-cli ping
docker ps -a

10. What is Docker Compose, and what does this compose.yaml do?

Docker Compose describes a multi-container application in one YAML file, usually compose.yaml, and starts it with docker compose up -d. This file builds the web image, starts Postgres, creates a named volume for its data and puts both services on a shared network, so web reaches the database by the service name db. Compose suits local development, test setups and small single-host deployments. Compose v2 is the docker compose plugin; the top-level version key is obsolete in the Compose Specification and can be left out.

Example
services:
  web:
    build: .
    ports:
      - "8080:3000"
    environment:
      DATABASE_URL: postgres://app:change-me@db:5432/jobs
    depends_on:
      - db
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: change-me
      POSTGRES_DB: jobs
    volumes:
      - dbdata:/var/lib/postgresql/data
volumes:
  dbdata:

11. What is a container registry, and what is the difference between an image tag and a digest?

A registry stores and serves images: Docker Hub, a cloud registry such as Amazon ECR or Google Artifact Registry, or a self-hosted one such as Harbor. An image name has the registry, repository and tag, here registry.example.com/hiring/api:1.4.0. A tag is a movable label, so a different image can be pushed under the same tag, and latest is only the default tag name, not the newest build. A digest (sha256:...) identifies the exact content and never changes. Production should deploy version tags, ideally pinned by digest.

Example
docker build -t registry.example.com/hiring/api:1.4.0 .
docker login registry.example.com
docker push registry.example.com/hiring/api:1.4.0
docker pull registry.example.com/hiring/api@sha256:<digest>

12. What is Kubernetes, and what problems does it solve?

Kubernetes is an open-source platform that runs containers across a cluster of machines. You declare the desired state, for example three replicas of an API with 512 MiB of memory each, and controllers keep working until reality matches it. It handles placing containers on nodes, restarting failed containers, replacing pods from failed nodes, scaling, service discovery and load balancing, rolling updates and rollbacks, and configuration and secrets. It also adds real complexity, so a small app on one server is often fine with Docker Compose.

13. What are the main components of a Kubernetes cluster?

The control plane decides and the worker nodes run the work. The kube-apiserver is the front door that kubectl and every component talk to, and it alone reads and writes etcd, the key-value store that holds the cluster state. The kube-scheduler picks a node for each new pod. The kube-controller-manager runs controllers such as the Deployment and node controllers. On each worker node the kubelet starts pods through a container runtime like containerd, and kube-proxy programs the rules that make Services work.

14. What is a Pod, and why does Kubernetes not schedule containers directly?

A Pod is the smallest unit Kubernetes schedules: one or more containers that always run together on the same node. Containers in a pod share one network namespace, so they have the same IP and can talk over localhost, and they can share volumes. That is why a helper such as a log shipper sidecar lives in the same pod as the app. Pods are disposable: a dead pod is replaced by a new one with a new IP. So you rarely create bare pods like this in production; a Deployment or another controller manages them.

Example
apiVersion: v1
kind: Pod
metadata:
  name: hello
  labels:
    app: hello
spec:
  containers:
    - name: web
      image: nginx:1.27
      ports:
        - containerPort: 80

15. What is a Deployment, and how is it related to ReplicaSets and Pods?

A Deployment declares how many replicas of a pod template should run and how to update them. It creates a ReplicaSet, and the ReplicaSet creates and replaces pods to keep the count at three. When you change the template, for example the image tag, the Deployment creates a new ReplicaSet and moves pods over gradually, which gives rolling updates and rollbacks. The selector must match the template's labels and cannot be changed after creation. Do not edit the ReplicaSet directly, because the Deployment owns it.

Example
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: registry.example.com/hiring/api:1.4.0
          ports:
            - containerPort: 8080

16. What is a Kubernetes Service, and what are the ClusterIP, NodePort and LoadBalancer types?

Pods come and go with new IPs, so a Service gives a stable virtual IP and DNS name in front of every ready pod whose labels match its selector, and spreads traffic across them. port is what clients use and targetPort is the container's port. ClusterIP, the default, is reachable only inside the cluster. NodePort also opens a port, by default from the range 30000-32767, on every node. LoadBalancer asks the cloud provider for an external load balancer. ExternalName only returns a DNS alias.

Example
apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  type: ClusterIP
  selector:
    app: api
  ports:
    - port: 80
      targetPort: 8080

17. What are Kubernetes namespaces used for?

A namespace splits one cluster into virtual groups, such as one per team or per environment. Names need to be unique only within a namespace, and RBAC rules, resource quotas and network policies are usually applied per namespace. A new cluster has default, kube-system, kube-public and kube-node-lease. Some objects are cluster-wide, such as nodes, PersistentVolumes and namespaces themselves. Namespaces are not a security boundary on their own: without RBAC and network policies, pods in different namespaces can still reach each other.

Example
kubectl create namespace staging
kubectl get pods -n staging
kubectl config set-context --current --namespace=staging
kubectl api-resources --namespaced=false

18. What are labels and selectors in Kubernetes?

Labels are key-value pairs attached to objects, such as app=api or env=staging, and selectors query them. They are how Kubernetes links objects: a Service finds its pods by label, a ReplicaSet counts its pods by label, and network policies and node selection use them too. Selectors are equality-based, like app=api, or set-based, like env in (staging,qa). Use annotations instead for data that does not identify the object, such as a build URL. A typo in a label is a classic reason a Service has no endpoints.

Example
kubectl get pods -l app=api,tier=backend
kubectl get pods -l 'env in (staging,qa)'
kubectl label pod api-6f9c7d5b8-x2k4p debug=true
kubectl get pods --show-labels

19. What are ConfigMaps and Secrets, and is a Secret encrypted?

Both keep configuration out of the image, so one image runs in every environment. A ConfigMap holds non-sensitive settings such as LOG_LEVEL or a config file; a Secret holds passwords, tokens and keys. Pods use either as environment variables (env or envFrom) or as files in a mounted volume. A Secret's values are only base64-encoded, which anyone can decode, and they are stored unencrypted in etcd unless encryption at rest is configured. So restrict who can read Secrets with RBAC and never commit them to git.

Example
kubectl create configmap api-config \
  --from-literal=LOG_LEVEL=info --from-file=app.properties
kubectl create secret generic db-creds \
  --from-literal=DB_PASSWORD='change-me'
kubectl get secret db-creds -o jsonpath='{.data.DB_PASSWORD}' | base64 -d

20. Which kubectl commands do you use every day, and what does each one tell you?

kubectl get lists resources, and -o wide adds the node and pod IP. describe shows details plus recent events, the first stop when something fails. logs prints container output, and --previous shows the last crashed container. exec runs a command or a shell in a running container. apply -f creates or updates objects from YAML, the declarative way teams keep config in git. port-forward reaches a pod or Service from your laptop without exposing it. delete removes objects, so check the context and namespace first.

Example
kubectl get pods -o wide
kubectl describe pod api-6f9c7d5b8-x2k4p
kubectl logs api-6f9c7d5b8-x2k4p --previous
kubectl exec -it api-6f9c7d5b8-x2k4p -- sh
kubectl apply -f deployment.yaml
kubectl port-forward svc/api 8080:80

Ready to check yourself? Take the free Docker and Kubernetes mock test

Docker and Kubernetes interview questions: Medium questions (1-3 years)

20 questions

21. What is a multi-stage build, and why does this Dockerfile produce a small image?

A multi-stage build has several FROM stages in one Dockerfile and copies only the needed output into the final stage. Here the first stage has the full Go toolchain, hundreds of megabytes, and compiles a static binary; the final stage is a distroless image of a few megabytes that holds only that binary and runs as a non-root user. The image is faster to pull and has far less attack surface: no compiler, package manager or shell. docker build --target build stops at the first stage, which is handy for running tests in CI.

Example
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
ENTRYPOINT ["/api"]

22. Your Python image is over 1 GB. How do you make it smaller?

Start from a small base such as a slim variant, install only what the app needs with --no-install-recommends, and clean up in the same RUN. Each layer is permanent: deleting the apt lists in a later RUN does not shrink the earlier layer. pip's --no-cache-dir skips storing the download cache. Use a multi-stage build so compilers stay out of the final image, and a .dockerignore. Alpine is smaller but uses musl instead of glibc, so some Python packages must compile and may behave differently. docker history shows each layer's size.

Example
FROM python:3.12-slim
WORKDIR /app
RUN apt-get update \
    && apt-get install -y --no-install-recommends libpq5 \
    && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python3", "main.py"]

23. Why can the API container not reach the database at localhost, and how do Docker networks fix it?

Inside a container, localhost is that container itself, so the API looking for Postgres on localhost finds nothing. Containers on the default bridge network can reach each other only by IP address. A user-defined bridge network adds Docker's embedded DNS, so containers on it resolve each other by name, and it isolates them from containers on other networks. Here the API reaches Postgres as db:5432. Compose creates such a network for every project automatically. The host network driver, on Linux, shares the host's network stack instead.

Example
docker network create jobs-net
docker run -d --name db --network jobs-net \
  -e POSTGRES_PASSWORD=change-me postgres:16
docker run -d --name api --network jobs-net -e DB_HOST=db \
  -p 8080:8080 registry.example.com/hiring/api:1.4.0
docker network inspect jobs-net

24. With depends_on in Compose, the API still crashes because the database is not ready. Why, and how do you fix it?

The short form of depends_on only controls start order: Compose waits for the db container to start, not for Postgres to accept connections, so the API can fail on boot. The long form with condition: service_healthy waits until the db healthcheck passes, here pg_isready every 5 seconds. Still make the app retry its connection, because the database can restart later and the healthcheck only covers start-up. Kubernetes has no depends_on at all, so retry logic in the app is the portable fix.

Example
services:
  api:
    image: registry.example.com/hiring/api:1.4.0
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10

25. How do you manage different settings for development and production with Docker Compose?

Keep one base compose.yaml and layer environment files on top. docker compose up reads compose.yaml and, if present, compose.override.yaml, the usual place for development extras such as bind mounts and debug ports. For production, pass files explicitly with -f; later files override earlier ones. A .env file in the project folder fills the variable placeholders in the YAML, while env_file passes variables into a container. Profiles keep optional services, such as an admin tool, off unless asked for. docker compose config prints the final merged file.

Example
# development: compose.yaml + compose.override.yaml
docker compose up -d
# production: explicit files, later ones win
docker compose -f compose.yaml -f compose.prod.yaml up -d
# start optional services in the "tools" profile too
docker compose --profile tools up -d
# print the merged configuration
docker compose -f compose.yaml -f compose.prod.yaml config

26. What is the difference between liveness, readiness and startup probes?

A readiness probe says whether the pod should get traffic: when it fails, the pod is removed from Service endpoints but not restarted. A liveness probe says whether the container is stuck: after failureThreshold failures the kubelet restarts the container. A startup probe holds off the other two until it succeeds, here allowing 24 x 5 = 120 seconds for a slow start. A common mistake is a liveness check that calls the database, so a slow database makes Kubernetes restart every pod at once and turns a slowdown into an outage.

Example
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
    - name: api
      image: registry.example.com/hiring/api:1.4.0
      startupProbe:
        httpGet:
          path: /healthz
          port: 8080
        periodSeconds: 5
        failureThreshold: 24
      readinessProbe:
        httpGet:
          path: /ready
          port: 8080
        periodSeconds: 5
      livenessProbe:
        httpGet:
          path: /healthz
          port: 8080
        periodSeconds: 10
        failureThreshold: 3

27. What do resource requests and limits do, and what happens when a container goes over them?

Requests are what the scheduler reserves: this pod lands only on a node with 250m CPU, a quarter of a core, and 256 MiB of memory still unrequested. Limits are hard caps enforced by the kernel through cgroups. A container that hits its CPU limit is throttled, so it slows down but keeps running. A container that goes over its memory limit is killed by the OOM killer, shows OOMKilled with exit code 137, and is restarted. Without requests the scheduler packs nodes blindly, so set them from measured usage.

Example
apiVersion: v1
kind: Pod
metadata:
  name: report-worker
spec:
  containers:
    - name: worker
      image: registry.example.com/hiring/worker:2.1.0
      resources:
        requests:
          cpu: 250m
          memory: 256Mi
        limits:
          cpu: "1"
          memory: 512Mi

28. How does the HorizontalPodAutoscaler decide how many replicas to run?

The HPA changes a Deployment's replica count from metrics. With autoscaling/v2 and averageUtilization 60, it aims to keep average CPU at 60 percent of the pods' CPU requests, so it needs metrics-server and requests set on the containers. The formula is desired = ceil(current x currentMetric / target): 4 pods averaging 90 percent give ceil(4 x 90 / 60) = 6, within the 3 to 12 bounds. By default it ignores changes within 10 percent of the target and waits 5 minutes before scaling down, to avoid flapping.

Example
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 3
  maxReplicas: 12
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60

29. How does a rolling update work in a Deployment, and how do you roll back?

Changing the pod template, for example with kubectl set image, starts a rolling update: the Deployment creates a new ReplicaSet and scales the old one down step by step. maxSurge and maxUnavailable, both 25 percent by default, set the pace. With 10 replicas, surge rounds up to 3 and unavailable rounds down to 2, so there are at most 13 pods and at least 8 available. rollout status waits for the end, and rollout undo returns to an earlier ReplicaSet. Readiness probes stop a broken version from taking traffic.

Example
kubectl set image deployment/api api=registry.example.com/hiring/api:1.5.0
kubectl rollout status deployment/api
kubectl rollout history deployment/api
kubectl rollout undo deployment/api --to-revision=3

30. Rohan's payments API pod at a Pune IT services firm shows CrashLoopBackOff. How do you debug it?

CrashLoopBackOff means the container keeps exiting and the kubelet keeps restarting it with a growing delay, by default 10, 20, 40 seconds and so on, capped at 5 minutes. Check describe for Last State, Reason and Exit Code, then logs --previous, because the new container may have no output yet. Exit code 1 is usually an app error such as a missing environment variable; 137 with OOMKilled means the memory limit is too low; failing liveness probes show in the events. A command that simply finishes also loops under a Deployment.

Example
kubectl get pod payments-api-7c9d8f6b5-q8wzt
kubectl describe pod payments-api-7c9d8f6b5-q8wzt
kubectl logs payments-api-7c9d8f6b5-q8wzt --previous
kubectl get events --sort-by=.metadata.creationTimestamp

31. A new pod is stuck in ImagePullBackOff. What are the likely causes and fixes?

ImagePullBackOff means the kubelet could not pull the image and is waiting before it tries again; ErrImagePull is the first failure. The events in describe give the reason: a typo in the image name or tag, a private registry without credentials, a node that cannot reach the registry, or a public registry's rate limit. For a private registry, create a docker-registry Secret and list it under imagePullSecrets in the pod spec or the service account. Also note that an image tagged latest, or untagged, defaults to imagePullPolicy Always.

Example
kubectl describe pod api-6f9c7d5b8-x2k4p
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=ci-bot --docker-password='change-me'
# then in the pod spec: imagePullSecrets: [{name: regcred}]

32. A pod stays in Pending for a long time. How do you find out why?

A pod stuck in Pending usually has not been scheduled; if describe shows a node, it is still pulling images. Otherwise describe shows a FailedScheduling event that says how many nodes failed each check: not enough unrequested CPU or memory, a nodeSelector or affinity that no node matches, a taint the pod does not tolerate, or a PersistentVolumeClaim that is not bound. Compare the pod's requests with each node's Allocated resources. Fix it by lowering oversized requests, adding nodes or letting the cluster autoscaler add them, or correcting the selector or the toleration.

Example
kubectl get pods --field-selector=status.phase=Pending
kubectl describe pod report-worker-5d8c7b9f4-m2xkq
kubectl describe node worker-2 | grep -A 8 "Allocated resources"
kubectl get pvc

33. What is an Ingress, and what does this one do?

An Ingress holds HTTP and HTTPS routing rules: here jobs.example.in/api goes to the api Service and everything else to web, with TLS from the jobs-tls Secret. The rules do nothing alone: an ingress controller must be installed, and its class must match ingressClassName. The gain is one external load balancer and one certificate setup for many Services, instead of a LoadBalancer Service each. With pathType Prefix, /api matches /api and /api/jobs but not /apiv2. The Ingress API is frozen; new features go into Gateway API.

Example
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: jobs
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - jobs.example.in
      secretName: jobs-tls
  rules:
    - host: jobs.example.in
      http:
        paths:
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: api
                port:
                  number: 80
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

34. You changed a ConfigMap, but the running pods still use the old values. Why?

Environment variables are read once when the container starts, so editing the ConfigMap changes nothing for running pods until they restart. A ConfigMap mounted as a volume is refreshed after a delay, the kubelet sync period plus cache time, but only helps if the app re-reads the file, and never for a subPath mount. The reliable way is to roll the Deployment after a change, with kubectl rollout restart or a hash of the config in a pod template annotation. Marking a ConfigMap immutable prevents accidental edits.

Example
kubectl create configmap api-config --from-file=config.yaml \
  --dry-run=client -o yaml | kubectl apply -f -
kubectl rollout restart deployment/api
kubectl rollout status deployment/api

35. What are PersistentVolumes, PersistentVolumeClaims and StorageClasses?

A PersistentVolume is a piece of storage in the cluster, and a PersistentVolumeClaim is a request for storage of a size and access mode. With a StorageClass, the claim triggers dynamic provisioning through a CSI driver, so nobody creates disks by hand. ReadWriteOnce means one node can mount the volume read-write, not one pod, so a Deployment using this claim scaled across nodes leaves extra pods stuck with a Multi-Attach error. Dynamically provisioned volumes default to the Delete reclaim policy, so the disk goes with the claim.

Example
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: uploads
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: standard
  resources:
    requests:
      storage: 20Gi

36. Why should a container not run as root, and how do you change that in a Dockerfile?

Containers run as root by default, and root in a container is UID 0 on the host kernel, so a container escape or a mounted host folder becomes far more dangerous. Add a USER instruction with a numeric ID: the Node image's node user is UID 1000, and COPY --chown gives it the app files. Enforce it in Kubernetes with runAsNonRoot, which refuses root and cannot verify a user given only by name. Other basics: never run an app with --privileged, do not mount the Docker socket into containers, and use a minimal base image.

Example
FROM node:22-alpine
WORKDIR /app
COPY --chown=node:node package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
# numeric UID of the node user, so runAsNonRoot can verify it
USER 1000
EXPOSE 3000
CMD ["node", "server.js"]

37. When do you use a Job, a CronJob or a DaemonSet instead of a Deployment?

A Job runs pods until a task completes, retrying failed pods up to backoffLimit. A CronJob creates a Job on a cron schedule; this one runs at 01:30 India time using the timeZone field, stable since Kubernetes 1.27, and concurrencyPolicy Forbid skips a run while the last one is still going. Job pods need restartPolicy OnFailure or Never. A DaemonSet runs one pod on every node, or on selected nodes, for agents such as log shippers and node monitors. Make job code idempotent, because a run can repeat.

Example
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "30 1 * * *"
  timeZone: Asia/Kolkata
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 2
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: report
              image: registry.example.com/hiring/report:1.0.0

38. What is Helm, and what are charts, values and releases?

Helm is a package manager for Kubernetes. A chart is a folder with Chart.yaml, templates and a values.yaml of defaults; a release is one installed copy of a chart in a namespace. Settings for each environment go in files such as values-staging.yaml, passed with -f. helm template renders the YAML locally for review, upgrade --install installs or upgrades in one repeatable command, and every upgrade is a numbered revision you can roll back to. In Helm 3 there is no server-side Tiller; release history is stored as Secrets in the release namespace.

Example
helm create api
helm lint ./api
helm template api ./api -f values-staging.yaml
helm upgrade --install api ./api -n staging -f values-staging.yaml
helm history api -n staging
helm rollback api 2 -n staging

39. Priya's frontend gets connection errors from the api Service. How do you debug a Service that does not reach its pods?

First check that the Service has endpoints. If its EndpointSlices list no addresses, the selector does not match the pods' labels (compare with --show-labels) or the pods are not ready. If endpoints exist, check that targetPort is the port the container really listens on. Then test from inside the cluster with a temporary pod, using the full name service.namespace.svc.cluster.local, because the short name works only from the same namespace. If that works, look outside: the Ingress, a NetworkPolicy or the client.

Example
kubectl get svc api -o wide
kubectl get endpointslices -l kubernetes.io/service-name=api
kubectl get pods -l app=api --show-labels
kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never \
  -- wget -qO- http://api.staging.svc.cluster.local

40. What happens when a pod is deleted, and how do you shut an app down gracefully?

Kubernetes marks the pod Terminating and starts removing it from Service endpoints, runs the preStop hook, sends SIGTERM to each container's main process and, after terminationGracePeriodSeconds (default 30), sends SIGKILL. The preStop time counts inside the grace period. Endpoint removal happens in parallel, so a short preStop sleep lets traffic stop arriving first; the image needs a sleep binary for this. The app must catch SIGTERM, stop taking work and finish requests in flight. docker stop is similar, with a 10-second default.

Example
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: api
      image: registry.example.com/hiring/api:1.4.0
      lifecycle:
        preStop:
          exec:
            command: ["sleep", "10"]

Ready to check yourself? Take the free Docker and Kubernetes mock test

Docker and Kubernetes interview questions: Hard questions (experienced)

20 questions

41. How do containers work under the hood on Linux?

A container is an ordinary Linux process with a restricted view and limits. Namespaces give it its own PID tree, network stack, mounts, hostname, IPC and optionally user IDs. Cgroups cap and account for CPU, memory and I/O. The filesystem is a stack of read-only image layers plus a writable layer, joined by a union filesystem such as overlayfs. Seccomp and dropped capabilities limit what the kernel will do for it. Docker's dockerd hands work to containerd, which uses runc to create the process. These commands show it from the host.

Example
docker run -d --name web1 nginx:1.27
PID=$(docker inspect --format '{{.State.Pid}}' web1)
sudo ls -l /proc/$PID/ns
cat /proc/$PID/cgroup

42. Kubernetes 1.24 removed dockershim. What changed, and what broke for teams?

dockershim was the built-in adapter that let the kubelet drive Docker Engine; Kubernetes 1.24 removed it. The kubelet now talks only to runtimes that implement the Container Runtime Interface, such as containerd and CRI-O. Images built with docker build are standard OCI images, so they run unchanged. What broke was anything that relied on Docker on the node: pods mounting /var/run/docker.sock for CI builds, or tools reading Docker's paths. Build with BuildKit, Kaniko or Buildah instead, and inspect nodes with crictl.

Example
crictl ps
crictl images
crictl inspect <container-id>
crictl logs <container-id>

43. Explain step by step what happens after you run kubectl apply for a new Deployment.

kubectl sends the object to the API server, which authenticates the caller, authorizes it, usually with RBAC, runs mutating admission, validates the schema, runs validating admission and stores the object in etcd. The Deployment controller, watching the API, creates a ReplicaSet, and the ReplicaSet controller creates Pods. The scheduler sees the unscheduled pods and binds each to a node. That node's kubelet pulls the image through the CRI runtime, and the CNI plugin gives the pod an IP. Ready pods join EndpointSlices. It is all watches, not direct calls.

44. Your cluster has three zones. How do you spread six API replicas evenly and keep them on dedicated nodes?

The scheduler filters out nodes that cannot run the pod and scores the rest. A topology spread constraint with maxSkew 1 across zones allows only two pods per zone for six replicas, so losing a zone removes a third of capacity. A taint repels pods without a matching toleration, but a toleration only permits a tainted node; it does not attract the pod there. To dedicate nodes to the API you need the taint and toleration plus a nodeSelector or node affinity. Pod anti-affinity can also keep replicas on separate nodes.

Example
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 6
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: api
      tolerations:
        - key: dedicated
          operator: Equal
          value: api
          effect: NoSchedule
      containers:
        - name: api
          image: registry.example.com/hiring/api:1.4.0

45. What are QoS classes, and which pods does the kubelet evict first when a node runs out of memory?

Each pod gets a QoS class. Guaranteed: every container has CPU and memory requests equal to its limits. Burstable: at least one request or limit is set. BestEffort: none at all. Under memory pressure the kubelet evicts pods, ranking first by whether usage exceeds requests, then by priority, then by how far usage is above requests. So BestEffort pods, whose requests are zero, usually go first and Guaranteed pods last. Give critical services such as payments Guaranteed resources and a PriorityClass, and never leave requests empty.

Example
kubectl get pod payments-api-0 -o jsonpath='{.status.qosClass}'
kubectl describe node worker-3 | grep -i pressure
kubectl get events -A --field-selector reason=Evicted

46. A latency-sensitive API shows p99 spikes although its node is mostly idle. How can CPU limits cause this?

CPU limits are enforced by the kernel's CFS quota in 100 ms periods. A 500m limit means 50 ms of CPU time per period. A service with four busy threads uses those 50 ms in 12.5 ms of wall time and is then throttled for the remaining 87.5 ms, even on an idle node, which appears as p99 latency spikes. Confirm it with the CFS throttled-periods metric from cAdvisor. Fixes: set requests from real usage, raise or remove CPU limits for latency-sensitive services while keeping memory limits, and size thread pools to the CPU actually available.

47. How do you keep secrets out of image layers, and what else secures the image supply chain?

Anything passed with ARG, ENV or COPY ends up in the image history or a layer, and deleting it in a later step does not remove it from earlier layers, so a private npm token copied in is readable by anyone who pulls the image. A BuildKit secret mount exposes the file to one RUN step only and never writes it to a layer, and a cache mount speeds up repeat installs. Beyond secrets: pin base images by digest, scan images for CVEs in CI, rebuild often for patches, generate an SBOM and sign images.

Example
# syntax=docker/dockerfile:1
# build: docker build --secret id=npmrc,src=$HOME/.npmrc -t api:1.4.0 .
FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev
COPY . .
USER node
CMD ["node", "server.js"]

48. How do you harden a pod with securityContext, and how is it enforced across a namespace?

This pod meets the restricted Pod Security Standard: it must run as a non-root user, cannot gain privileges through setuid binaries, drops all Linux capabilities and uses the runtime's default seccomp profile. A read-only root filesystem stops an attacker from writing tools into the container, and the emptyDir gives the app a writable /tmp. Enforce it per namespace with the label pod-security.kubernetes.io/enforce=restricted, handled by Pod Security Admission, which replaced PodSecurityPolicy after it was removed in Kubernetes 1.25.

Example
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: api
      image: registry.example.com/hiring/api:1.4.0
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]
      volumeMounts:
        - name: tmp
          mountPath: /tmp
  volumes:
    - name: tmp
      emptyDir: {}

49. How does Kubernetes RBAC work, and how would you give a CI pipeline least-privilege access?

RBAC rules only grant permissions; there is no deny, so access is the union of all bindings. A Role is scoped to one namespace and a ClusterRole is cluster-wide or a reusable template; a RoleBinding grants either one inside a namespace. Here the CI service account may update Deployments in staging and nothing else. Check it with kubectl auth can-i using --as=system:serviceaccount:staging:ci-deployer. Watch for risky grants: list on secrets reveals every secret, pods/exec gives a shell, and cluster-admin for CI is a breach waiting to happen.

Example
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deploy-manager
  namespace: staging
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ci-deploy-manager
  namespace: staging
subjects:
  - kind: ServiceAccount
    name: ci-deployer
    namespace: staging
roleRef:
  kind: Role
  name: deploy-manager
  apiGroup: rbac.authorization.k8s.io

50. How do NetworkPolicies work, and what is the catch in enforcing them?

By default every pod can reach every other pod in the cluster. A NetworkPolicy is an allow-list: once any policy selects a pod for ingress, only traffic that some policy allows gets in, and policies add up. This one lets only pods labelled app=api in the same namespace reach Postgres on port 5432. Enforcement comes from the CNI plugin, such as Calico or Cilium; with a plugin that does not support policies they are silently ignored. Start each namespace with a default-deny policy, and when denying egress, allow DNS.

Example
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-allow-api
  namespace: prod
spec:
  podSelector:
    matchLabels:
      app: postgres
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: api
      ports:
        - protocol: TCP
          port: 5432

51. How would you manage Kubernetes Secrets securely for a Bengaluru fintech?

By default a Secret sits base64-encoded in etcd, readable by anyone with etcd access or a backup. Turn on encryption at rest with an EncryptionConfiguration, ideally the KMS v2 provider so the key lives in a cloud KMS or HSM, then rewrite existing Secrets so they are re-encrypted. Limit get, list and watch on Secrets with RBAC. Keep the source of truth in a secret manager synced by External Secrets Operator or the Secrets Store CSI driver, never commit plain Secret YAML (use Sealed Secrets or SOPS), and rotate regularly.

Example
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
    providers:
      - kms:
          apiVersion: v2
          name: cloud-kms
          endpoint: unix:///var/run/kms-plugin/socket.sock
      - identity: {}

52. How do you achieve zero-downtime deployments on Kubernetes?

It takes several pieces together. Readiness probes keep traffic off pods that are not ready. maxUnavailable 0 with maxSurge 1 keeps full capacity during a rollout. A preStop sleep and proper SIGTERM handling drain connections. A PodDisruptionBudget, like this one keeping two api pods up, protects against voluntary disruptions such as node drains and cluster upgrades, but it does not limit the Deployment's own rollout or help when a node crashes. Database changes must be backward compatible, expand then contract, so old and new pods can run together.

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

53. How do blue-green and canary releases work on Kubernetes, and when would you choose each?

Blue-green runs the old and new versions as two full Deployments and switches the Service selector or the route at once: instant cutover and instant rollback, at double capacity. Canary sends a small share of traffic to the new version and grows it while error rate and latency stay healthy, which limits the blast radius. Splitting by replica count is coarse, 1 pod in 10 is about 10 percent, so exact weights come from Gateway API, as in this HTTPRoute, or a service mesh. Argo Rollouts or Flagger can automate the analysis and rollback.

Example
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: api
spec:
  parentRefs:
    - name: public-gateway
  rules:
    - backendRefs:
        - name: api-stable
          port: 80
          weight: 90
        - name: api-canary
          port: 80
          weight: 10

54. What does a StatefulSet guarantee, and does it make a database highly available?

A StatefulSet gives each pod a stable identity: fixed names queue-0, queue-1 and queue-2, a stable DNS name through the headless Service named in serviceName, and its own PersistentVolumeClaim from volumeClaimTemplates that follows the pod across restarts and reschedules. By default pods start and stop in order, and claims are kept after a scale-down. It does not make a database highly available: replication, failover and backups are still the software's or an operator's job, which is why many teams use a managed database instead.

Example
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: queue
spec:
  serviceName: queue
  replicas: 3
  selector:
    matchLabels:
      app: queue
  template:
    metadata:
      labels:
        app: queue
    spec:
      containers:
        - name: queue
          image: registry.example.com/hiring/queue:3.2.0
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 50Gi

55. How do you tune HPA scaling speed for a job portal that gets sudden traffic spikes on results day?

The behavior section of an autoscaling/v2 HPA controls speed. By default scale-up has no stabilization window and may add 100 percent or 4 pods, whichever is more, every 15 seconds; this one allows 100 percent per minute, so 6 pods can become 12. Scale-down waits 300 seconds by default so a short dip does not cut capacity, and here removes at most 2 pods a minute. Choose a metric that tracks load, keep minReplicas high before a known spike, and keep headroom, because new nodes take minutes.

Example
behavior:
  scaleUp:
    stabilizationWindowSeconds: 0
    policies:
      - type: Percent
        value: 100
        periodSeconds: 60
  scaleDown:
    stabilizationWindowSeconds: 300
    policies:
      - type: Pods
        value: 2
        periodSeconds: 60

56. API pods calling payments.example.com see slow DNS under load. What is the ndots problem, and how do you fix it?

Pods get a resolv.conf with the cluster search domains and ndots:5, so a name with fewer than five dots is first tried with each search suffix. payments.example.com has two dots, so with the three cluster suffixes each lookup makes three failing queries before the real one, doubled for A and AAAA records: 8 queries instead of 2. Under load this floods CoreDNS and adds latency. Fixes: write external names with a trailing dot, lower ndots for that workload as shown, add NodeLocal DNSCache, scale CoreDNS, and reuse HTTP connections.

Example
apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  dnsConfig:
    options:
      - name: ndots
        value: "2"
  containers:
    - name: api
      image: registry.example.com/hiring/api:1.4.0

57. How do you debug a running pod whose distroless image has no shell?

kubectl exec needs a shell or tool inside the image, which distroless and scratch images lack. kubectl debug adds an ephemeral container with your tools to the running pod, a feature stable since Kubernetes 1.25; --target shares the process namespace of the api container, so ps shows its processes and /proc/PID/root reaches its files. --copy-to debugs a copy of the pod instead, leaving the original alone. kubectl debug node/worker-2 runs a pod with the host filesystem at /host. Ephemeral containers cannot be removed and need RBAC.

Example
kubectl debug -it api-6f9c7d5b8-x2k4p --image=busybox:1.36 --target=api
kubectl debug api-6f9c7d5b8-x2k4p -it --image=busybox:1.36 \
  --share-processes --copy-to=api-debug
kubectl debug node/worker-2 -it --image=ubuntu:24.04

58. What role does etcd play, how many members should it have, and how do you back it up?

etcd stores all cluster state and uses the Raft protocol, so every write needs a quorum of floor(n/2) + 1 members. Three members tolerate one failure and five tolerate two, while four still tolerate only one, so use odd sizes. Writes wait for disk fsync on a quorum, so etcd needs fast SSDs, and requests are capped at about 1.5 MiB by default. Take etcdctl snapshot save backups on a schedule and test restores; since etcd 3.5 restore uses etcdutl into a new data directory. Managed services run etcd for you.

Example
ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
  --cert=/etc/kubernetes/pki/etcd/server.crt \
  --key=/etc/kubernetes/pki/etcd/server.key \
  snapshot save /backup/etcd-2026-11-14.db
etcdutl snapshot status /backup/etcd-2026-11-14.db --write-out=table

59. How do you run Helm safely in a production CI/CD pipeline?

In Helm 3, upgrade --install with --atomic waits for the resources to become ready and rolls back automatically if the release fails, so a bad image does not stay half-deployed. Version the chart and the app separately with version and appVersion. A values.schema.json validates values before rendering. The checksum annotation shown restarts pods whenever the ConfigMap template changes. Render with helm template in CI and review the diff. Use hooks sparingly, such as a pre-upgrade migration Job, and keep real secrets out of values files in git.

Example
helm upgrade --install api ./charts/api \
  --namespace prod --create-namespace \
  -f values-prod.yaml --set image.tag=1.5.0 \
  --atomic --timeout 10m

# templates/deployment.yaml, in the pod template metadata:
annotations:
  checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}

60. How would you design a shared Kubernetes cluster for several product teams at a Hyderabad SaaS company?

Give each team or environment a namespace with a ResourceQuota, like this one, plus a LimitRange so pods without requests get defaults instead of being rejected by the quota. Map SSO groups to Roles per namespace, add default-deny NetworkPolicies and the restricted Pod Security level, and use PriorityClasses so critical services win under pressure. Put sensitive workloads on tainted node pools. Namespaces are only soft isolation, so for untrusted tenants or strict compliance, use separate clusters, and keep production apart from test.

Example
apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-payments
  namespace: payments
spec:
  hard:
    requests.cpu: "20"
    requests.memory: 40Gi
    limits.memory: 80Gi
    pods: "100"

Practice questions for November 2026

New every month

3 questions from the Docker and Kubernetes mock test, the way they appear in it. A new set comes on the 1st of every month. Pick your answer, then open it.

  1. FresherKubernetes Architecture

    Which Kubernetes component stores the whole cluster state?

    • kube-proxy
    • kube-scheduler
    • kubelet
    • etcd
    Show the answer

    Answer: etcd. etcd is a consistent, highly available key-value store that holds every Kubernetes object. Only the API server reads and writes it directly; every other component goes through the API server.

  2. Intermediate (1-5 years)ConfigMaps and Secrets

    A ConfigMap key is mounted into a container with subPath. What happens when the ConfigMap changes?

    • Edits to the file are written back to the ConfigMap
    • The file is updated at once
    • The mounted file is never updated
    • The pod restarts on every change
    Show the answer

    Answer: The mounted file is never updated. Normal configMap volumes use a symlink that the kubelet swaps when data changes, so files update after a delay. A subPath mount binds one file directly and never sees updates, so pods must be restarted.

  3. Experienced (5+ years)Images and Containers

    A container's main process is a shell script that starts worker processes, and zombie processes pile up over time. Which change fixes it with the least effort?

    • Run it with an init such as docker run --init, which reaps zombies
    • Switch to a bigger base image that has more system tools
    • Raise the container's PID limit so that the zombies have more room
    • Mount /proc read-only so the zombies are cleaned up
    Show the answer

    Answer: Run it with an init such as docker run --init, which reaps zombies. PID 1 must reap orphaned children, and most apps and shell scripts never do. --init puts a tiny init (tini) in as PID 1 that reaps zombies and forwards signals; in Kubernetes, ship such an init in the image.

Take the full Docker and Kubernetes mock test

Ready to apply?

Browse the open jobs on CoreHRx. Create a free profile once and apply with it.