BACK TO BLOG

kubectl logs: Retrieve the Right Evidence Before a Restart

kubectl logs retrieves the output a container has written to its standard output (stdout) and standard error (stderr) streams. During an incident, the hard part is choosing the instance that holds the failure. A healthy proxy can hide a crashing server, and a fresh container can have nothing to say about the process it replaced. We start with identity, preserve the available evidence, and keep retrieval separate from changes to the workload.

Start with the cluster, namespace, Pod, and container

Choose the Pod and container that ran the failing process, such as the model server, request proxy, or setup container. Keep the namespace with the Pod name so a same-named Pod elsewhere is not mistaken for the target.

Use explicit context and namespace flags to select the intended cluster, credentials, and namespace without relying on someone else's terminal defaults.

kubectl config current-context

ctx='production-eu'
ns='inference'

kubectl --context="$ctx" -n "$ns" get pods -l app=model-api -o wide

The -l app=model-api selector limits the list to Pods carrying that label. The context, namespace, label, Pod name, and container names here are examples. Substitute the intended workload's values. If a selector returns no Pods, that is a selection result, not evidence that the application produced no logs. If namespace-wide listing is denied but a Pod name is already known, named-Pod retrieval can still be permitted.

Select the failing replica from that list, then retrieve its identity and container names:

pod='model-api-7d9b8c6f5b-k2m4p'

kubectl --context="$ctx" -n "$ns" get pod "$pod" \
  -o custom-columns='POD:.metadata.name,UID:.metadata.uid,NODE:.spec.nodeName'

kubectl --context="$ctx" -n "$ns" get pod "$pod" \
  -o jsonpath='{.spec.containers[*].name}{"\n"}{.spec.initContainers[*].name}{"\n"}{.spec.ephemeralContainers[*].name}{"\n"}'

The three lines list regular containers, init containers, and any ephemeral containers. For setup failures, use the relevant regular init container; native sidecars also appear under initContainers and can keep running with the application. Use an ephemeral container's name to retrieve output from its temporary troubleshooting session. Blank lines mean that group is absent.

Record the Pod UID and node alongside the evidence. A replacement Pod can reuse a name while having a different UID, particularly for StatefulSet replicas with stable names. A replacement is a different evidence source. Kubernetes' Pod lifecycle rules distinguish replacement Pods from container restarts inside an existing Pod.

Set the container explicitly, even when an unqualified command appears to work:

Logs may contain credentials or customer data. Use a private terminal, avoid screen sharing, and keep raw output out of tickets and chat. The private-file capture below avoids printing the log body to the terminal.

container='server'

kubectl --context="$ctx" -n "$ns" logs "$pod" -c "$container" \
  --tail=200 --since=15m --timestamps=true

Omitting -c can select the annotated default container or the first regular container. Successful output does not establish that the failing container was selected. The upstream container selection code also explains why --all-containers=true widens the request to setup and troubleshooting containers.

Understand current and previous container logs

A container can restart without the Pod being replaced. Ordinary kubectl logs prefers its running instance, but can return the latest terminated attempt while the container is waiting or before a new run starts. Adding --previous, or -p, requests the last terminated instance recorded for that container inside the same Pod. During a restart wait, both commands can therefore refer to the same last termination. The kubelet's instance selection logic defines this distinction.

For a crash loop, preserve the previous instance promptly:

kubectl --context="$ctx" -n "$ns" logs "$pod" -c "$container" \
  --previous --tail=300 --timestamps=true

The previous-instance command omits --since=15m. A recent-time filter can exclude a crash that happened earlier, even when its log remains available.

CrashLoopBackOff means Kubernetes is delaying another restart after repeated failures. It is not the application's error message. A previous-instance startup failure can explain the crash while the current instance contains only initialization output.

Pod status gives the restart count and the preceding termination reason and time:

kubectl --context="$ctx" -n "$ns" get pod "$pod" \
  -o jsonpath='{range .status.containerStatuses[*]}{.name}{"\trestarts="}{.restartCount}{"\tlastReason="}{.lastState.terminated.reason}{"\tlastFinished="}{.lastState.terminated.finishedAt}{"\n"}{end}'

For an init-container failure, use its name with -c and read .status.initContainerStatuses instead. A completed init container's latest execution is available through the ordinary command; completion alone is no reason to add --previous.

A Deployment rollout can replace whole Pods. Distinguish those replacements from container restarts:

Situation Evidence to request
Running container with an application error Current instance of that exact container
Same container restarted after a failure Last termination, then ordinary logs; they can overlap during a restart wait
Container terminated and has not restarted Ordinary logs for its latest execution
Deployment replaced an old Pod Old Pod by name while it exists, or retained centralized logs
Container never started Pod status and events; application output may not exist

--previous is neither Deployment history nor a selector for an arbitrary restart number. Another restart can change which terminated instance it addresses. Capture restart status around retrieval and preserve that uncertainty if the count changes.

A restart keeps container attempts inside one Pod; replacement separates their Pod identities.

With a new run active, ordinary logs and --previous address different attempts within one Pod. A replacement Pod starts a separate history.

Bound the history and the live follow session

The useful controls answer different questions:

Flag What it bounds
--tail=200 Recent lines in the available log file
--since=15m Records newer than a relative time
--since-time=2026-11-18T09:00:00Z Records after an absolute timestamp, including its time-zone offset
--limit-bytes=1048576 Bytes returned per log request
--follow, or -f Keeps receiving new output; it does not impose a duration

Use either --since or --since-time, never both. Absolute timestamps use RFC3339 format; Z denotes UTC. Combined tail and time filters can exclude different parts of the incident. Byte limits can cut a record mid-line and can return slightly more or less than the requested size. These controls come from the log API options; they cannot restore records that are no longer available.

For a bounded live session on Linux with GNU Coreutils, wrap the command in timeout:

follow_status=0
timeout --signal=INT --kill-after=5s 30s \
  kubectl --context="$ctx" -n "$ns" logs "$pod" -c "$container" \
  --follow --tail=100 --since=5m --timestamps=true || follow_status=$?
printf 'follow exit status: %s\n' "$follow_status"

This starts with a bounded history, follows new output, sends an interrupt after 30 seconds, and allows another five seconds before forced termination. --tail=100 does not cap the total lines received while following. A byte limit adds a per-stream size bound, with the qualifications above.

GNU timeout returns 124 when its deadline triggers, or 137 if forced killing is required. An earlier completion returns the command's status. These are timeout exit semantics, not proof that the workload succeeded or failed. In an interactive session without GNU timeout, Ctrl+C ends retrieval, but does not provide an automatic deadline.

An ended follow stream is not a subscription to future replacement Pods or container instances. Select the intended instance again after a restart. Leave --ignore-errors off during evidence collection so retrieval failures remain visible.

Widen to multiple replicas only when the question requires it

A label selector retrieves logs from matching Pods. --all-containers=true widens the container scope; --prefix=true preserves the Pod and container source on each line:

kubectl --context="$ctx" -n "$ns" logs -l app=model-api \
  --all-containers=true --prefix=true \
  --tail=100 --since=5m --timestamps=true

Set --tail explicitly. Its default is all available lines without a selector and only ten lines with a selector. Multi-stream output is not a globally time-sorted incident timeline.

For live multi-stream retrieval, the default concurrency limit is five streams. Choose a small, deliberate --max-log-requests value if more are required. Limits apply to individual requests, so aggregate output grows with the number of selected containers. The kubectl command reference documents these defaults.

logs deployment/model-api ordinarily chooses one Pod. --all-pods=true requests all Pods selected through that resource. An explicit Pod remains the clearer choice when preserving evidence from a particular failed replica. Label-based follow also starts from the matched set, rather than continuously discovering every future Pod.

Use the permissions each request actually needs

In role-based access control (RBAC) policies, Pod metadata and Pod logs are separate resources: log retrieval uses get on the pods/log subresource in the core API group, represented by an empty string in an RBAC policy. A namespace-scoped Role can grant this without granting workload changes or access to Secrets.

In our cluster operations, we act only on access the customer explicitly grants, with role-based permissions for each person. Reading evidence does not require blanket administrator access.

Operation Resource permission
Ordinary named-Pod kubectl logs, including -f and --previous get on pods, plus get on pods/log
Discover Pods or retrieve logs using -l list on pods, plus get on pods/log for logs
logs deployment/model-api get on deployments.apps, list on pods, and get on pods/log
Read the events used below list on core events

The normal CLI retrieves the Pod before requesting its logs. Having pods/log access alone can therefore still produce a denial on pods. The upstream request construction code makes that distinction visible; Kubernetes' RBAC resource syntax defines pods/log separately.

Following an existing Pod's log uses a streaming GET. It does not, by itself, require watch on Pods. Controller shorthand can enter a Pod-watch path when its initial selection is empty; named-Pod retrieval avoids that discovery path. There is no reason to add blanket watch, exec, Secret-reading, or administrator permissions to tail an existing container.

These authorization queries expose the relevant grants for the selected identity and namespace:

kubectl --context="$ctx" -n "$ns" auth can-i get "pods/$pod"
kubectl --context="$ctx" -n "$ns" auth can-i get "pods/$pod" --subresource=log
kubectl --context="$ctx" -n "$ns" auth can-i list pods

yes concerns authorization, not log existence or node reachability. no exits nonzero. The query itself submits an authorization review, without changing the workload. A Forbidden response on the actual retrieval identifies the denied resource and verb. Keep that response for the access owner and request only the missing scope.

Use a supported client/server combination: Kubernetes maintains the 1.35, 1.36, and 1.37 release branches, and supports kubectl within one minor version of the API server. Mixed-version API servers narrow that range. These are the upstream supported releases and version-skew policy.

Separate missing evidence from a quiet application

An empty file, a denied request, and a lost log are different outcomes. Preserve stderr and the exit status alongside stdout.

Result Meaning and next evidence source
Empty output, exit 0 No matching records were returned. The selected instance may be quiet, filters may exclude its output, or the application may log to a file instead of stdout/stderr.
previous terminated container ... not found No previous instance is available for that container in this Pod. This is a failed request, not an empty successful log.
Pod NotFound Wrong context, namespace, or name, or the Pod has gone. Use the recorded UID to locate retained logs.
Invalid container name The selected Pod does not contain that name. Its container list is the relevant source.
Waiting to start, ImagePullBackOff, or ContainerCreating The application may never have run. Pod status and events describe image, setup, or mount failures.
Forbidden Authorization denied the request. Repeating it with different tail settings cannot fix access.
Backend timeout, connection error, or certificate error Retrieval could not reliably reach or authenticate the node-side log service. Empty stdout establishes nothing about application output.

For a container that never started, retrieve only the relevant status and events:

kubectl --context="$ctx" -n "$ns" get pod "$pod" \
  -o jsonpath='{.status.phase}{"\n"}{.status.conditions}{"\n"}{.status.initContainerStatuses}{"\n"}{.status.containerStatuses}{"\n"}'

if pod_uid=$(kubectl --context="$ctx" -n "$ns" get pod "$pod" \
  -o jsonpath='{.metadata.uid}'); then
  kubectl --context="$ctx" -n "$ns" get events \
    --field-selector="involvedObject.uid=$pod_uid" \
    --sort-by=.metadata.creationTimestamp
fi

Events describe lifecycle activity and can expire; they are not application log history. An event-list denial does not imply that log reading is also denied. Kubernetes' Pod debugging guidance separates startup and scheduling problems from failures inside a running application.

Rotation is a retention boundary

The kubelet rotates container log files. kubectl logs exposes only the latest file for the requested instance. --tail=-1 means all available lines in that file, not every rotated file. Neither a longer --since window nor --previous retrieves older rotations.

By default, the kubelet retains one terminated container and its logs after a restart; eviction removes the associated containers and logs. The upstream logging architecture defines those limits.

Only the latest local log file feeds terminal retrieval; a separate collector preserves historical records.

Terminal retrieval reaches the latest local file. Historical evidence needs a collector and retained store in place before the logs disappear.

For evidence beyond that boundary, use the centralized logging backend that already collected it, with the cluster, namespace, Pod UID, container, and time range. Collection and retention must precede the loss. Restricted node-level recovery is a separate operator workflow and cannot be assumed to recover deleted files.

Do not bypass Transport Layer Security (TLS) certificate verification to make a backend error disappear. It weakens the identity assurance of the log source. Route the retrieval failure to the cluster operator with the node and request details.

Preserve a private original and share a minimal copy

For file capture, create a private directory on approved local storage. This Bash example stores ordinary and previous-instance responses separately, limits each response to roughly one MiB (1,048,576 bytes), and keeps diagnostics out of the application log. The current filename labels the ordinary command's response; it does not prove a process is running.

umask 077
if ! evidence_dir=$(mktemp -d); then
  printf 'Private capture directory creation failed.\n' >&2
  exit 1
fi

current_status=0
kubectl --context="$ctx" -n "$ns" logs "$pod" -c "$container" \
  --tail=500 --timestamps=true --limit-bytes=1048576 \
  >"$evidence_dir/current.raw.log" \
  2>"$evidence_dir/current.stderr" || current_status=$?

previous_status=0
kubectl --context="$ctx" -n "$ns" logs "$pod" -c "$container" \
  --previous --tail=500 --timestamps=true --limit-bytes=1048576 \
  >"$evidence_dir/previous.raw.log" \
  2>"$evidence_dir/previous.stderr" || previous_status=$?

printf 'current=%s previous=%s\n' \
  "$current_status" "$previous_status" >"$evidence_dir/status.txt"

A nonzero status can accompany partial output. Zero-byte output from a denied or missing-instance request is not a clean bill of health. Retain capture times, Pod identity, container, instance, command filters, and restart counts with these files.

Raw logs and diagnostic files belong under the incident's access and retention policy. Avoid world-readable files, automatic uploads, and copying raw logs into AI tools. Passwords, access tokens, connection strings, and personal data are among the categories the Open Worldwide Application Security Project (OWASP) identifies as sensitive log data.

Share a derived copy containing only the fields needed to explain the failure. For structured logs, a schema-specific allowlist can retain an approved event code and timestamp while dropping headers, prompts, payloads, and free-text messages. A generic token regex cannot guarantee that secrets are removed. Preserve useful correlation identifiers only when their values are permitted for the receiving audience. An exposed credential still needs the organization's credential-rotation response.

Make the workload change a separate decision

Before a restart, rollout, or configuration change, the evidence should identify the cluster, Pod UID, container, instance, and time window. It should also say where retrieval failed or retention ended. Application output alone cannot establish GPU, storage, or network health; those signals belong in the broader inference failure diagnosis.

With our fully managed clusters, we design, deploy, and operate the cluster end to end. If ongoing cluster operations are taking time away from serving workloads, talk to an engineer about putting that responsibility with Aranya.