DevOps Engineer Top 100 Interview Questions
100 DevOps engineer interview questions with structured answers, comparison tables, flow diagrams, worked calculations and runnable shell scripts. Covers CI/CD, release strategies, containers, orchestration, infrastructure as code, cloud networking, observability, reliability and pipeline security, from fundamentals to production scenarios.
Questions 41-60 of 100
Q41.How do you make a container image smaller and more secure?
Start from a minimal base, include only what the application needs at runtime, and keep the image patched and scanned. Smaller images pull faster and give attackers fewer tools.
Minimal or distroless base image Multi-stage build Install only runtime dependencies Clean package caches in the same step Large size reduction Large size reduction Medium size reduction Medium size reduction Fewer packages to exploit No build tools shipped Smaller attack surface No security benefit Run as a non-root user Pin and regularly update the base image Scan images in the pipeline No size benefit No size benefit No size benefit Limits damage after a compromise Includes security patches Blocks known vulnerabilities Additional practices:
- Exclude files from the build context with an ignore file, so secrets and test data are never copied.
- Make the root filesystem read-only at runtime and mount writable volumes only where needed.
- Remove shells and package managers from production images where the application does not need them.
Rebuild images regularly even when the code has not changed, because the base image keeps receiving security fixes.
Q42.Why should you deploy a container image by its digest instead of a tag such as "latest"?
A tag is a movable label that can point to a different image tomorrow; a digest is a hash of the image's contents, so it always identifies exactly one image. Deploying by digest guarantees that every environment and every restart runs the same bits.
Tag such as "latest" or "v2" Digest Can be moved to another image over time Fixed by content, never changes Readable by people A long hash, not readable Reproducible deployments not guaranteed Reproducible deployments guaranteed A safe rollback target only if never moved Always a safe rollback target Weak protection against tampering Strong protection: contents must match the hash When to use which:
- Use version tags for people to read and search, and never move a release tag once published.
- Use digests in deployment manifests, or record the digest that a tag resolved to at deploy time.
The "latest" tag is the worst choice for production: two replicas started an hour apart can run different code, and nobody can tell which version is live.
Q43.Why should a container not run as root, and what else hardens it?
By default, many images run their process as root inside the container. If an attacker breaks out of the application or the container, root privileges make it far easier to damage the host or other containers.
Hardening measures:
- Run as a non-root user: create a dedicated user in the image and run the process as that user.
- Drop kernel capabilities: remove all capabilities and add back only the few the process needs.
- Read-only root filesystem: the process cannot modify its own binaries or plant files.
- No privilege escalation: block setuid programs from gaining extra rights.
- Resource limits: cap CPU, memory and process count so one container cannot starve the host.
- No privileged mode or host mounts: never mount the container runtime's socket or the host's root filesystem into a container.
- Minimal image: fewer binaries means fewer tools for an attacker.
These settings follow the principle of least privilege. Most can be enforced cluster-wide by an admission policy, so an insecure workload is rejected before it starts.
Interview tip: mention that root inside a container is not root on the host only when user namespaces are configured; without them, it is the same user ID.
Q44.How does a container handle shutdown signals, and why does process ID 1 matter?
When a platform stops a container, it sends SIGTERM to the main process, waits a grace period, often 30 seconds, then sends SIGKILL, which cannot be caught. A well-behaved service catches SIGTERM, stops taking new work, finishes current requests and exits.
Why process ID 1 matters:
- The container's main process runs as PID 1, which the kernel treats specially: it gets no default signal handlers, so an unhandled SIGTERM is ignored instead of stopping it.
- If the start command runs through a shell wrapper, the shell may become PID 1 and not forward signals to the application, so the application is killed abruptly after the grace period.
- PID 1 must also collect finished child processes; otherwise they remain as zombie processes.
What to do:
- Start the application directly, or replace the shell with it using
exec, so it receives signals. - Handle SIGTERM in the application: stop accepting work, drain in-flight requests, close connections.
- Use a minimal init process as PID 1 when the application cannot reap child processes.
- Keep shutdown shorter than the grace period.
Example
A worker that finishes its current job before exiting when it receives SIGTERM. The background line plays the role of the platform stopping the container:
#!/bin/sh stopping=0 trap 'echo "SIGTERM received, finishing current job"; stopping=1' TERM ( sleep 3; kill -TERM $$ ) & job=0 while [ "$stopping" -eq 0 ]; do job=$((job + 1)) echo "processing job $job" sleep 2 done echo "clean shutdown after job $job" # processing job 1 # processing job 2 # SIGTERM received, finishing current job # clean shutdown after job 2The trap runs when the current
sleepends, so job 2 completes instead of being cut off halfway.Q45.How do you persist data for a container?
A container's own writable layer is deleted with the container, so anything that must survive a restart or replacement goes in storage mounted from outside the container.
Container writable layer Named volume Bind mount Data lives inside the container Storage managed by the container runtime A chosen directory on the host Lost when the container is removed Survives container removal Survives container removal Best for temporary scratch files Best for databases and app data on one host Best for local development and host config files In-memory filesystem Network or cloud volume Data lives in host memory An external storage service Lost when the container is removed Survives container removal Best for sensitive temporary data Best for data that must follow a container to another host When to use which:
- Use named volumes rather than bind mounts in production, because they do not depend on host paths.
- Use network volumes in orchestrated clusters, where a container may be rescheduled to another machine.
- Keep stateless services stateless: store data in databases or object storage rather than local volumes.
Volumes protect against container restarts, not against host failure or mistakes, so they still need backups.
Q46.How do containers on the same host communicate with each other and with the outside world?
Each container gets its own network namespace with a virtual network interface. The container runtime connects these interfaces to virtual networks on the host and uses network address translation for traffic leaving or entering the host.
- Bridge network: containers on the same user-defined bridge network reach each other by container name through built-in DNS.
- Port publishing: a host port is mapped to a container port, so external clients reach the container through the host's address.
- Outbound traffic: containers reach the internet through the host, with their addresses translated to the host's.
- Host networking: the container shares the host's network stack directly, which is faster but removes network isolation.
- No network: the container has only a loopback interface, for jobs that must not make network calls.
flowchart LR A["External client"] -->|host port 8080| B["Host network"] B -->|translated to port 80| C["Web container"] C -->|by name over bridge| D["API container"] D -->|by name over bridge| E["Database container"]Only publish the ports that outside clients need; internal services such as databases should be reachable only on the internal network.
Q47.A container keeps restarting right after it starts. How do you investigate?
Work from the evidence the platform already keeps: the exit code, the last logs and the recent events. Most restart loops come from a crash on startup, a failed health check, missing configuration or running out of memory.
- Check status and exit code: the code points to the kind of failure.
- Read the logs of the previous run: the crash message is usually in the last lines before exit.
- Check events: look for failed health checks, image pull errors or memory kills.
- Compare configuration: environment variables, secrets and mounted files against a working environment.
- Run it interactively: start the same image with a shell or debug entry point and run the start command by hand.
Exit code 1 Exit code 126 or 127 Exit code 137 Exit code 143 Application error during startup Start command not executable or not found Killed with SIGKILL, often for exceeding its memory limit Stopped with SIGTERM, often by a failed liveness check flowchart TD A["Container restarting"] --> B{"Exit code 137?"} B -->|yes| C["Check memory limit and usage"] B -->|no| D{"Errors in last logs?"} D -->|yes| E["Fix config or code error"] D -->|no| F["Check health probe settings"]Example
A service restarts every 40 seconds after a new release.
- Its status shows exit code 143, and events report that the liveness check failed three times before each restart.
- The logs show the service is still loading a large cache when the checks begin: startup now takes 45 seconds instead of 10.
- The liveness check starts after 10 seconds and allows three failures 10 seconds apart, so the platform kills the container at about 40 seconds, before it is ready.
- The fix is a startup check that gives the service up to 90 seconds to start, after which the normal liveness check takes over.
Q48.What is a container registry, and how should you manage images in it?
A container registry stores and distributes container images, organised into repositories with tags and digests. Pipelines push images to it, and hosts or clusters pull images from it when they start containers.
Good management practices:
- Access control: only the trusted pipeline can push production images; runtime environments get read-only pull access.
- Immutable tags: once a release tag is pushed, it cannot be overwritten, so a version always means the same image.
- Vulnerability scanning: scan images on push and on a schedule, because new vulnerabilities are found in old images.
- Signing and verification: sign images in the pipeline and verify signatures before deployment.
- Retention rules: delete untagged and old development images automatically, but keep every version still deployed or needed for rollback.
- Regional mirrors or caches: keep a copy near each cluster for faster, more reliable pulls.
A private registry close to production also removes a dependency on public registries, which may rate-limit pulls or become unavailable during an incident.
Q49.What does a container orchestrator do?
A container orchestrator runs containers across a group of machines and keeps them in the state you declared, so you describe what should run instead of starting each container by hand.
- Scheduling: decides which machine each container runs on, based on available resources and placement rules.
- Self-healing: restarts failed containers and replaces those on machines that go down.
- Scaling: changes the number of replicas manually or automatically based on load.
- Service discovery and load balancing: gives a group of containers one stable name and spreads traffic across healthy replicas.
- Rolling updates and rollbacks: replaces a version gradually and can return to the previous one.
- Configuration and secrets: delivers settings and credentials to containers at runtime.
- Storage: attaches persistent volumes to the containers that need them.
All of this runs as a control loop: the orchestrator constantly compares the actual state with the desired state and acts to close the gap. That loop is why declarative configuration is the normal way to work with an orchestrator.
Q50.How does an orchestrator decide which node to place a new workload on?
Placement happens in two phases: first the scheduler filters out nodes that cannot run the workload, then it scores the remaining nodes and picks the best one.
- Filter: remove nodes without enough free CPU or memory for the workload's requests, nodes marked to repel workloads, and nodes that fail required placement rules such as a needed hardware type.
- Score: rank the remaining nodes by preferences such as spreading replicas across zones, keeping related workloads together, and balancing resource use.
- Bind: assign the workload to the highest-scoring node, where the node agent pulls the image and starts the containers.
- No fit: if no node passes the filter, the workload stays pending until resources free up or new nodes are added.
flowchart TD A["New workload"] --> B["Filter nodes"] B --> C{"Any node fits?"} C -->|no| D["Stay pending"] C -->|yes| E["Score nodes"] E --> F["Bind to best node"] F --> G["Node starts containers"]Scheduling uses the requested resources, not actual usage, so accurate requests are essential: requests set too high waste capacity, and requests set too low overload nodes.
Q51.What is the difference between liveness, readiness and startup probes?
All three are health checks the orchestrator runs against a container, but each triggers a different action. Mixing them up is a common cause of restart loops and dropped traffic.
Liveness Readiness Startup Asks: is the process stuck or broken? Asks: can it serve traffic right now? Asks: has it finished starting? On failure: restart the container On failure: remove it from the load balancer On failure: hold off the other probes, then restart Checks a lightweight endpoint with no dependencies Checks that dependencies are reachable and warm-up is done Checks the same as liveness, with a long allowance When to use which:
- Use readiness to stop sending traffic during warm-up, overload or a lost database connection, without restarting.
- Use liveness only for states the process cannot recover from, such as a deadlock.
- Use startup for slow-starting applications, so liveness does not kill them before they are ready.
Never make liveness depend on a shared dependency such as the database: if the database goes down, every replica fails liveness and is restarted at once, turning a partial outage into a total one.
Q52.What are resource requests and limits, and what happens when a container exceeds its limit?
A request is the amount of CPU and memory the scheduler reserves for a container when placing it on a node. A limit is the maximum the container may use. Requests drive scheduling; limits are enforced at runtime.
CPU Memory Above its request: allowed if the node has idle CPU Above its request: allowed if the node has free memory Above its limit: throttled, so it runs slower Above its limit: killed for running out of memory CPU is measured in cores or millicores, where 1000 millicores is one core. Memory is measured in bytes, usually mebibytes or gibibytes.
How to set them:
- Measure real usage under normal and peak load.
- Set requests near typical usage, so the scheduler packs nodes accurately.
- Set memory limits with headroom above peak usage, since hitting them kills the container.
- Be careful with tight CPU limits on latency-sensitive services, because throttling adds delay even when the node is idle.
A container with no requests can be placed on an already busy node and is the first to be evicted when the node runs short of memory.
Example
How many replicas fit on a node with 4 cores and 16 GiB of memory, when each replica requests 500 millicores and 1.5 GiB?
- CPU:
4 cores = 4000 millicores, and4000 / 500 = 8replicas. - Memory:
16 / 1.5 = 10.67, so 10 replicas. - The smaller number wins, so CPU limits the node to 8 replicas.
- In practice the node reserves some capacity for its own system processes. If 300 millicores are reserved,
3700 / 500 = 7.4, so only 7 replicas fit.
Q53.How does horizontal autoscaling decide how many replicas to run?
A horizontal autoscaler compares a measured metric, such as average CPU use, with a target value and scales the replica count in proportion to the difference.
desired_replicas = ceil(current_replicas * current_metric / target_metric)- current_replicas: how many replicas run now.
- current_metric: the average of the metric across those replicas, such as 90% CPU.
- target_metric: the value you want each replica to average, such as 60% CPU.
- ceil: round up, so capacity is never too low.
Behaviour that prevents constant changes:
- Tolerance: small differences, often within 10% of the target, cause no change.
- Stabilisation window: scale-down waits several minutes to confirm lower load, while scale-up reacts quickly.
- Bounds: minimum and maximum replica counts cap the result.
CPU percentage is relative to each container's CPU request, so wrong requests make autoscaling wrong too. For queue workers, a metric such as queue length per replica is often a better signal than CPU.
Example
A service runs 4 replicas with a target of 60% average CPU, a minimum of 2 and a maximum of 10.
- Traffic rises and average CPU reaches 90%:
ceil(4 * 90 / 60) = ceil(6) = 6replicas. - With 6 replicas, CPU settles at 61%. The ratio
61 / 60 = 1.017is within the 10% tolerance, so nothing changes. - At night CPU drops to 15%:
ceil(6 * 15 / 60) = ceil(1.5) = 2replicas. After the stabilisation window confirms the lower load, the service scales down to 2, which is also the minimum.
Q54.Compare horizontal and vertical scaling.
Horizontal scaling adds more instances of a service; vertical scaling gives an existing instance more CPU or memory. Horizontal scaling is the default for modern services, but it only works when the service is designed for it.
Horizontal scaling Vertical scaling Changes the number of instances Changes the size of each instance Very high upper limit Limited by the largest machine available Improves availability: no single point of failure Availability unchanged: still one instance Usually no downtime to scale Often needs a restart Needs stateless apps or shared state No application requirement Many small units Larger, pricier units When to use which:
- Scale horizontally for stateless web services and workers, where instances are interchangeable behind a load balancer.
- Scale vertically for components that are hard to split, such as a single primary database, or as a quick fix while a redesign happens.
- Combine them: right-size each instance vertically, then add instances horizontally as load grows.
Q55.How does service discovery work inside a container cluster?
Service discovery lets workloads find each other by a stable name even though individual containers come and go with changing addresses. The cluster tracks healthy endpoints and resolves a service name to them.
- A service is defined with a stable name and a selector that matches a group of workloads.
- The cluster tracks endpoints: as replicas start and pass readiness checks, their addresses are added; failed ones are removed.
- Internal DNS returns a stable virtual address for the service name.
- Traffic is load-balanced: connections to the virtual address are spread across the current healthy endpoints.
sequenceDiagram participant C as Client container participant D as Cluster DNS participant S as Service address participant P as Healthy replica C->>D: Look up orders service D-->>C: Stable virtual address C->>S: Send request S->>P: Forward to one replica P-->>C: ResponseClients should use the service name, never a replica's own address, because replica addresses change on every restart. Readiness checks are what keep traffic away from replicas that cannot serve.
Q56.How do you pass configuration and secrets to workloads in a cluster?
Keep configuration and secrets outside the image and inject them at runtime, so the same image runs in every environment. Clusters provide separate objects for plain configuration and for sensitive values.
Environment variables Mounted configuration files Cluster secret objects External secret store Good for simple settings Good for larger or structured config Good for passwords, tokens and keys Good for production credentials Easy, but visible in process listings and crash dumps Can update without a restart, if the app reloads them Stored encoded, not encrypted, unless encryption at rest is enabled Adds rotation, audit and fine-grained access control Good practices:
- Enable encryption at rest for cluster secrets and limit who can read them.
- Prefer mounting secrets as files over environment variables, so they do not leak through logs or child processes.
- Sync secrets from an external store for rotation and audit, rather than editing them by hand.
- Roll workloads automatically when configuration changes, so no replica runs with stale values.
A common mistake is treating the cluster's secret object as encrypted storage; by default it is only base64-encoded.
Q57.How does a rolling update proceed in an orchestrator, and how do you control its speed?
A rolling update replaces old replicas with new ones in small batches, starting a new replica and waiting for it to become ready before removing an old one. Two settings control how fast it goes and how much spare capacity it uses.
- Maximum surge: how many extra replicas may exist above the desired count during the update.
- Maximum unavailable: how many replicas may be unavailable below the desired count.
- Start new replicas, up to the surge limit.
- Wait until they pass readiness checks.
- Remove old replicas, keeping availability within the unavailable limit.
- Repeat until all replicas run the new version.
- Pause or stop automatically if new replicas never become ready.
Tuning the speed:
- A higher surge finishes faster but needs more spare capacity.
- Zero unavailable keeps full capacity throughout but needs surge capacity.
- A minimum ready time adds a delay after each new replica becomes ready, catching crashes that appear a little after startup.
When values are given as percentages, surge is usually rounded up and unavailable rounded down, which keeps capacity safe.
Example
A service has 10 replicas, with a maximum surge of 25% and a maximum unavailable of 25%.
- Surge:
10 * 25% = 2.5, rounded up to 3, so up to 13 replicas may run at once. - Unavailable:
10 * 25% = 2.5, rounded down to 2, so at least 8 replicas must stay ready. - The update can start 3 new replicas and remove 2 old ones straight away, then continue in similar batches as new replicas become ready.
- With surge 0 and unavailable 1, the same update replaces one replica at a time, which is slower but needs no extra capacity.
Q58.How do you run a stateful service such as a database on an orchestrator?
Stateful services need things that stateless ones do not: a stable identity, storage that follows each replica, and a careful order for starting, stopping and updating. Orchestrators provide a dedicated controller for this, but much of the risk remains with the team.
What a stateful workload controller provides:
- Stable names: each replica keeps the same name and network identity across restarts, such as db-0, db-1 and db-2.
- Dedicated volumes: each replica gets its own persistent volume, which is reattached when it is rescheduled.
- Ordered operations: replicas start, stop and update one at a time, in a defined order.
What you still need to handle:
- Replication and failover: the database itself must replicate data and elect a new primary.
- Backups and restores: volumes are not backups; test restoring regularly.
- Storage performance: choose volume types with suitable throughput and latency.
- Disruption limits: stop maintenance from taking down too many replicas at once.
- Operational automation: an operator, a controller that encodes expert procedures, can automate upgrades and failover.
Many teams use a managed database service instead, because it removes most of this work; running databases on an orchestrator makes sense when the team has the skills and a strong reason.
Q59.What are namespaces in a cluster, and how do resource quotas protect a shared cluster?
A namespace is a logical partition of a cluster that groups related resources, such as everything belonging to one team or one environment. Names must be unique only within a namespace, and many policies are applied per namespace.
What namespaces are used for:
- Separating teams or applications so their resources do not collide or get changed by mistake.
- Access control: roles grant permissions within a namespace, so a team can manage only its own workloads.
- Policies: network rules and security settings can apply to a whole namespace.
How quotas and limits protect the cluster:
- A resource quota caps the total CPU, memory, storage and object count a namespace may use, so one team cannot consume the whole cluster.
- Default limits give containers sensible requests and limits when a workload does not set them.
- Without quotas, one bad deployment, such as a runaway autoscaler, can starve every other team.
Namespaces are not a strong security boundary: workloads in different namespaces still share nodes and the kernel. Untrusted tenants need separate clusters or extra isolation.
Q60.How does external traffic reach a service running inside a cluster?
External traffic enters through a load balancer at the cluster edge, is routed by rules on host name and path to the right service, and is then spread across that service's healthy replicas.
- DNS points the public host name to the external load balancer's address.
- The load balancer receives the connection and forwards it to the cluster's edge proxy.
- The edge proxy applies routing rules, such as sending
/apito the API service and everything else to the web service, and usually terminates TLS. - The service forwards the request to one of its ready replicas.
flowchart LR A["User"] --> B["Public DNS"] B --> C["External load balancer"] C --> D["Edge proxy with routing rules"] D -->|path api| E["API service"] D -->|other paths| F["Web service"] E --> G["API replicas"] F --> H["Web replicas"]Design points:
- Terminate TLS at the edge and manage certificates automatically, with renewal before expiry.
- Expose only the edge proxy publicly; internal services stay on the cluster network.
- Add rate limits and request size limits at the edge to protect services behind it.