kubectl logs and exec
- Version
- 1.37
- Review
- Draft
Summary#
kubectl logs prints a container's standard output and error. --previous reads the terminated instance before the current one. kubectl exec runs a command in a running container and returns its exit status.
Syntax#
kubectl logs POD [-c CONTAINER] [--previous] [--tail=N] [-f]
kubectl logs deployment/NAME
kubectl exec POD [-c CONTAINER] -- COMMAND [ARG...]
kubectl exec -it POD -- sh
Example#
The container fails on its first start and succeeds on the second. An emptyDir volume remembers the first attempt.
(
set -eu
ns="ref-logs-$$"
kubectl create namespace "$ns" >/dev/null
trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null
kubectl apply -n "$ns" -f - >/dev/null <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
terminationGracePeriodSeconds: 1
containers:
- name: app
image: busybox:1.37
command:
- sh
- -c
- |
if [ ! -f /state/tried ]; then
touch /state/tried
echo "first start: failing"
exit 1
fi
echo "second start: ready"
touch /tmp/ready
exec sleep 3600
readinessProbe:
exec:
command: ["test", "-f", "/tmp/ready"]
periodSeconds: 1
volumeMounts:
- name: state
mountPath: /state
volumes:
- name: state
emptyDir: {}
EOF
kubectl wait -n "$ns" --for=condition=Ready pod/app --timeout=180s >/dev/null
echo "previous instance:"
kubectl logs -n "$ns" app -c app --previous
echo "current instance:"
kubectl logs -n "$ns" app -c app --tail=1
kubectl exec -n "$ns" app -c app -- ls /state
status=0
kubectl exec -n "$ns" app -c app -- sh -c 'exit 3' 2>/dev/null || status=$?
echo "exec exit status: $status"
)
Expected output#
previous instance:
first start: failing
current instance:
second start: ready
tried
exec exit status: 3
Common mistakes#
CrashLoopBackOff means that a container keeps exiting and the kubelet is waiting before it restarts it. Read the previous run with kubectl logs POD --previous, adding -c CONTAINER when the Pod has several containers.
Separate the command with --. kubectl 1.37 rejects the older form without it. exec also needs the program to exist in the image. For a minimal image without a shell, add an ephemeral container with kubectl debug instead.
Version applicability#
The commands target Kubernetes 1.37. kubectl is supported within one minor version, older or newer, of the API server.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0