⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Kubernetes Interview Questions Scenario 156 of 207 in Kubernetes
Senior DevOps / SRE [L2] Kubernetes Additional Kubernetes Scenarios (Q101-Q200) Production Scenario [L2]
🎯 Target Role / Context: Kubernetes Scenario #146 (L2) · Additional Kubernetes Scenarios (Q101-Q200)

Q: How do you retrieve only the logs from a specific container in a pod that has multiple containers?

kubectl logs <pod> -c <container-name>. Get container names: kubectl get pod <pod> -o jsonpath='{.spec.containers[].name}'.

#Kubernetes #L2 #Container Orchestration #K8s
🎙️ Candidate Opening & Architectural Context
"To get the <strong>logs from a specific container in a pod</strong> that runs several containers, pass the container name with <code>kubectl logs &lt;pod&gt; -c &lt;container&gt;</code>. Without <code>-c</code>, kubectl either picks a default container and prints a notice or fails, depending on version and annotations. Interviewers use this simple question to check that you know a pod is a group of containers, that init containers and crashed containers need different flags, and that you can debug sidecar-heavy workloads such as service-mesh or logging agents without scraping everything. A complete answer includes how to discover container names, filter by time, follow streams and read the previous crashed instance."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's CKA & CKAD Hands-On Certification Track covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: To get the <strong>logs from a specific container in a pod</strong> that runs several containers, pass the container name with <code>kubectl logs &lt;pod&gt; -c &lt;container&gt;</code>. Without <code>-c</code>, kubectl either picks a default container and prints a notice or fails, depending on version and annotations. Interviewers use this simple question to check that you know a pod is a group of containers, that init containers and crashed containers need different flags, and that you can debug sidecar-heavy workloads such as service-mesh or logging agents without scraping everything. A complete answer includes how to discover container names, filter by time, follow streams and read the previous crashed instance.

1️⃣

Step zero: list the containers in the pod

You cannot select a container you cannot name, so start by discovering the names, including init and ephemeral ones.

  • Quick list: kubectl get pod my-pod -o jsonpath='{.spec.containers[*].name}' prints the regular containers; use .spec.initContainers[*].name for init containers.
  • Human view: kubectl describe pod my-pod shows each container state, restart count, last termination reason and exit code.
  • Hint from kubectl: running kubectl logs my-pod on a multi-container pod prints Defaulted container "app" out of: app, istio-proxy on modern versions, which reveals the names.
  • Default container: the annotation kubectl.kubernetes.io/default-container on the pod sets which container kubectl picks when -c is omitted.
2️⃣

Hands-on: logs from a specific container in a pod

The core command is the same for every case: add -c, then layer flags for time, size and follow behaviour.

# Only the app container
kubectl logs my-pod -n prod -c app

# Last 200 lines from the last 15 minutes, with timestamps
kubectl logs my-pod -n prod -c app --tail=200 --since=15m --timestamps

# Follow a sidecar live
kubectl logs my-pod -n prod -c istio-proxy -f --tail=0

# Init container logs (they have already exited)
kubectl logs my-pod -n prod -c wait-for-db
  • Basic: -c app returns only that container stdout and stderr as captured by the container runtime, leaving the sidecar noise out.
  • Bound the output: combine --tail=200, --since=15m and --timestamps so you do not download a huge log or lose time correlation.
  • Stream live: -f follows the log; pair it with --tail=0 to see only new lines during a reproduction.
  • Namespace: add -n prod, because a pod name alone resolves only in the current context namespace.
  • Multiple lines of context: -c app --tail=50 -f is the usual live debugging combination while you reproduce a request.
Advertisement
3️⃣

Crashed containers and many pods at once

A restarting container hides its failure reason in the previous instance, and real incidents involve several replicas.

# Why did it crash? read the previous run of the failing container
kubectl logs my-pod -n prod -c app --previous --tail=100

# All containers in all pods with this label, tagged by source
kubectl logs -n prod -l app=my-app --all-containers=true --prefix --since=10m

# Check exit code and reason first
kubectl get pod my-pod -n prod \
  -o jsonpath='{.status.containerStatuses[?(@.name=="app")].lastState.terminated}'
  • Previous instance: --previous (or -p) prints logs of the last terminated container, essential in CrashLoopBackOff where the current instance has just started.
  • Whole pod: --all-containers=true merges every container, and --prefix labels each line with pod and container so you can still tell them apart.
  • By label: kubectl logs -l app=my-app -c app reads from all matching pods; --max-log-requests caps parallel streams (default 5) when following many pods.
  • Via workload: kubectl logs deploy/my-app -c app selects one pod from the deployment, convenient but not a view of every replica.
4️⃣

Verify and troubleshoot common errors

Most failures come from a wrong name, a container that has not started, or logs that never reached the kubelet.

  • container not found: a typo or a name from another pod; recheck with the jsonpath listing and remember init and ephemeral containers use the same -c flag.
  • waiting to start: ContainerCreating or PodInitializing means no log exists yet; read kubectl describe pod events for image pull or volume problems.
  • Empty output: the app may log to a file instead of stdout; Kubernetes only exposes stdout and stderr, so run kubectl exec my-pod -c app -- tail /var/log/app.log for that case.
  • Logs vanish after deletion: kubectl reads from the node, so logs disappear when the pod is evicted or deleted and are subject to kubelet rotation limits.
5️⃣

Production practice beyond kubectl logs

kubectl is for live debugging; durable investigation needs centralised logging and sane sidecar design.

  • Ship logs: run a node-level agent (Fluent Bit, Vector or the Grafana Alloy agent) that tags records with container_name, so queries filter the same way -c does.
  • Structured output: emit JSON to stdout with a request ID so you can correlate the app with its proxy sidecar logs.
  • Rotation: tune kubelet containerLogMaxSize and containerLogMaxFiles so a chatty container cannot fill node disk.
  • Ephemeral debugging: when a distroless container offers no shell, attach one with kubectl debug -it my-pod --image=busybox --target=app.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: In CrashLoopBackOff always add --previous together with -c, because the current container instance has barely started and the real error lives in the previous one."
⚡ 60-Second Elevator Pitch Talking Points
  • A pod can hold several containers, so I select one with kubectl logs <pod> -c <container>, using jsonpath or describe to find the names.
  • I verify with --since, --tail and --timestamps, add --previous for crashes, and check events if the container never started.
  • I automate this by shipping stdout to a central log stack labelled by container name and by setting a default-container annotation on sidecar-injected pods.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Forgetting --previous on a crash-looping container The live container often has no useful output yet, so you miss the stack trace that explains the restart.
  2. Assuming deploy/my-app shows every replica kubectl picks a single pod from the workload; use a label selector or central logging for all replicas.
  3. Looking for file-based logs with kubectl logs Only stdout and stderr are captured; an app writing to a file inside the container produces empty output.
  4. Dumping full unbounded logs Without --tail or --since a busy container returns huge output, slows the API server path and hides the relevant window.
Advertisement
📥 FREE DOWNLOAD · 101-PAGE COMPANION HANDBOOK
Studying for Kubernetes & SRE Technical Rounds?
Download the complete 100-question PDF field guide covering all 11 core modules with offline diagnostic runbooks.
📥 Download PDF (Free) Read Online Guide →
Want more Kubernetes scenarios?
Explore our complete collection of scenario-based Kubernetes interview runbooks.
Browse All Kubernetes Questions →