Skip to content

DevOps Interview Questions & Answers

All 200 unique questions in one place — 60 easy, 95 medium, 45 hard — grouped by topic.

Practise by topic

Solved overallStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between a process and a thread in Linux?

Save to ▾
Show answer
A process is a running program with its own address space, file descriptors and PID. A thread is a unit of execution inside a process that shares the same memory and open files with other threads. Creating threads is cheaper and they communicate easily, but a bug in one thread can crash the whole process, while separate processes are isolated from each other.
02

Explain Linux file permissions and what chmod 755 means.

Save to ▾
Show answer
Every file has read (4), write (2) and execute (1) bits for three classes: owner, group and others. chmod 755 gives the owner 7 (read, write, execute) and gives group and others 5 (read, execute). It is typical for scripts and directories that everyone may run or enter but only the owner may change. Use ls -l to see permissions.
03

What is the difference between a hard link and a soft link?

Save to ▾
Show answer
A hard link is another directory entry pointing to the same inode, so the data survives until every hard link is deleted; it cannot cross file systems or point to directories. A soft (symbolic) link is a small file that stores a path to the target; it can cross file systems and point to directories, but it breaks if the target is moved or deleted.
04

How do you manage a service with systemd?

Save to ▾
Show answer
systemctl status nginx sudo systemctl start nginx sudo systemctl restart nginx sudo systemctl enable nginx # start at boot sudo systemctl disable nginx journalctl -u nginx -f # follow service logs sudo systemctl daemon-reload # after editing a unit file Unit files live in /etc/systemd/system. enable creates the symlink for the boot target, while start only runs it now.
05

What is the difference between kill, kill -15 and kill -9?

Save to ▾
Show answer
kill sends SIGTERM (15) by default, which asks the process to stop so it can close files, finish requests and clean up. kill -9 sends SIGKILL, which the kernel enforces immediately; the process cannot catch it, so data may be lost and temp files left behind. Always try SIGTERM first and use SIGKILL only when the process does not respond.
06

Explain stdin, stdout, stderr and what 2>&1 means.

Save to ▾
Show answer
Every process gets three file descriptors: 0 is stdin, 1 is stdout and 2 is stderr. > redirects stdout to a file, 2> redirects errors, and 2>&1 sends stderr to wherever stdout currently points. So command > out.log 2>&1 captures both normal output and errors in one file. Order matters: 2>&1 placed before > out.log would still print errors to the terminal.
07

How do you schedule a cron job to run every day at 2:30 AM?

Save to ▾
Show answer
crontab -e # min hour day month weekday command 30 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1 crontab -l # list jobs Use absolute paths because cron runs with a minimal PATH and environment. Redirect output to a log, otherwise errors are mailed or lost. On systemd hosts, timers are an alternative with better logging.
08

Your app fails to start with 'address already in use' on port 8080. What do you do?

Save to ▾
Show answer
Find what is holding the port with ss -ltnp | grep 8080 or lsof -i :8080. If it is an old instance of the same app that did not shut down, stop it gracefully or fix the service manager so only one runs. If it is another service, change one app's port through configuration rather than hard coding. Then restart and confirm with curl localhost:8080.
09

What is the difference between sudo and su?

Save to ▾
Show answer
su switches to another user, usually root, and needs that user's password, giving a full shell as them. sudo runs a single command with elevated rights using your own password, and is controlled by rules in /etc/sudoers. sudo is preferred in teams because each action is logged against the real user and access can be limited to specific commands.
10

Why do you want to build a career in DevOps?

Save to ▾
Show answer
I enjoy both writing code and understanding how systems run in production, and DevOps sits between the two. In my projects I set up a CI pipeline and Docker deployment and liked seeing a change go from commit to live in minutes. I want to keep learning cloud, Kubernetes and automation, and help teams release faster with fewer failures.
11

What is an inode in Linux?

Save to ▾
Show answer
An inode is a data structure that stores a file's metadata: owner, permissions, size, timestamps, link count and pointers to data blocks, but not the file name. Names live in directory entries that map to inode numbers. A file system has a fixed number of inodes, so millions of tiny files can exhaust them while disk space is still free; check with df -i.
12

What is load average in Linux and how do you read it?

Save to ▾
Show answer
Load average is the average number of processes running or waiting for CPU (and uninterruptible I/O) over 1, 5 and 15 minutes, shown by uptime or top. Compare it with the number of CPU cores: a load of 4 on a 4-core machine means full use, while 12 means work is queuing. A high load with low CPU use often points to disk or network I/O waits.
13

What are zombie and orphan processes?

Save to ▾
Show answer
A zombie is a process that has exited but whose parent has not yet read its exit status with wait(), so it still holds a PID entry and shows state Z. An orphan is a running process whose parent died; it is adopted by PID 1, which reaps it later. Many zombies indicate a buggy parent; fixing or restarting the parent clears them.
14

What does set -euo pipefail do in a bash script?

Save to ▾
Show answer
set -e exits the script when any command fails, set -u treats unset variables as errors, and set -o pipefail makes a pipeline fail if any command in it fails, not just the last. Together they stop a script from silently continuing after an error, which matters in CI and deployment scripts. Commands that may fail on purpose need explicit handling such as || true.
15

How do you find files larger than 100 MB and older than 7 days under /var/log?

Save to ▾
Show answer
find /var/log -type f -size +100M -mtime +7 -exec ls -lh {} + # compress them instead of just listing find /var/log -type f -size +100M -mtime +7 -exec gzip {} + -size +100M matches files above 100 MB, -mtime +7 means modified more than 7 days ago, and -exec with + passes many files to one command call, which is faster than running it once per file.
16

Write a bash script that checks whether a service is running and restarts it if not.

Save to ▾
Show answer
#!/bin/bash set -u SERVICE="nginx" if ! systemctl is-active --quiet "$SERVICE"; then echo "$(date) $SERVICE down, restarting" >> /var/log/svc-check.log systemctl restart "$SERVICE" if ! systemctl is-active --quiet "$SERVICE"; then echo "$SERVICE failed to start" | mail -s "ALERT" ops@example.com fi fi Run it from cron every few minutes; a real setup would rely on systemd Restart= plus monitoring.
17

How do you count unique client IP addresses in an nginx access log?

Save to ▾
Show answer
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10 # total number of unique IPs awk '{print $1}' access.log | sort -u | wc -l The first field in the default log format is the client IP. uniq -c only collapses adjacent lines, so sort must run before it; the final sort -rn shows the busiest IPs first.
18

Write a script that alerts when any disk partition is above 80 percent used.

Save to ▾
Show answer
#!/bin/bash THRESHOLD=80 df -hP | awk 'NR>1 {gsub("%","",$5); print $5, $6}' | while read -r used mount; do if [ "$used" -ge "$THRESHOLD" ]; then echo "WARNING: $mount is ${used}% full on $(hostname)" fi done df -P keeps each entry on one line, awk strips the percent sign, and the loop compares each value with the threshold.
19

A production server is very slow. How do you troubleshoot high CPU usage?

Save to ▾
Show answer
Start with uptime and top or htop to see load and which processes use CPU. Check whether it is user, system or iowait time, and use pidstat or ps -eo pid,pcpu,cmd --sort=-pcpu for detail. For a Java process, take thread dumps; for others, use perf or strace. Correlate with recent deployments, cron jobs or traffic spikes before deciding to scale, roll back or fix code.
20

You suddenly cannot SSH into a Linux server. What do you check?

Save to ▾
Show answer
Check reachability with ping and whether port 22 is open with nc -zv host 22. Then look at security groups, firewall rules and whether the sshd service is running, using the cloud console or serial access. Run ssh -vvv to see whether it fails at key exchange or authentication. Common causes are wrong key permissions, a full disk, a changed IP, or fail2ban blocking you.
21

Tell me about a time you automated a repetitive manual task.

Save to ▾
Show answer
Situation: our team manually cleaned old build artefacts on shared servers every week, which took two hours and sometimes deleted the wrong files. Task: I offered to automate it. Action: I wrote a bash script with dry-run mode, logging and a retention rule, tested it on staging and scheduled it with cron. Result: zero manual effort and no more full-disk alerts for six months.
22

Explain the Linux boot process briefly.

Save to ▾
Show answer
The firmware (BIOS or UEFI) runs hardware checks and loads the bootloader, usually GRUB. GRUB loads the kernel and the initramfs, which contains drivers needed to mount the real root file system. The kernel then starts PID 1, which is systemd on most modern distributions. systemd mounts file systems and starts services in parallel according to unit dependencies and the default target.
23

df shows the disk is 100 percent full but du does not find large files. What is happening?

Save to ▾
Show answer
Usually a large file was deleted while a process still holds it open, so the space is not released. Run lsof +L1 or lsof | grep deleted to find the process and file. Restarting or reloading that process frees the space; if you cannot restart, truncate the file through /proc/<pid>/fd/<n>. The fix is proper log rotation with copytruncate or a reopen signal.
24

The kernel OOM killer keeps killing your application. How do you handle it?

Save to ▾
Show answer
Confirm with dmesg or journalctl -k, which shows the OOM message and the killed process. Check whether memory grows over time (a leak) or spikes with load. Set correct heap limits, for example JVM -Xmx below container memory, add swap only as a buffer, and set memory limits so one service cannot starve others. Then profile the app and right-size the instance.
25

An application logs 'Too many open files'. How do you fix it?

Save to ▾
Show answer
The process has hit its file descriptor limit. Check usage with ls /proc/<pid>/fd | wc -l and the limit in /proc/<pid>/limits. Raise it through LimitNOFILE in the systemd unit or /etc/security/limits.conf, then restart. But also look for a leak: sockets or files not closed in code keep growing and will hit any limit. Raising the limit alone only buys time.
26

What is Git and how is it different from GitHub?

Save to ▾
Show answer
Git is a distributed version control system that tracks changes to files; every clone has the full history and works offline. GitHub is a hosting service built around Git that adds remote repositories, pull requests, code review, issues and Actions for CI. Alternatives such as GitLab and Bitbucket offer similar features. You can use Git without GitHub, but not the other way round.
27

What is the difference between git fetch and git pull?

Save to ▾
Show answer
git fetch downloads new commits and branches from the remote into remote-tracking branches like origin/main without touching your working files. git pull is fetch followed by merge (or rebase if configured) into your current branch. Fetch is safer when you want to inspect incoming changes first with git log main..origin/main before integrating them.
28

What is git stash and when do you use it?

Save to ▾
Show answer
git stash saves your uncommitted changes and cleans the working directory, so you can switch branches for an urgent fix. git stash list shows saved entries, git stash pop reapplies the latest and removes it, and git stash apply keeps it. Use git stash -u to include untracked files. It is a short-term tool; for longer work, commit on a branch.
29

What does git cherry-pick do?

Save to ▾
Show answer
git cherry-pick <hash> applies the changes of one specific commit onto your current branch as a new commit. It is useful to bring a hotfix from main into a release branch without merging everything else. Overusing it creates duplicate commits with different hashes and can cause confusing conflicts later, so prefer merging when you need a whole set of changes.
30

What is .gitignore and how do you stop tracking a file that is already committed?

Save to ▾
Show answer
A .gitignore file lists patterns such as node_modules/, *.log or .env that Git should not track. It only affects untracked files, so a file already committed keeps being tracked. To stop tracking it, run git rm --cached <file>, add it to .gitignore and commit. If it held a secret, the old commits still contain it and the secret must be rotated.
31

How do you undo the last commit but keep the changes?

Save to ▾
Show answer
git reset --soft HEAD~1 # undo commit, keep changes staged git reset HEAD~1 # undo commit, keep changes unstaged # only fix the message or add a missed file git add missed-file.txt git commit --amend Use these only on commits not yet pushed. For a pushed commit on a shared branch, use git revert instead.
32

How do you create a new branch, push it and set the upstream?

Save to ▾
Show answer
git switch -c feature/payment-retry # make changes git add . git commit -m "Add retry for failed payments" git push -u origin feature/payment-retry After -u (set upstream), plain git push and git pull work on this branch without naming the remote. Then open a pull request against main.
33

How do you view the commit history in a compact graph form?

Save to ▾
Show answer
git log --oneline --graph --decorate --all # last 10 commits by one author git log --oneline -10 --author="Ravi" # commits touching one file, with diffs git log -p -- src/app.py # who changed each line git blame src/app.py --graph draws branch and merge lines, and --decorate shows branch and tag names next to commits.
34

How do you create a release tag and push it?

Save to ▾
Show answer
git tag -a v1.2.0 -m "Release 1.2.0" git push origin v1.2.0 # push all tags git push origin --tags # list and inspect git tag -l "v1.*" git show v1.2.0 Annotated tags (-a) store author, date and message and are preferred for releases. Many CI pipelines trigger production builds on tags matching v*.
35

How do you make your commits and pull requests easy for teammates to review?

Save to ▾
Show answer
I keep each pull request focused on one change and small enough to review in about fifteen minutes. Commits have clear messages saying what and why. The description explains the problem, the approach, how I tested it and any risk or rollback step. I run linters and tests locally first, and I reply to every review comment, even if just to say done.
36

What is the difference between git merge and git rebase?

Save to ▾
Show answer
Merge joins two branches with a merge commit and keeps the true history, including when work happened in parallel. Rebase replays your commits on top of the target branch, giving a clean linear history but new commit hashes. Rebase local feature branches to stay current, but never rebase commits others have already pulled, because it rewrites shared history.
37

What is a detached HEAD state in Git?

Save to ▾
Show answer
HEAD normally points to a branch name. In detached HEAD, it points directly to a commit, for example after git checkout <hash> or checking out a tag. You can look around and even commit, but new commits belong to no branch and can be lost when you switch away. To keep them, create a branch with git switch -c new-branch.
38

Explain git reset --soft, --mixed and --hard.

Save to ▾
Show answer
All three move the current branch pointer to another commit. --soft keeps your changes staged, useful for recombining commits. --mixed, the default, keeps changes in the working directory but unstaged. --hard discards changes in both staging and working directory, so uncommitted work is lost. Lost commits can usually still be found with git reflog for a while.
39

What is the difference between git revert and git reset?

Save to ▾
Show answer
git revert creates a new commit that undoes the changes of an earlier commit, leaving history intact, so it is safe on shared branches like main. git reset moves the branch pointer backwards and removes commits from the branch history, which is fine locally but forces others to deal with rewritten history if already pushed. Use revert for anything already public.
40

What are Git hooks and how are they used in DevOps?

Save to ▾
Show answer
Hooks are scripts Git runs at events such as pre-commit, commit-msg and pre-push on the client, or pre-receive on the server. Teams use them to run linters, format code, block secrets or enforce commit message formats before code leaves a laptop. Client hooks are not shared by default, so tools like pre-commit or Husky manage them, and CI repeats the checks.
41

How do you resolve a merge conflict?

Save to ▾
Show answer
Git marks conflicting files and inserts markers showing both versions. Open each file, decide the correct final code, often combining both sides after talking to the other author, and remove the markers. Then git add the files and finish with git commit or git rebase --continue. Run tests before pushing, because a conflict resolved without errors can still break logic.
42

You deleted a local branch that had unmerged commits. How do you recover it?

Save to ▾
Show answer
Git keeps unreferenced commits for a while. Run git reflog to see recent HEAD positions and find the last commit of that branch, or check the hash printed when you deleted it. Then recreate the branch with git branch feature-x <hash>. Reflog is local only, so this works on the same machine, and entries expire after about 90 days by default.
43

You pushed a broken commit to the shared main branch and the build is failing. What do you do?

Save to ▾
Show answer
First restore a green main quickly: run git revert <hash> and push, which adds an undo commit without rewriting history that others have pulled. Tell the team in the channel. Then fix the issue on a branch with a proper pull request and tests. Avoid git reset with force push on main; branch protection rules should block it anyway.
44

How do you squash your last three commits into one?

Save to ▾
Show answer
git rebase -i HEAD~3 # in the editor, keep the first line as pick # and change the other two to squash (or s) pick a1b2c3 Add login API squash d4e5f6 Fix typo squash 789abc Add tests # alternative without the editor git reset --soft HEAD~3 git commit -m "Add login API with tests" If the branch was already pushed, update it with git push --force-with-lease.
45

Tell me about a time you disagreed with a code review comment.

Save to ▾
Show answer
Situation: a reviewer asked me to replace a simple retry loop in our deploy script with a heavy external library. Task: I felt it added risk. Action: I explained my reasoning, shared a small benchmark and failure tests, and asked what concern they had; it was about backoff. Result: I added exponential backoff to my version, they approved, and we documented the pattern.
46

Compare GitFlow and trunk-based development.

Save to ▾
Show answer
GitFlow uses long-lived develop and main branches plus feature, release and hotfix branches; it suits scheduled releases but causes big merges. Trunk-based development has everyone merge small changes into main at least daily, with short-lived branches and feature flags to hide unfinished work. It suits continuous delivery and is what high-performing DevOps teams usually prefer, but needs strong automated tests.
47

A developer accidentally pushed an AWS access key to a public repository. What do you do?

Save to ▾
Show answer
Treat the key as compromised immediately: deactivate and rotate it in IAM, then check CloudTrail for misuse. Removing it from history comes second, using git filter-repo or BFG and a force push, and asking everyone to re-clone. Then prevent repeats with secret scanning in CI, pre-commit hooks like gitleaks and storing secrets in a vault or secrets manager instead of code.
48

Your repository has become huge because of binary files and clones are very slow. How do you fix it?

Save to ▾
Show answer
Short term, CI can use shallow clones with --depth 1 and partial clone filters. For future binaries, move them to Git LFS or an artefact store such as S3 or Nexus. To shrink existing history, use git filter-repo to remove the large files, coordinate a force push and ask everyone to re-clone. Add size checks in pre-receive hooks to prevent recurrence.
49

Two features are in main but only one must go to production this week. How do you manage this?

Save to ▾
Show answer
The cleanest approach is feature flags: both features merge to main, but the unfinished one stays switched off in production, so deployment is separated from release. Without flags, you cut a release branch and revert or exclude the second feature, which is error prone. For the future, keep branches short-lived and agree with product on flag-based releases.
50

How do you use git bisect to find the commit that introduced a bug?

Save to ▾
Show answer
git bisect start git bisect bad # current commit has the bug git bisect good v1.4.0 # last known good tag # Git checks out a middle commit; test it, then mark it git bisect good # or: git bisect bad # repeat until Git prints the first bad commit git bisect reset # automate with a test script git bisect run ./run-tests.sh Bisect is a binary search, so 1000 commits need about 10 tests.
51

What is the difference between continuous integration, continuous delivery and continuous deployment?

Save to ▾
Show answer
Continuous integration means developers merge small changes often and every merge is automatically built and tested. Continuous delivery goes further: every passing build is packaged and ready to release, but a human approves the production push. Continuous deployment removes that manual step, so every change that passes all checks goes to production automatically. Each stage needs more test confidence than the last.
52

What are the typical stages of a CI/CD pipeline?

Save to ▾
Show answer
A common pipeline is checkout, build or compile, unit tests, static analysis and security scans, packaging into an artefact or container image, pushing to a registry, deploying to a test or staging environment, running integration or smoke tests, an approval gate, and production deployment with monitoring. Fast checks run first so developers get feedback within minutes and slow tests run later.
53

What is an artefact repository and why is it used?

Save to ▾
Show answer
An artefact repository such as Nexus, JFrog Artifactory or a container registry stores versioned build outputs like JAR files, npm packages and Docker images. The pipeline builds once and promotes the same artefact through dev, staging and production, so what you tested is exactly what you deploy. It also caches public dependencies, speeds up builds and keeps release history for rollbacks.
54

What is a webhook and how does it trigger a build?

Save to ▾
Show answer
A webhook is an HTTP callback: when an event happens in the Git server, such as a push or pull request, it sends a POST request with event details to a configured URL. Jenkins or another CI tool receives it and starts the matching pipeline immediately. This is better than polling the repository every few minutes, which wastes resources and delays feedback.
55

The build works on your laptop but fails on the CI server. How do you debug it?

Save to ▾
Show answer
The environments differ. Compare tool versions such as JDK, Node or Python, environment variables, and dependency versions, especially if there is no lock file. Check for files present locally but not committed, and for hard-coded paths. Reproduce by running the build inside the same Docker image the CI agent uses. Long term, build inside containers so local and CI match.
56

Explain the Jenkins controller and agent architecture.

Save to ▾
Show answer
The Jenkins controller stores configuration, schedules jobs, serves the UI and keeps build history. Agents are separate machines or containers that actually execute build steps, connected over SSH or JNLP and selected by labels. Running builds on agents rather than the controller keeps the controller stable and secure, and lets you scale with dynamic agents on Kubernetes or cloud VMs that are created per build.
57

What is the difference between declarative and scripted Jenkins pipelines?

Save to ▾
Show answer
Both are written in a Jenkinsfile using Groovy. Declarative pipelines use a fixed structure with pipeline, agent, stages, steps and post blocks, which is easy to read, validate and maintain. Scripted pipelines start with node and allow full Groovy logic, giving more flexibility but more room for messy code. Most teams use declarative and drop into a script block only when needed.
58

Compare blue-green, canary and rolling deployments.

Save to ▾
Show answer
Blue-green runs two full environments and switches traffic from old to new at once; rollback is instant but costs double capacity. Rolling replaces instances in batches with no extra environment, but old and new versions run together for a while. Canary sends a small share of traffic, say 5 percent, to the new version and widens it as metrics stay healthy, limiting blast radius.
59

How do you manage secrets in a CI/CD pipeline?

Save to ▾
Show answer
Never store secrets in code or the Jenkinsfile. Use the CI tool's encrypted credentials store, such as Jenkins credentials or GitHub Actions secrets, or fetch them at runtime from HashiCorp Vault or AWS Secrets Manager. Prefer short-lived credentials, for example OIDC federation from GitHub Actions to AWS instead of long-lived keys. Mask secrets in logs and give each pipeline only the permissions it needs.
60

Builds fail randomly because of flaky tests. How do you handle it?

Save to ▾
Show answer
First identify flaky tests by tracking which tests fail and pass on the same commit. Quarantine them into a separate non-blocking job so the main pipeline stays trustworthy, and raise tickets with owners. Common causes are timing assumptions, shared test data, order dependence and external services. Blind automatic retries hide real bugs, so use them only briefly while fixing the root cause.
61

A production deployment failed halfway. What do you do?

Save to ▾
Show answer
Assess impact quickly using monitoring and error rates. If users are affected, roll back to the last good version, which should be a single pipeline action redeploying the previous artefact. Communicate status to stakeholders. Then check pipeline logs and application logs to find the cause, fix it in a branch and redeploy. Afterwards, hold a blameless review and add a check to catch it earlier.
62

You need one pipeline that deploys to dev, staging and production with approval before production. How do you design it?

Save to ▾
Show answer
Build and test once, publish a versioned artefact, then promote it through environments. Dev deploys automatically on merge, staging deploys after dev smoke tests, and production waits for a manual approval from authorised people using a Jenkins input step or GitHub environment protection rules. Keep environment-specific settings in config files or parameters, not separate pipelines, and record who approved each release.
63

Write a declarative Jenkinsfile with build, test and deploy stages.

Save to ▾
Show answer
pipeline { agent { label 'linux' } stages { stage('Build') { steps { sh 'mvn -B clean package -DskipTests' } } stage('Test') { steps { sh 'mvn -B test' } post { always { junit 'target/surefire-reports/*.xml' } } } stage('Deploy') { when { branch 'main' } steps { sh './deploy.sh staging' } } } post { failure { echo 'Build failed' } } }
64

Write a GitHub Actions workflow that runs tests on every pull request.

Save to ▾
Show answer
name: CI on: pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 cache: npm - run: npm ci - run: npm test Add this as .github/workflows/ci.yml and make the job a required status check in branch protection.
65

How do you run a matrix build in GitHub Actions?

Save to ▾
Show answer
jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] python: ['3.11', '3.12'] steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - run: pip install -r requirements.txt - run: pytest This creates four parallel jobs; fail-fast false lets all finish so you see every failure.
66

How do you build and push a Docker image from a pipeline?

Save to ▾
Show answer
# shell steps in any CI tool IMAGE=registry.example.com/shop/api TAG=$(git rev-parse --short HEAD) echo "$REG_PASS" | docker login registry.example.com -u "$REG_USER" --password-stdin docker build -t $IMAGE:$TAG . docker push $IMAGE:$TAG Tag with the commit SHA so each image is traceable and immutable; avoid relying on latest. Credentials come from the CI secret store, and --password-stdin keeps them out of process lists.
67

How do you use stored credentials inside a Jenkins pipeline?

Save to ▾
Show answer
pipeline { agent any environment { SONAR_TOKEN = credentials('sonar-token') } stages { stage('Push') { steps { withCredentials([usernamePassword(credentialsId: 'docker-hub', usernameVariable: 'USER', passwordVariable: 'PASS')]) { sh 'echo $PASS | docker login -u $USER --password-stdin' } } } } } Jenkins masks these values in console output. Use single quotes in sh so Groovy does not interpolate the secret.
68

How do you handle pressure when a release is blocked close to a deadline?

Save to ▾
Show answer
Situation: a security scan blocked our release one day before a client demo. Task: ship without ignoring the risk. Action: I checked the finding, confirmed it was a real vulnerable library, upgraded it, ran the full test suite and kept the product manager updated every few hours. Result: we released on time, and I added weekly dependency scans to avoid last-minute surprises.
69

What is DevSecOps and which security checks belong in a pipeline?

Save to ▾
Show answer
DevSecOps moves security earlier into the delivery process instead of a final audit. A pipeline typically adds secret scanning, static code analysis (SAST) with tools like SonarQube, dependency scanning (SCA) for vulnerable libraries, container image scanning with Trivy, infrastructure-as-code checks with Checkov, and sometimes dynamic testing (DAST) on staging. Critical findings fail the build, while lower ones create tickets.
70

What is GitOps?

Save to ▾
Show answer
GitOps uses a Git repository as the single source of truth for the desired state of infrastructure and applications. An agent running in the cluster, such as Argo CD or Flux, continuously compares the live state with Git and pulls changes to reconcile drift. Deployments become pull requests, giving review, audit history and easy rollback by reverting a commit. CI builds images; GitOps handles deployment.
71

What are DORA metrics?

Save to ▾
Show answer
DORA metrics measure software delivery performance: deployment frequency, lead time for changes, change failure rate and time to restore service. The first two measure speed and the last two measure stability. Elite teams deploy on demand with lead times under a day and recover within an hour. DevOps teams use them to find bottlenecks, not to rank individual engineers.
72

Your CI pipeline takes 40 minutes. How would you speed it up?

Save to ▾
Show answer
Measure first: find which stages take longest. Then cache dependencies and Docker layers, run independent stages and test suites in parallel, split tests across agents, and run only affected modules in a monorepo. Move slow end-to-end tests to a later stage or nightly run while keeping fast unit tests on every commit. Use bigger or autoscaled agents if they are the bottleneck.
73

The Jenkins controller is slow and builds keep queueing. What do you do?

Save to ▾
Show answer
Make sure no builds run on the controller by setting its executors to zero. Add agents, ideally dynamic ones on Kubernetes or EC2 that scale with the queue. Check controller heap, disk and plugin count, and remove unused plugins. Discard old builds and artefacts with retention rules. For very large setups, split teams across multiple controllers or move suitable jobs to another CI tool.
74

How do you run stages in parallel in a Jenkins declarative pipeline?

Save to ▾
Show answer
stage('Tests') { parallel { stage('Unit') { steps { sh 'mvn test' } } stage('Lint') { steps { sh 'mvn checkstyle:check' } } stage('Security') { agent { docker { image 'aquasec/trivy' } } steps { sh 'trivy fs --exit-code 1 --severity CRITICAL .' } } } } Add failFast true to abort the others when one fails. Each branch can use its own agent.
75

Tell me about a production deployment that went wrong and how you handled it.

Save to ▾
Show answer
Situation: a release passed staging but caused payment timeouts in production because a new connection pool setting was wrong. Task: as release owner, I had to restore service. Action: I triggered the rollback job within ten minutes, updated stakeholders, then found the config difference between environments. Result: service recovered quickly and we added config validation and a canary stage to the pipeline.
76

What is the difference between a container and a virtual machine?

Save to ▾
Show answer
A virtual machine runs a full guest operating system on a hypervisor, so it is heavier, takes minutes to boot and uses gigabytes. A container shares the host kernel and isolates only the application and its dependencies using namespaces and cgroups, so it starts in seconds and uses far less memory. VMs give stronger isolation; containers give density and portability.
77

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

Save to ▾
Show answer
An image is a read-only template made of layers, containing the application, libraries and configuration, built from a Dockerfile. A container is a running instance of an image with a thin writable layer on top. You can start many containers from one image. Changes made inside a container are lost when it is removed unless they are stored in volumes.
78

What is the difference between COPY and ADD in a Dockerfile?

Save to ▾
Show answer
COPY copies local files and directories into the image and does nothing else. ADD can also download from a URL and automatically extracts local tar archives. Because that extra behaviour can be surprising, best practice is to use COPY by default and ADD only when you specifically want tar extraction. For downloads, use curl in a RUN step so you can verify checksums.
79

What is Docker Compose?

Save to ▾
Show answer
Docker Compose defines and runs multi-container applications from a YAML file, usually compose.yaml. You describe services, networks, volumes, environment variables and dependencies, then start everything with docker compose up. It is ideal for local development and testing, for example an API, database and cache together. For production orchestration across many hosts, teams use Kubernetes instead.
80

A container exits immediately after it starts. How do you debug it?

Save to ▾
Show answer
Run docker ps -a to see the exit code and docker logs <id> for output. Exit code 0 usually means the main process finished, for example a script that ran once or a service started in background mode, so the container has nothing to keep it alive. Non-zero codes point to errors such as missing config. Start an interactive shell with docker run -it --entrypoint sh to inspect.
81

Database data disappeared after the container was recreated. Why, and how do you fix it?

Save to ▾
Show answer
Data written inside the container's writable layer is deleted when the container is removed. The database must store its data directory in a named volume or bind mount, for example -v pgdata:/var/lib/postgresql/data. Then containers can be upgraded or recreated without losing data. Also take regular backups, because volumes protect against container removal, not against disk failure.
82

Which Docker commands do you use to debug a running container?

Save to ▾
Show answer
docker ps # running containers docker logs -f --tail 100 api # follow logs docker exec -it api sh # shell inside docker inspect api # config, IP, mounts, env docker stats # live CPU and memory docker top api # processes inside docker cp api:/app/log.txt . # copy a file out docker events # daemon events Use sh for alpine images, where bash may not exist.
83

How do you keep yourself updated with new DevOps tools and practices?

Save to ▾
Show answer
I follow official release notes for tools I use, such as Kubernetes and Terraform, and read a few engineering blogs and CNCF updates weekly. I learn by doing, so I try new tools in a small home lab or free cloud tier before suggesting them. I also prepare for certifications to structure my learning, and share short notes with my team.
84

How do Docker image layers and build caching work?

Save to ▾
Show answer
Each Dockerfile instruction like RUN, COPY or ADD creates a layer. Docker caches layers and reuses them if the instruction and its inputs have not changed; once one layer changes, all later layers rebuild. So copy dependency files and install dependencies first, then copy source code. That way code changes do not reinstall all packages, and builds become much faster.
85

What is the difference between CMD and ENTRYPOINT?

Save to ▾
Show answer
ENTRYPOINT defines the main executable that always runs, while CMD provides default arguments or a default command that can be overridden from docker run. For example, ENTRYPOINT ["python", "app.py"] with CMD ["--port", "8000"] lets users change only the port. Use the exec (JSON array) form so the process runs as PID 1 and receives signals properly.
86

Explain Docker network types.

Save to ▾
Show answer
bridge is the default: containers get private IPs on a virtual bridge and reach outside through NAT; user-defined bridges also provide DNS by container name. host shares the host's network stack directly, with no port mapping. none disables networking. overlay connects containers across multiple hosts in Swarm. macvlan gives a container its own MAC address on the physical network.
87

What is the difference between volumes and bind mounts?

Save to ▾
Show answer
A volume is storage managed by Docker under its own directory, created with docker volume create and referenced by name; it is portable and is the recommended way to persist data such as databases. A bind mount maps a specific host path into the container, which is handy for local development hot reload but depends on host directory layout and permissions.
88

What is a multi-stage Docker build and why use it?

Save to ▾
Show answer
A multi-stage build uses several FROM instructions in one Dockerfile. Early stages contain compilers and build tools to produce the artefact; the final stage starts from a small runtime image and copies only the built output with COPY --from. The result is a much smaller image with fewer vulnerabilities, because build tools, source code and caches never reach production.
89

Your Docker image is 1.5 GB. How do you reduce its size?

Save to ▾
Show answer
Switch to a slimmer base image such as a slim or distroless variant. Use a multi-stage build so compilers and build caches stay out of the final image. Combine package installs and clean caches in the same RUN layer. Add a .dockerignore to exclude .git, node_modules and test data. Then inspect remaining layers with docker history or the dive tool.
90

Two containers on the same host cannot talk to each other. What do you check?

Save to ▾
Show answer
Check that both are on the same user-defined network with docker network inspect; the default bridge does not resolve container names. Use the service or container name and the container's internal port, not localhost and not the published host port. Confirm the app listens on 0.0.0.0 rather than 127.0.0.1. Then test with curl or nc from inside one container.
91

The host disk is filling up because of Docker. How do you clean up and prevent it?

Save to ▾
Show answer
Check usage with docker system df. Remove stopped containers, dangling images and unused networks with docker system prune, and old build cache with docker builder prune; be careful with the volumes flag. Container logs are a common culprit, so configure log rotation with max-size and max-file in daemon.json. In CI agents, schedule regular pruning jobs.
92

Write a production-ready Dockerfile for a Node.js application.

Save to ▾
Show answer
FROM node:20-alpine WORKDIR /app ENV NODE_ENV=production COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY . . USER node EXPOSE 3000 CMD ["node", "server.js"] Dependencies are copied and installed before source code so the layer is cached. npm ci gives reproducible installs, USER node avoids running as root, and exec form CMD lets the app receive signals.
93

Write a multi-stage Dockerfile for a Java Spring Boot application.

Save to ▾
Show answer
FROM maven:3.9-eclipse-temurin-21 AS build WORKDIR /src COPY pom.xml . RUN mvn -B dependency:go-offline COPY src ./src RUN mvn -B package -DskipTests FROM eclipse-temurin:21-jre-alpine WORKDIR /app COPY --from=build /src/target/*.jar app.jar RUN adduser -D appuser USER appuser EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"] The final image has only the JRE and the JAR, not Maven or source.
94

Write a Docker Compose file for a web app with a PostgreSQL database.

Save to ▾
Show answer
services: web: build: . ports: - "8000:8000" environment: DATABASE_URL: postgres://app:secret@db:5432/appdb depends_on: db: condition: service_healthy db: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: secret POSTGRES_DB: appdb volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD", "pg_isready", "-U", "app"] interval: 5s volumes: pgdata:
95

How do you limit CPU and memory for a container?

Save to ▾
Show answer
docker run -d --name api \ --memory=512m --memory-swap=512m \ --cpus=1.5 \ --restart=unless-stopped \ myapp:1.0 # change limits on a running container docker update --memory=1g --memory-swap=1g api If the process exceeds the memory limit it is OOM killed, so set application heap sizes below the limit. --cpus caps CPU time rather than reserving cores.
96

How do you add a health check to a Docker image?

Save to ▾
Show answer
FROM nginx:1.27-alpine COPY site/ /usr/share/nginx/html/ HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ CMD wget -qO- http://localhost/ || exit 1 # check status docker inspect --format '{{.State.Health.Status}}' web Docker marks the container healthy or unhealthy. Compose can wait on it with condition: service_healthy. Kubernetes ignores HEALTHCHECK and uses its own probes.
97

Tell me about a time you introduced a new tool or practice to your team.

Save to ▾
Show answer
Situation: new developers took two days to set up our app locally because of different OS versions and manual database installs. Task: I wanted to make onboarding easy. Action: I created a Docker Compose setup with the app, database and seed data, wrote a short README and demoed it. Result: setup dropped to under an hour and the team adopted it for CI.
98

How do containers work under the hood using namespaces and cgroups?

Save to ▾
Show answer
Linux namespaces give each container its own isolated view of process IDs, network interfaces, mount points, hostname, users and IPC, so it believes it is alone on the machine. Control groups (cgroups) limit and account for CPU, memory and I/O usage. A container runtime such as containerd with runc sets these up, plus an overlay file system for image layers.
99

What are the best practices for securing Docker images?

Save to ▾
Show answer
Use small, trusted base images such as distroless or alpine and pin versions or digests. Run as a non-root user, use multi-stage builds, and never bake secrets into layers. Scan images with Trivy or similar in CI and rebuild regularly to pick up patches. At runtime, drop Linux capabilities, use read-only root file systems and sign images to verify their source.
100

Your container takes 10 seconds to stop and does not shut down gracefully. Why?

Save to ▾
Show answer
docker stop sends SIGTERM to PID 1 and waits 10 seconds before SIGKILL. If the Dockerfile uses shell form like CMD node app.js, PID 1 is a shell that does not forward signals, so the app never gets SIGTERM. Use exec form CMD ["node", "app.js"], use exec in entrypoint scripts, or add an init such as tini with --init, and handle SIGTERM in code.
101

What is Kubernetes and why do companies use it?

Save to ▾
Show answer
Kubernetes is an open-source container orchestration platform. You declare the desired state, such as five replicas of an API, and it schedules containers across nodes, restarts failed ones, scales them, balances traffic and rolls out updates. Companies use it to run many microservices reliably on shared infrastructure, on any cloud or on-premises, through managed services like EKS, AKS and GKE.
102

What is the difference between a Pod, a ReplicaSet and a Deployment?

Save to ▾
Show answer
A Pod is the smallest deployable unit: one or more containers sharing network and storage. A ReplicaSet keeps a specified number of identical pods running. A Deployment manages ReplicaSets and adds rolling updates and rollbacks by creating a new ReplicaSet for each version. In practice you create Deployments and rarely touch ReplicaSets or bare pods directly.
103

What is the difference between a ConfigMap and a Secret?

Save to ▾
Show answer
Both inject configuration into pods as environment variables or mounted files, keeping config out of images. ConfigMaps hold non-sensitive data like URLs and feature flags. Secrets hold sensitive values like passwords and tokens; they are only base64 encoded by default, so you should enable encryption at rest, restrict access with RBAC, or use an external secrets manager.
104

What is a DaemonSet and when is it used?

Save to ▾
Show answer
A DaemonSet makes sure one copy of a pod runs on every node, or on a selected group of nodes. When a node joins the cluster, the pod is added automatically. It is used for node-level agents such as log collectors like Fluent Bit, monitoring agents like the Prometheus node exporter, and CNI or storage plugins.
105

A pod shows ImagePullBackOff. What do you check?

Save to ▾
Show answer
The kubelet cannot pull the image. Check the image name and tag for typos and confirm the tag exists in the registry. For private registries, verify an imagePullSecret is set and has valid credentials, or that node IAM roles allow pulling from ECR. Also check network access from nodes to the registry and registry rate limits. kubectl describe pod shows the exact error.
106

Which kubectl commands do you use most for debugging?

Save to ▾
Show answer
kubectl get pods -n shop -o wide kubectl describe pod api-7d9f -n shop kubectl logs api-7d9f -n shop -c api --previous kubectl logs -l app=api -f --tail=50 kubectl exec -it api-7d9f -- sh kubectl get events -n shop --sort-by=.lastTimestamp kubectl top pods -n shop kubectl port-forward svc/api 8080:80 kubectl get endpoints api describe and events usually explain scheduling and startup problems; logs explain application problems.
107

Explain the Kubernetes architecture.

Save to ▾
Show answer
The control plane has the kube-apiserver, the front door for all requests; etcd, the key-value store holding cluster state; the scheduler, which places pods on nodes; and the controller manager, which runs reconciliation loops. Each worker node runs the kubelet, which starts and monitors pods; kube-proxy, which handles service networking; and a container runtime such as containerd.
108

Explain the Kubernetes Service types ClusterIP, NodePort and LoadBalancer.

Save to ▾
Show answer
A Service gives pods a stable IP and DNS name and load balances across them using label selectors. ClusterIP, the default, is reachable only inside the cluster. NodePort also opens a port, 30000 to 32767, on every node. LoadBalancer additionally asks the cloud provider to create an external load balancer pointing to the service. Each type builds on the previous one.
109

What is the difference between an Ingress and a Service?

Save to ▾
Show answer
A Service exposes a set of pods at layer 4. An Ingress is a layer 7 HTTP routing resource that maps hostnames and paths to services, for example api.example.com to the api service and /admin to another. It needs an ingress controller such as NGINX or a cloud controller to work. One Ingress with one load balancer can serve many services, and it handles TLS termination.
110

Explain liveness, readiness and startup probes.

Save to ▾
Show answer
A liveness probe checks whether the container is healthy; if it fails, the kubelet restarts it. A readiness probe checks whether it can serve traffic; if it fails, the pod is removed from service endpoints but not restarted. A startup probe gives slow-starting apps time to boot and holds off the other probes until it succeeds. Wrong liveness probes can cause restart loops.
111

When do you use a StatefulSet instead of a Deployment?

Save to ▾
Show answer
Use a StatefulSet for stateful workloads such as databases, Kafka or Elasticsearch that need stable identity. Pods get fixed names like db-0 and db-1, start and stop in order, and each gets its own PersistentVolumeClaim that follows it after rescheduling. A headless service gives each pod a stable DNS name. Deployments treat pods as interchangeable, which suits stateless apps.
112

How does the Horizontal Pod Autoscaler work?

Save to ▾
Show answer
The HPA periodically reads metrics from the metrics server or a custom metrics adapter and changes the replica count of a Deployment or StatefulSet to keep a target, for example 70 percent average CPU. It calculates desired replicas from current usage divided by the target, within min and max bounds, with stabilisation windows to avoid flapping. CPU-based HPA needs resource requests set.
113

A pod is in CrashLoopBackOff. How do you troubleshoot it?

Save to ▾
Show answer
The container starts and keeps crashing, and Kubernetes waits longer between restarts. Run kubectl describe pod to see events and exit codes, and kubectl logs <pod> --previous for the crashed container's output. Common causes are missing environment variables or secrets, bad config, failing database connections, a wrong command, an aggressive liveness probe, or exit code 137 meaning OOM kill.
114

A pod is stuck in Pending state. What could be the reasons?

Save to ▾
Show answer
Pending means it has not been scheduled or its volumes are not ready. kubectl describe pod shows the scheduler's reason. Common causes are insufficient CPU or memory on nodes for the requests, node selectors, affinity or taints that no node satisfies, a PersistentVolumeClaim that cannot bind, or a resource quota being exceeded. Fix the spec or add nodes with the cluster autoscaler.
115

Pods are running but the service is not reachable. How do you debug it?

Save to ▾
Show answer
Run kubectl get endpoints <svc>; if empty, the service selector does not match the pod labels or pods are not ready. Check that the service targetPort matches the container port. Test from a debug pod with curl svc-name.namespace:port to separate DNS from app issues. Then check network policies blocking traffic and, for external access, the ingress rules and load balancer health checks.
116

Write a Deployment manifest with 3 replicas, resource limits and a readiness probe.

Save to ▾
Show answer
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/api:1.4.2 ports: - containerPort: 8080 resources: requests: {cpu: 250m, memory: 256Mi} limits: {cpu: 500m, memory: 512Mi} readinessProbe: httpGet: {path: /health, port: 8080} periodSeconds: 5
117

How do you perform a rolling update and roll back a Deployment?

Save to ▾
Show answer
# update the image kubectl set image deployment/api api=registry.example.com/api:1.5.0 kubectl rollout status deployment/api # history and rollback kubectl rollout history deployment/api kubectl rollout undo deployment/api kubectl rollout undo deployment/api --to-revision=3 # pause or restart kubectl rollout pause deployment/api kubectl rollout restart deployment/api In GitOps setups, you change the image tag in Git instead and let Argo CD apply it.
118

What is Helm and what are its basic commands?

Save to ▾
Show answer
helm repo add bitnami https://charts.bitnami.com/bitnami helm repo update helm install my-redis bitnami/redis -n cache --create-namespace helm upgrade my-redis bitnami/redis -f values-prod.yaml helm list -A helm rollback my-redis 1 helm uninstall my-redis -n cache helm template ./mychart -f values.yaml # render locally Helm is the package manager for Kubernetes. A chart is a set of templated manifests, and values files customise it per environment.
119

How do you create a Secret and use it as an environment variable in a pod?

Save to ▾
Show answer
kubectl create secret generic db-creds \ --from-literal=DB_USER=app --from-literal=DB_PASS='S3cret!' -n shop # in the container spec env: - name: DB_PASS valueFrom: secretKeyRef: name: db-creds key: DB_PASS # or load all keys envFrom: - secretRef: name: db-creds Pods do not pick up changed env values until restarted; mounted secret files update automatically.
120

Describe how you handled an on-call incident late at night.

Save to ▾
Show answer
Situation: at 2 AM I got an alert that checkout error rates crossed 10 percent. Task: restore service as on-call engineer. Action: I checked dashboards, saw a node pool had scaled down and pods were pending, scaled it manually, and posted updates in the incident channel. Result: errors cleared in 20 minutes, and next day I fixed the autoscaler settings and wrote the post-mortem.
121

What are resource requests and limits, and what are QoS classes?

Save to ▾
Show answer
Requests are what the scheduler reserves for a container when placing it on a node; limits are the maximum it may use. Exceeding a CPU limit causes throttling, while exceeding a memory limit gets the container OOM killed. Pods are Guaranteed when requests equal limits, Burstable when requests are lower, and BestEffort with none; BestEffort pods are evicted first under node pressure.
122

How does RBAC work in Kubernetes?

Save to ▾
Show answer
RBAC controls who can do what on which resources. A Role defines allowed verbs like get, list or create on resources within a namespace; a ClusterRole does so cluster-wide. RoleBindings and ClusterRoleBindings attach those roles to users, groups or service accounts. Follow least privilege: give each application its own service account with only the permissions it needs.
123

During rolling updates some user requests fail. How do you get true zero-downtime deployments?

Save to ▾
Show answer
Add a proper readiness probe so new pods get traffic only when ready. Set maxUnavailable to 0 and maxSurge to 1 or more. Handle SIGTERM gracefully and add a short preStop sleep so endpoints update before the old pod stops accepting connections, with terminationGracePeriodSeconds long enough to drain requests. Add a PodDisruptionBudget for node maintenance too.
124

A worker node shows NotReady. What do you do?

Save to ▾
Show answer
Run kubectl describe node to see conditions such as MemoryPressure, DiskPressure or a kubelet that stopped posting status. SSH in and check systemctl status kubelet, the container runtime, journalctl -u kubelet, disk space and network to the API server. Pods on the node are evicted after a timeout. Cordon and drain it, fix or replace the node, and in cloud setups let the node group recreate it.
125

Tell me about a time you migrated an application to Kubernetes.

Save to ▾
Show answer
Situation: our monolith and five services ran on hand-managed VMs with frequent config drift. Task: I led the move to a managed Kubernetes cluster. Action: I containerised each service, wrote Helm charts, added probes and resource limits, set up Argo CD, and migrated one low-risk service first with a rollback plan. Result: deployments went from weekly to daily and VM costs dropped about 30 percent.
126

What is Infrastructure as Code and what are its benefits?

Save to ▾
Show answer
Infrastructure as Code means defining servers, networks, databases and other resources in version-controlled files instead of clicking in a console. Benefits are repeatable environments, code review for infrastructure changes, history and rollback through Git, fewer manual mistakes, faster provisioning and easy disaster recovery. Common tools are Terraform and OpenTofu for provisioning and Ansible for configuration management.
127

Explain the basic Terraform workflow.

Save to ▾
Show answer
terraform init downloads providers and modules and configures the backend. terraform fmt and validate check style and syntax. terraform plan shows what will be created, changed or destroyed without making changes. terraform apply executes the plan after confirmation. terraform destroy removes all managed resources. In CI, save the plan with -out and apply that exact plan after review.
128

Explain Ansible architecture: inventory, modules and playbooks.

Save to ▾
Show answer
Ansible runs from a control node and connects to managed hosts over SSH, or WinRM for Windows, with no agent needed. The inventory lists hosts and groups. Modules are units of work like apt, copy or service. Playbooks are YAML files containing plays that map host groups to ordered tasks. Variables, templates with Jinja2 and roles organise larger automation.
129

How do you define variables and outputs in Terraform?

Save to ▾
Show answer
# variables.tf variable "instance_type" { type = string default = "t3.micro" description = "EC2 size" } # outputs.tf output "public_ip" { value = aws_instance.web.public_ip } # use them terraform apply -var="instance_type=t3.small" terraform apply -var-file=prod.tfvars terraform output public_ip Outputs also pass values between modules.
130

Write an Ansible playbook to install and start nginx.

Save to ▾
Show answer
- name: Configure web servers hosts: web become: true tasks: - name: Install nginx ansible.builtin.apt: name: nginx state: present update_cache: true - name: Deploy site config ansible.builtin.template: src: site.conf.j2 dest: /etc/nginx/conf.d/site.conf notify: Reload nginx - name: Ensure nginx is running ansible.builtin.service: name: nginx state: started enabled: true handlers: - name: Reload nginx ansible.builtin.service: name: nginx state: reloaded
131

How do you write an Ansible inventory and run ad-hoc commands?

Save to ▾
Show answer
# inventory.ini [web] web1 ansible_host=10.0.1.10 web2 ansible_host=10.0.1.11 [db] db1 ansible_host=10.0.2.20 [all:vars] ansible_user=ubuntu # ad-hoc commands ansible all -i inventory.ini -m ping ansible web -i inventory.ini -a "uptime" ansible web -i inventory.ini -m apt -a "name=htop state=present" --become Ad-hoc commands suit quick one-off checks; repeatable work belongs in playbooks.
132

What is the difference between declarative and imperative IaC, and between Terraform and Ansible?

Save to ▾
Show answer
Declarative tools describe the end state and the tool works out the steps; imperative tools describe the steps. Terraform is declarative, keeps a state file and is best at provisioning cloud resources. Ansible is procedural with mostly idempotent modules, agentless over SSH, and best at configuring servers and deploying software. Many teams use Terraform to create VMs and Ansible to configure them.
133

What is the Terraform state file and why is it important?

Save to ▾
Show answer
terraform.tfstate maps the resources in your code to real resources in the cloud, storing their IDs and attributes. Terraform compares code, state and reality to decide what to create, change or destroy. Without it Terraform would not know what it manages. It may contain secrets in plain text, so store it in a secure remote backend, never in Git.
134

What is remote state and state locking in Terraform?

Save to ▾
Show answer
Remote state stores the state file in a shared backend such as an S3 bucket, Azure Storage or Terraform Cloud, so the whole team and CI use the same state. Locking prevents two runs from changing state at the same time, avoiding corruption; on S3 it uses a lock file or a DynamoDB table. Enable versioning and encryption on the backend for recovery and security.
135

What are Terraform modules?

Save to ▾
Show answer
A module is a reusable folder of Terraform files with input variables and outputs, for example a vpc module or an eks-cluster module. The root module calls child modules with different values for each environment. Modules reduce duplication and enforce standards across teams. They can come from local paths, Git or the Terraform Registry and should be pinned to versions.
136

What is the difference between count and for_each in Terraform?

Save to ▾
Show answer
count creates N copies indexed by number, such as aws_instance.web[0]. Removing an item in the middle shifts indexes and can destroy and recreate resources unexpectedly. for_each iterates over a map or set of strings and keys each instance by name, such as aws_s3_bucket.b["logs"], so adding or removing one item affects only that item. Prefer for_each for named collections.
137

What does idempotency mean in Ansible?

Save to ▾
Show answer
Idempotency means running the same playbook many times gives the same result without unwanted changes. Modules check current state first: the apt module installs a package only if missing and reports ok instead of changed. The shell and command modules are not idempotent by default, so use creates, removes or changed_when conditions, or prefer a dedicated module.
138
Save to ▾
Show answer
A role is a standard folder structure that packages tasks, handlers, templates, files, variables and defaults for one purpose, for example a nginx or postgres role. Playbooks then just list roles for host groups, keeping them short and reusable across projects. Roles can be shared through Ansible Galaxy or collections, and tested with Molecule.
139

You need to bring existing manually created cloud resources under Terraform. How?

Save to ▾
Show answer
Write the resource blocks in code, then import the real resources into state. Since Terraform 1.5 you can declare import blocks with the resource ID and run plan; terraform plan -generate-config-out can even draft the configuration. Older versions use the terraform import CLI command. Run plan until it shows no changes, which proves code matches reality.
140

An Ansible playbook run against 100 servers failed on 7 of them. What do you do?

Save to ▾
Show answer
Check the output and the retry file or failed host list to see the error on those hosts, for example unreachable SSH, a missing package repo or full disk. Fix the cause, then rerun only those hosts with --limit. Because tasks are idempotent, rerunning on successful hosts is also safe. For rolling changes, use serial and max_fail_percentage to stop early on failures.
141

Write Terraform code to create an AWS EC2 instance.

Save to ▾
Show answer
terraform { required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } } } provider "aws" { region = "ap-south-1" } resource "aws_instance" "web" { ami = var.ami_id instance_type = "t3.micro" subnet_id = var.subnet_id tags = { Name = "web-server" Env = "dev" } } Run terraform init, plan and apply. ap-south-1 is the Mumbai region.
142

How do you configure an S3 remote backend with locking?

Save to ▾
Show answer
terraform { backend "s3" { bucket = "acme-terraform-state" key = "prod/network/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true } } Then run terraform init (add -migrate-state if moving local state). Enable versioning on the bucket. Older setups use dynamodb_table = "tf-locks" instead of use_lockfile for locking.
143

What are Ansible handlers and how do you use them?

Save to ▾
Show answer
Handlers are tasks that run only when notified by another task that reported a change, and they run once at the end of the play even if notified many times. tasks: - name: Update app config ansible.builtin.copy: src: app.conf dest: /etc/app/app.conf notify: Restart app handlers: - name: Restart app ansible.builtin.service: name: app state: restarted This avoids restarting services when nothing changed.
144

Tell me about a mistake you made in infrastructure work and what you learned.

Save to ▾
Show answer
Situation: I applied a Terraform change that renamed a security group, which forced replacement and briefly cut access to a staging database. Task: fix it and prevent repeats. Action: I restored access quickly, explained it openly to my lead, and then added plan review in pull requests plus lifecycle create_before_destroy rules. Result: no similar outage since, and I now read every destroy line in a plan.
145

What is configuration drift and how do you detect it with Terraform?

Save to ▾
Show answer
Drift is when real infrastructure differs from code, usually because someone changed it manually in the console. terraform plan, or plan -refresh-only, shows differences between state and reality. Teams run scheduled plans in CI and alert on any diff. Prevent drift by restricting console write access, applying only through pipelines, and either reverting manual changes or codifying them.
146

Two engineers ran terraform apply at the same time. What could go wrong and how do you prevent it?

Save to ▾
Show answer
Without locking, both runs read the same state and write conflicting updates, which can corrupt state or create duplicate resources. Use a remote backend with state locking so the second run waits or fails. Better still, run apply only from a CI pipeline on merge to main, so changes are serialised and reviewed. If a lock is stuck after a crash, use terraform force-unlock carefully.
147

Someone deleted a resource manually that Terraform manages, and the state is now out of sync. What do you do?

Save to ▾
Show answer
Run terraform plan; Terraform refreshes and sees the resource is missing, so it plans to recreate it, which is often right. If the resource should no longer exist, remove it from code, or use terraform state rm. If state itself is corrupted, restore a previous version from the versioned S3 bucket. Then find out why manual changes happened and tighten access.
148

How do you manage dev, staging and production environments with Terraform?

Save to ▾
Show answer
Keep shared logic in versioned modules and create a separate root configuration per environment, each with its own backend state and tfvars, for example envs/dev and envs/prod. This isolates state so a mistake in dev cannot touch prod. Workspaces are an option for near-identical environments but share backend config. Promote module versions from dev to prod through pull requests.
149

How do you handle secrets in Terraform and Ansible?

Save to ▾
Show answer
Do not hard-code secrets in .tf files or playbooks. In Terraform, read them from AWS Secrets Manager or Vault data sources, mark variables sensitive, and protect state because it may still hold values. In Ansible, encrypt secret variable files with ansible-vault and supply the vault password from CI secrets, or look up values from Vault at runtime. Rotate anything exposed in Git.
150

How would you convince a team that manages servers by hand to adopt Infrastructure as Code?

Save to ▾
Show answer
I would start with their pain, such as slow environment setup or outages from manual changes, rather than the tool. Then I would codify one small, visible piece, for example a new staging environment, and show it rebuilt in minutes with a reviewed pull request. I would pair with team members, write simple docs and expand gradually, measuring time saved and incidents avoided.
151

What are AWS Regions, Availability Zones and edge locations?

Save to ▾
Show answer
A Region is a geographic area such as ap-south-1 in Mumbai or ap-south-2 in Hyderabad, fully independent from others. Each Region has multiple Availability Zones, which are separate data centres with independent power and networking, linked by low-latency connections. Edge locations are smaller sites used by CloudFront and Route 53 to cache content and answer DNS close to users.
152

Explain IAM users, groups, roles and policies.

Save to ▾
Show answer
An IAM user is an identity for a person or app with long-term credentials. Groups collect users so permissions are managed together. Policies are JSON documents that allow or deny actions on resources. Roles are identities with temporary credentials that are assumed by services, such as EC2 or Lambda, or by users from other accounts. Prefer roles over access keys wherever possible.
153

What are the S3 storage classes and lifecycle policies?

Save to ▾
Show answer
S3 Standard is for frequently accessed data. Standard-IA and One Zone-IA are cheaper for infrequent access but charge retrieval fees. Intelligent-Tiering moves objects automatically based on access. Glacier Instant, Flexible Retrieval and Deep Archive are for archives with slower, cheaper access. Lifecycle rules move objects between classes after a set age and delete old versions or logs automatically.
154

What is the AWS shared responsibility model?

Save to ▾
Show answer
AWS is responsible for security of the cloud: physical data centres, hardware, the network and the hypervisor. The customer is responsible for security in the cloud: IAM, data encryption, OS patching on EC2, security groups and application code. The split shifts with the service; for managed services like RDS or Lambda, AWS handles more of the underlying patching.
155

Which AWS CLI commands do you commonly use?

Save to ▾
Show answer
aws configure aws sts get-caller-identity aws ec2 describe-instances \ --filters Name=instance-state-name,Values=running \ --query 'Reservations[].Instances[].[InstanceId,PrivateIpAddress]' --output table aws s3 cp build.zip s3://acme-artifacts/releases/ aws s3 sync ./site s3://acme-site --delete aws logs tail /aws/lambda/orders --follow get-caller-identity confirms which account and role you are using before you run anything risky.
156

Write an EC2 user data script that installs and starts a web server on boot.

Save to ▾
Show answer
#!/bin/bash set -e dnf update -y dnf install -y nginx systemctl enable --now nginx TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \ -H 'X-aws-ec2-metadata-token-ttl-seconds: 60') ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \ http://169.254.169.254/latest/meta-data/instance-id) echo "<h1>Served by $ID</h1>" > /usr/share/nginx/html/index.html User data runs once as root on first boot; logs are in /var/log/cloud-init-output.log. This uses IMDSv2.
157

Tell me about a time you had to learn a new cloud service quickly.

Save to ▾
Show answer
Situation: in my internship, the team needed a scheduled job and asked me to use AWS Lambda, which I had never used. Task: deliver it in a week. Action: I went through the official docs and a hands-on tutorial, built a small proof of concept on day two, and asked a senior to review the IAM role. Result: the job went live on time and I documented the setup.
158

Explain the main components of an AWS VPC.

Save to ▾
Show answer
A VPC is your private network with a CIDR range like 10.0.0.0/16. It is split into subnets in each Availability Zone. Public subnets have a route to an Internet Gateway; private subnets reach the internet only through a NAT Gateway in a public subnet. Route tables control traffic, security groups and NACLs filter it, and VPC endpoints give private access to services like S3.
159

What is the difference between a security group and a network ACL?

Save to ▾
Show answer
A security group acts as a firewall for instances or network interfaces. It is stateful, so return traffic is allowed automatically, and it supports only allow rules. A network ACL works at the subnet level, is stateless, so inbound and outbound rules must both allow traffic, supports allow and deny rules, and evaluates rules in number order. Security groups are the main control.
160

How do an Application Load Balancer and an Auto Scaling group work together?

Save to ▾
Show answer
The Auto Scaling group launches EC2 instances from a launch template across several Availability Zones and keeps the count between min and max, scaling on policies such as target 60 percent CPU. It registers instances with the ALB's target group. The ALB spreads HTTP traffic across healthy targets, routes by path or host, and health checks let the group replace failed instances.
161

When would you choose ECS, EKS or Lambda?

Save to ▾
Show answer
Lambda runs functions without servers, billed per request and duration, ideal for event-driven tasks with short runtimes up to 15 minutes. ECS is AWS's simpler container orchestrator, good when you want containers without Kubernetes complexity, often with Fargate. EKS is managed Kubernetes, chosen for portability, a rich ecosystem and existing Kubernetes skills, but it needs more operational knowledge.
162

An EC2 instance in a private subnet cannot download packages from the internet. Why?

Save to ▾
Show answer
A private subnet has no direct route to the Internet Gateway. Check that its route table sends 0.0.0.0/0 to a NAT Gateway placed in a public subnet, that the NAT Gateway has an Elastic IP, and that the security group and NACL allow outbound traffic and return ports. For AWS services like S3, a VPC endpoint avoids NAT data charges.
163

An application on EC2 needs to read files from S3. How do you give it access securely?

Save to ▾
Show answer
Create an IAM role with a policy allowing only the needed actions, such as s3:GetObject on that bucket, attach it to the instance through an instance profile, and let the AWS SDK pick up temporary credentials automatically. Never put access keys in code or config files. Optionally add a bucket policy and a VPC endpoint so traffic stays inside AWS.
164

Someone made an S3 bucket with customer files public. What do you do?

Save to ▾
Show answer
Immediately block public access on the bucket and remove the public policy or ACLs. Check S3 server access logs or CloudTrail data events to see whether objects were downloaded, and involve security if customer data was exposed. Then enable Block Public Access at the account level, use AWS Config rules to detect public buckets, and require bucket changes through reviewed IaC.
165

The application cannot connect to an RDS database. What do you check?

Save to ▾
Show answer
Confirm the endpoint, port, username and password. Check that the RDS security group allows inbound traffic on the database port from the application's security group, and that both are in reachable subnets of the same VPC or peered networks. Test with nc -zv endpoint 5432 from the app host. Also check the instance status, max connections and SSL requirements.
166

Write an IAM policy that gives read-only access to one S3 bucket.

Save to ▾
Show answer
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": "arn:aws:s3:::acme-reports" }, { "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::acme-reports/*" } ] } ListBucket applies to the bucket ARN and GetObject to object ARNs, so both resources are needed.
167

How do you assume an IAM role in another account using the AWS CLI?

Save to ▾
Show answer
# ~/.aws/config [profile prod-admin] role_arn = arn:aws:iam::123456789012:role/DevOpsAdmin source_profile = default region = ap-south-1 aws s3 ls --profile prod-admin # manual way aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/DevOpsAdmin \ --role-session-name ravi-session The role's trust policy must allow your account. Temporary credentials expire, usually after an hour.
168

How do you create an EKS cluster with eksctl and connect kubectl to it?

Save to ▾
Show answer
eksctl create cluster \ --name shop-dev \ --region ap-south-1 \ --nodegroup-name workers \ --node-type t3.medium \ --nodes 2 --nodes-min 2 --nodes-max 5 \ --managed aws eks update-kubeconfig --name shop-dev --region ap-south-1 kubectl get nodes eksctl builds CloudFormation stacks for the VPC, control plane and node group. In production, teams usually manage EKS with Terraform modules instead.
169

Tell me about a time you reduced cloud costs.

Save to ▾
Show answer
Situation: our dev and test AWS accounts cost almost as much as production. Task: my manager asked me to cut waste without slowing teams. Action: I tagged resources by owner, found idle instances and old snapshots, scheduled non-production instances to stop at night with a Lambda, and moved CI agents to Spot. Result: non-production spend fell about 40 percent within two months.
170

How do you prioritise when several teams ask you for infrastructure work at the same time?

Save to ▾
Show answer
I list the requests with their business impact and deadline, and check which are blocking production or a release. Production issues and security fixes come first. For the rest I agree priority with my lead and the requesting teams openly, give realistic timelines and share progress. Where requests repeat, I build self-service templates so teams are not waiting on me.
171

How do you design a highly available web application on AWS?

Save to ▾
Show answer
Spread every tier across at least two Availability Zones. Put an ALB in front of an Auto Scaling group of stateless instances or containers. Use RDS Multi-AZ or Aurora for the database and ElastiCache for sessions. Serve static content from S3 through CloudFront and use Route 53 health checks. Remove single points of failure and test failover regularly.
172

The monthly AWS bill suddenly doubled. How do you investigate and fix it?

Save to ▾
Show answer
Open Cost Explorer and group by service, account and tag to find the spike, then drill into usage type. Common causes are forgotten instances, unattached EBS volumes, NAT Gateway data transfer, oversized RDS, or logs retained forever. Fix the source, then set AWS Budgets alerts, enforce tagging, right-size using Compute Optimizer, and use Savings Plans or Spot for steady or batch workloads.
173

An e-commerce site expects 10 times normal traffic during a festive sale. How do you prepare?

Save to ▾
Show answer
Load test beforehand to find bottlenecks. Pre-scale Auto Scaling groups or Kubernetes nodes with scheduled scaling, since reactive scaling may be too slow. Cache aggressively with CloudFront and Redis, add read replicas, and check service quotas. Use queues to absorb spikes in order processing, set up dashboards and alerts, freeze risky deployments, and keep an on-call war room ready.
174

How would you plan disaster recovery for a complete AWS region failure?

Save to ▾
Show answer
Start from business RTO and RPO. Options range from backup and restore, which is cheapest and slowest, to pilot light, warm standby and multi-region active-active. Replicate data with S3 cross-region replication, Aurora Global Database or DynamoDB global tables, keep infrastructure in Terraform so it can be rebuilt, use Route 53 failover routing and rehearse failover drills.
175

How do you work with developers who resist new DevOps processes?

Save to ▾
Show answer
Situation: a team saw our new pipeline checks as slowing them down. Task: get adoption without forcing it. Action: I sat with them to understand the pain, found that the scans added twelve minutes, moved slow scans to run in parallel and made results clearer. Result: pipeline time went below the old one, the team adopted it and later suggested further improvements.
176

What is the difference between monitoring and observability?

Save to ▾
Show answer
Monitoring tracks known metrics and alerts when they cross thresholds, answering whether something is wrong. Observability is the ability to understand any internal state from outside data, answering why, even for problems you did not predict. It rests on three pillars: metrics for trends, logs for detailed events and traces for following one request across services. Good systems need both.
177

What is the ELK or EFK stack?

Save to ▾
Show answer
ELK is Elasticsearch, Logstash and Kibana: Logstash or Beats collect and parse logs, Elasticsearch stores and indexes them, and Kibana provides search and dashboards. EFK replaces Logstash with Fluentd or Fluent Bit, which is common in Kubernetes as a DaemonSet. Centralised logging lets you search across all servers and containers in one place instead of SSH-ing into each.
178

What is Site Reliability Engineering, and what is toil?

Save to ▾
Show answer
SRE, which began at a large search company, applies software engineering to operations: teams own reliability through SLOs, error budgets, automation, incident management and capacity planning. Toil is manual, repetitive, automatable work that grows with scale and adds no lasting value, such as manually restarting services. SRE teams aim to keep toil below about half their time and automate the rest.
179

You get an alert that the company website is down. What are your first steps?

Save to ▾
Show answer
Acknowledge the alert so others know you are on it. Check whether it is really down from outside with curl or an uptime checker, and whether it is all users or one region. Look at recent deployments or changes, then load balancer health, application logs and the database. If a recent change caused it, roll back first. Inform the team and escalate if you cannot fix it quickly.
180

How do you configure Prometheus to scrape a target?

Save to ▾
Show answer
# prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: node static_configs: - targets: ['10.0.1.10:9100', '10.0.1.11:9100'] - job_name: api metrics_path: /metrics static_configs: - targets: ['api.internal:8080'] # validate and reload promtool check config prometheus.yml curl -X POST http://localhost:9090/-/reload Port 9100 is the node exporter default. In Kubernetes, use service discovery or ServiceMonitors instead.
181

How much downtime does a 99.9 percent availability SLO allow?

Save to ▾
Show answer
Allowed downtime = (1 - SLO) x period 99.9 percent over 30 days: 0.001 x 30 x 24 x 60 = 43.2 minutes per month 99.9 percent over a year = about 8.76 hours 99.95 percent per month = about 21.6 minutes 99.99 percent per month = about 4.3 minutes Each extra nine cuts the budget tenfold and usually needs much more redundancy and automation, so pick an SLO that matches real user needs.
182

How do you quickly search logs for errors from the last hour on a server or in Kubernetes?

Save to ▾
Show answer
# systemd service journalctl -u api --since "1 hour ago" -p err # plain log files grep -i "error" /var/log/app/app.log | tail -50 grep -c "timeout" /var/log/app/app.log # Kubernetes kubectl logs deploy/api --since=1h | grep -i error kubectl logs -l app=api --since=1h --prefix | grep 500 For many hosts, search the central logging tool instead, filtering by service, level and time.
183

How do you handle the stress of on-call duty?

Save to ▾
Show answer
I prepare before my shift by reading recent incidents and making sure runbooks and access work. During an incident I follow the runbook, stay calm and escalate early instead of struggling alone, because quick recovery matters more than solving it myself. Afterwards I note what was confusing and improve the docs or alerts, so each rotation gets easier for everyone.
184

What are the Prometheus metric types?

Save to ▾
Show answer
A counter only increases, such as total requests, and you use rate() on it. A gauge goes up and down, such as memory in use or queue length. A histogram counts observations into configurable buckets, such as request duration, and lets you compute percentiles with histogram_quantile across instances. A summary computes quantiles on the client side but cannot be aggregated across instances.
185

What are the four golden signals, and the RED and USE methods?

Save to ▾
Show answer
The four golden signals are latency, traffic, errors and saturation. RED, for request-driven services, tracks rate, errors and duration. USE, for resources such as CPU, disks and network, tracks utilisation, saturation and errors. RED tells you whether users are hurting; USE helps find which resource is the bottleneck. Together they give a solid starting set of dashboards and alerts.
186

The on-call team gets dozens of alerts every night and is burning out. How do you fix it?

Save to ▾
Show answer
Collect alert data for a few weeks: which fired, how often, and whether anyone acted. Delete or downgrade non-actionable alerts, tune thresholds and add for durations, and group duplicates in Alertmanager. Fix the recurring root causes behind the top alerts and automate common fixes. Move to SLO-based alerts and make sure rotations are fair with follow-up time after bad nights.
187

Write PromQL queries for request rate, error rate and p95 latency.

Save to ▾
Show answer
# requests per second per service over 5 minutes sum by (service) (rate(http_requests_total[5m])) # error ratio (5xx) sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) # p95 latency from a histogram histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) rate() works on counters and handles resets; the le label holds histogram bucket bounds.
188

Write a Prometheus alerting rule for a high error rate.

Save to ▾
Show answer
groups: - name: api-alerts rules: - alert: HighErrorRate expr: | sum(rate(http_requests_total{job="api",status=~"5.."}[5m])) / sum(rate(http_requests_total{job="api"}[5m])) > 0.05 for: 10m labels: severity: page annotations: summary: "API error rate above 5 percent" runbook: "https://wiki.example.com/runbooks/api-errors" for: 10m ignores short spikes; Alertmanager routes by the severity label.
189

Tell me about a blameless post-mortem you were part of.

Save to ▾
Show answer
Situation: a certificate expired and our API was down for 40 minutes. Task: I wrote the post-mortem. Action: I built a timeline from logs and chat, and we focused on why the system allowed it rather than who forgot: renewal was manual and nothing alerted. Result: we automated renewal with cert-manager, added expiry alerts 21 days ahead, and tracked actions to closure.
190

How do you communicate with stakeholders during an outage?

Save to ▾
Show answer
I post a short first update quickly saying what is affected, that we are working on it and when the next update will come. Then I update at a fixed interval, such as every 20 minutes, in plain language without guessing at causes. I keep technical detail in the engineering channel. After resolution, I send a summary with impact, cause and next steps.
191

Explain the Prometheus architecture.

Save to ▾
Show answer
Prometheus pulls, or scrapes, metrics over HTTP from targets that expose a /metrics endpoint, either apps instrumented with client libraries or exporters such as node exporter. Targets come from static config or service discovery, for example Kubernetes. Data is stored in a local time-series database and queried with PromQL. Alert rules fire to Alertmanager, which groups, silences and routes notifications. Grafana visualises the data.
192

Explain SLI, SLO, SLA and error budget.

Save to ▾
Show answer
An SLI is a measured indicator, for example the share of requests served under 300 ms. An SLO is the internal target for it, such as 99.9 percent over 30 days. An SLA is the external contract with penalties, usually looser than the SLO. The error budget is the allowed unreliability, 0.1 percent here; while budget remains teams ship features, and when it runs out they focus on reliability.
193

What is distributed tracing and how does OpenTelemetry help?

Save to ▾
Show answer
Distributed tracing follows one request across many services. Each operation is a span with timing and attributes, and spans share a trace ID passed in request headers, so tools like Jaeger or Tempo can show where time is spent. OpenTelemetry is the vendor-neutral standard and SDK for producing traces, metrics and logs, so you instrument once and send data to any backend.
194

What makes a good alert, and how do you avoid alert fatigue?

Save to ▾
Show answer
A good alert is actionable, urgent and tied to user impact, such as an SLO burn rate, not just high CPU. Each page should have a runbook link and a clear owner. Reduce noise by removing alerts nobody acts on, using severity levels so non-urgent issues create tickets, grouping related alerts, and using for durations to ignore short spikes. Review alerts after each on-call week.
195

Users complain the app is slow, but your dashboards look normal. What do you do?

Save to ▾
Show answer
Averages can hide pain, so check p95 and p99 latency, not mean. Find out which users, regions or features are affected; it may be one endpoint, a third-party API or client-side slowness. Use traces to follow a slow request and check DNS, CDN and front-end metrics through real user monitoring. Then add the missing signal to dashboards so it is visible next time.
196

You suspect a memory leak in a production service. How do you confirm and handle it?

Save to ▾
Show answer
Look at memory graphs over days: a leak shows steady growth that drops only on restart, often with OOM kills. Correlate the start with a deployment. Take heap dumps or profiles, for example jmap for Java or pprof for Go, and compare them over time. As a short-term fix, set memory limits and schedule restarts or roll back, then fix the code and add a memory alert.
197

You are the incident commander for a major outage. What do you do?

Save to ▾
Show answer
Declare the incident, open a channel and bridge, and assign roles: someone to investigate, someone to communicate and a scribe. My job is to coordinate, not to debug. Prioritise mitigation over root cause, such as rollback, failover or feature flags. Post regular status updates to stakeholders. After recovery, confirm it is stable, close it and schedule a blameless post-mortem with action items.
198

Logging costs are rising fast because of huge log volume. What do you do?

Save to ▾
Show answer
Find the top log sources by volume. Lower verbose debug logging in production, drop health check and noisy access logs, and sample high-volume info logs. Use structured logs to avoid duplicated fields. Set retention tiers: a few days hot, then archive to S3. Turn repeated log lines into metrics where only counts matter, which is far cheaper to store and query.
199

Your service has used its entire error budget halfway through the quarter. What happens next?

Save to ▾
Show answer
Following the agreed error budget policy, the team pauses risky feature launches and focuses on reliability work: fixing the top causes of failures from post-mortems, adding tests, improving rollbacks and canaries. Product and engineering leads review the plan together. Once the budget recovers in the rolling window, normal releases resume. If the SLO is unrealistic, revisit it with data.
200

Tell me about a time you improved the reliability of a system.

Save to ▾
Show answer
Situation: our order service had repeated weekend outages from database connection exhaustion. Task: as the senior engineer I owned the fix. Action: I defined an availability SLO, added connection pool metrics and alerts, introduced a connection proxy, and added load tests to the pipeline. Result: monthly availability went from about 99.5 to 99.95 percent and pages dropped by more than half.

Frequently asked questions

What jobs can I get after learning DevOps?

Freshers usually start as junior DevOps engineers, build and release engineers, cloud support associates or Linux administrators. With two to five years of hands-on experience you can move into DevOps engineer, cloud engineer and site reliability engineer roles, and later platform engineer, DevSecOps or cloud architect positions. IT services companies, product companies, banks, fintechs and startups across Bengaluru, Hyderabad, Pune, Noida, Gurugram and Chennai hire for these roles regularly.

Who is eligible to learn DevOps?

Anyone with basic computer knowledge can start, but it suits B.Tech, BCA, MCA and B.Sc IT students, software developers, testers and system or network administrators best. You do not need to be an expert programmer, but you should be comfortable with logic and willing to learn scripting. Professionals from support or testing backgrounds often switch to DevOps successfully because they already understand how applications run in production.

How long does it take to learn DevOps?

A focused learner can cover the core stack of Linux, Git, CI/CD, Docker, Kubernetes, Terraform and AWS in about four months with two to three hours of daily practice. Becoming job ready also needs hands-on projects that you can explain in interviews. Real depth in areas like Kubernetes operations, reliability and large-scale cloud design comes over the first few years of working on production systems.

Do I need coding knowledge for DevOps?

You need practical scripting rather than heavy application development. Bash is essential for automation on Linux, and Python is widely used for tooling and cloud scripts. You will also write a lot of YAML for pipelines and Kubernetes and HCL for Terraform. Being able to read application code helps you debug builds and production issues. Senior SRE and platform roles often expect stronger Python or Go skills.

Which certifications help in getting a DevOps job?

Useful certifications include AWS Certified Solutions Architect Associate or AWS DevOps Engineer Professional, Microsoft Azure Administrator or Azure DevOps Engineer Expert, Certified Kubernetes Administrator (CKA) and Certified Kubernetes Application Developer (CKAD) from the Linux Foundation, and HashiCorp Terraform Associate. Certifications help your resume clear screening, but interviewers mostly test hands-on skills, so combine them with real projects on GitHub.

Is DevOps a good career in India in 2026?

Yes. Companies keep moving workloads to cloud and Kubernetes, and they need engineers who can automate delivery, control cloud costs and keep systems reliable. DevOps, SRE and platform engineering roles are among the better paid technical roles at every experience level. The field changes quickly, with new tools and AI-assisted operations, so engineers who keep learning and understand fundamentals deeply grow fastest.