使用kubectl获取pod日志小技巧

本文介绍了如何使用kubectl命令查看Kubernetes(K8S)集群中Pod的日志,包括获取单个Pod、同一Deployment下所有副本的日志,以及通过不同参数设置如时间范围、行数等筛选日志。示例中详细展示了如何操作,并提供了官方命令解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1. 前言

2. kubectl logs

3. 附官方命令解释


1. 前言

如何查看k8s中pod的console控制台日志?即类似于docker logs查看容器日志一样;可以使用 kubectl 命令,查看K8S中 Pod的日志。 在这里,将通过kubectl获取 Pod 的日志,包括当前运行、同一deployment下所有副本的日志。

2. kubectl logs

2.1 创建示例

创建nginx deployment,副本为2

 $ kubectl create deployment my-dep --image=nginx --replicas=2
 $ kubectl get pod 
NAME                      READY   STATUS    RESTARTS   AGE
my-dep-5b7868d854-8d5kf   1/1     Running   0          28m
my-dep-5b7868d854-q6lj7   1/1     Running   0          21m

2.2 获取单个pod日志

语法: kubectl logs <pod>

# 示例
$ kubectl logs my-dep-5b7868d854-8d5kf 
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/07/26 01:18:56 [notice] 1#1: using the "epoll" event method

2.3 获取同一deployment下多个副本pod的日志

语法: kubectl logs -l <key>=<value>

# 示例
# 获取pod labels 
$ kubectl get pod --show-labels
NAME                      READY   STATUS    RESTARTS   AGE   LABELS
my-dep-5b7868d854-8d5kf   1/1     Running   0          33m   app=my-dep,pod-template-hash=5b7868d854
my-dep-5b7868d854-q6lj7   1/1     Running   0          26m   app=my-dep,pod-template-hash=5b7868d854

# 获取多个Pod日志
$ kubectl logs -l app=my-dep
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/07/26 01:18:56 [notice] 1#1: using the "epoll" event method
2022/07/26 01:18:56 [notice] 1#1: nginx/1.23.1
2022/07/26 01:18:56 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/07/26 01:18:56 [notice] 1#1: OS: Linux 4.15.0-122-generic
2022/07/26 01:18:56 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/07/26 01:18:56 [notice] 1#1: start worker processes
2022/07/26 01:18:56 [notice] 1#1: start worker process 31
2022/07/26 01:18:56 [notice] 1#1: start worker process 32
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/07/26 01:25:33 [notice] 1#1: using the "epoll" event method
2022/07/26 01:25:33 [notice] 1#1: nginx/1.23.1
2022/07/26 01:25:33 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/07/26 01:25:33 [notice] 1#1: OS: Linux 4.15.0-122-generic
2022/07/26 01:25:33 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/07/26 01:25:33 [notice] 1#1: start worker processes
2022/07/26 01:25:33 [notice] 1#1: start worker process 30
2022/07/26 01:25:33 [notice] 1#1: start worker process 31

2.4 获取pod最近xx行日志

语法:kubectl logs --tail=xx <pod>

# 获取pod最近5行日志
$ kubectl logs --tail=5 my-dep-5b7868d854-8d5kf 
2022/07/26 01:18:56 [notice] 1#1: OS: Linux 4.15.0-122-generic
2022/07/26 01:18:56 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/07/26 01:18:56 [notice] 1#1: start worker processes
2022/07/26 01:18:56 [notice] 1#1: start worker process 31
2022/07/26 01:18:56 [notice] 1#1: start worker process 32

2.5 获取最近一段时间的日志

语法:kubectl logs --since=1h/m <pod>

# 获取最近1分钟/小时的日志
$ kubectl logs my-dep-5b7868d854-8d5kf --since=1m
$ kubectl logs my-dep-5b7868d854-8d5kf --since=1h

/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/07/26 01:18:56 [notice] 1#1: using the "epoll" event method
2022/07/26 01:18:56 [notice] 1#1: nginx/1.23.1
2022/07/26 01:18:56 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/07/26 01:18:56 [notice] 1#1: OS: Linux 4.15.0-122-generic
2022/07/26 01:18:56 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/07/26 01:18:56 [notice] 1#1: start worker processes
2022/07/26 01:18:56 [notice] 1#1: start worker process 31
2022/07/26 01:18:56 [notice] 1#1: start worker process 32

2.6 kubectl logs --previous

获取上一个崩溃但还存在的pod的日志,说实在的,不是很懂,官方的解释是:--previous=false: If true, print the logs for the previous instance of the container in a pod if it exists. 意思是:上一个崩溃过,但还存在的实例的日志。暂无场景重现。略过

2.7 获取pod中指定或所有容器的日志

查看指定容器日志 语法:kubectl logs <pod> -c <contianer>

# 获取pod中容器名
$ kubectl get pods my-dep-5b7868d854-8d5kf -o jsonpath={.spec.containers[*].name}
nginx
# 获取指定容器日志
 kubectl logs my-dep-5b7868d854-8d5kf -c nginx

查看同一个Pod中所有容器日志 语法:kubectl logs <pod> --all-containers

$ kubectl logs my-dep-5b7868d854-8d5kf --all-containers 

2.8 持续获取Pod日志

语法:kubectl logs -f <pod>

$ kubectl logs -f my-dep-5b7868d854-8d5kf  

3. 附官方命令解释

kubectl logs --help

 -c, --container="": 容器名。
  -f, --follow[=false]: 指定是否持续输出日志。
      --interactive[=true]: 如果为true,当需要时提示用户进行输入。默认为true。
      --limit-bytes=0: 输出日志的最大字节数。默认无限制。
  -p, --previous[=false]: 如果为true,输出pod中曾经运行过,但目前已终止的容器的日志。
      --since=0: 仅返回相对时间范围,如5s、2m或3h,之内的日志。默认返回所有日志。只能同时使用since和since-time中的一种。
      --since-time="": 仅返回指定时间(RFC3339格式)之后的日志。默认返回所有日志。只能同时使用since和since-time中的一种。
      --tail=-1: 要显示的最新的日志条数。默认为-1,显示所有的日志。
      --timestamps[=false]: 在日志中包含时间戳。
      

觉得有用的点个关注和收藏吧~ 

<think>好的,用户现在想了解Pod容器的状态。之前他们已经询问过Kubernetes的lifecycle钩子,现在可能是在进一步学习Pod的相关知识。我需要先回顾一下KubernetesPod状态的基本概念,确保信息准确。 首先,用户可能已经知道PodKubernetes的最小部署单元,但需要更详细的状态信息。常见的状态包括Pending、Running、Succeeded、Failed等。需要解释每个状态的具体含义和可能的原因,比如Pending可能是因为调度问题,Failed可能是容器启动失败。 接下来,用户可能需要了解容器状态,比如Waiting、Running、Terminated。每个状态下的子状态和原因也很重要,比如CrashLoopBackOff说明容器反复崩溃。要结合之前提到的lifecycle钩子,可能状态变化与PreStop或PostStart的执行有关。 用户可能还关心如何排查状态异常。比如,使用kubectl describe和logs命令查看详细信息,检查资源配额、镜像拉取、探针配置等。需要给出具体的命令示例,方便用户操作。 另外,用户之前的问题涉及exec、HTTPGet、TCPSocket,可能在状态检查中也会用到这些探针,比如就绪探针失败会导致容器未就绪。需要将状态与探针联系起来,说明它们如何影响Pod的状态。 需要确保回答结构清晰,分点说明Pod容器的状态,可能的原因,以及排查方法。避免使用过多术语,保持解释简洁明了。同时,结合之前的回答,保持一致性,比如提到lifecycle钩子可能影响Terminated状态。 最后,检查是否有遗漏的重要状态,比如Init容器状态、就绪和存活探针的影响。确保覆盖用户可能遇到的问题场景,如镜像拉取失败、启动命令错误、资源不足等,并提供相应的解决方案建议。</think>### Kubernetes Pod 容器状态解析 PodKubernetes 的最小调度单元,其状态反映了容器生命周期的关键信息。以下是容器状态的完整说明体系: --- #### 一、Pod 全局状态(`kubectl get pods` 显示列) | 状态类型 | 触发条件 | 典型场景 | |-----------------|--------------------------------------------------------------------------|--------------------------------------------------------------------------| | **Pending** | 调度器未完成资源分配 | 节点资源不足、镜像下载中、亲和性规则冲突 | | **Running** | 至少一个容器处于运行状态 | 正常服务运行中 | | **Succeeded** | 所有容器执行完成且退出码为 0 | 批处理作业(Job/CronJob)正常结束 | | **Failed** | 至少一个容器非 0 退出 | 容器启动命令错误、OOMKilled、健康检查持续失败 | | **Unknown** | kubelet 与 API Server 通信中断 | 节点宕机、网络分区 | | **CrashLoopBackOff** | 容器反复崩溃(特殊错误状态) | 应用程序启动依赖缺失、配置错误 | --- #### 二、容器详细状态(通过 `kubectl describe pod` 查看) 每个容器会报告以下状态机: $$ \text{容器状态} \in \{ \text{Waiting, Running, Terminated} \} $$ ##### 1. **Waiting** 状态 $$ \text{Waiting} = \begin{cases} \text{ImagePullBackOff} & \text{镜像拉取失败} \\ \text{ErrImagePull} & \text{镜像地址错误/权限不足} \\ \text{CrashLoopBackOff} & \text{容器反复崩溃(间隔时间指数增长)} \\ \text{ContainerCreating} & \text{CNI 插件配置中/存储卷挂载中} \end{cases} $$ **诊断命令**: ```bash kubectl describe pod <pod-name> | grep -A 15 "Containers" kubectl logs <pod-name> --previous # 查看前一个容器日志 ``` ##### 2. **Running** 状态 - **就绪检查**:通过 `readinessProbe` 控制流量接入 ```yaml readinessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 10 # 启动后等待时间 periodSeconds: 5 # 检查间隔 ``` - **存活检查**:通过 `livenessProbe` 控制容器重启 ```yaml livenessProbe: exec: command: ["pgrep", "nginx"] ``` ##### 3. **Terminated** 状态 $$ \text{Exit Code} = \begin{cases} 0 & \text{正常退出} \\ 1-127 & \text{应用错误(如 Python 异常)} \\ 137 & \text{SIGKILL(通常因 OOMKilled)} \\ 143 & \text{SIGTERM(优雅终止)} \end{cases} $$ **查看终止原因**: ```bash kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[0].state.terminated}' ``` --- #### 三、状态关联关系 ```mermaid graph TD A[Pod 创建] --> B{Pending} B --> |调度成功| C[ContainerCreating] C --> |镜像拉取完成| D{启动容器} D --> |主进程启动| E[Running] E --> |探针失败| F[CrashLoopBackOff] E --> |正常退出| G[Succeeded] E --> |异常退出| H[Failed] D --> |启动命令错误| H ``` --- #### 四、高频故障排查场景 ##### 场景 1:`ImagePullBackOff` **排查步骤**: 1. 检查镜像标签是否存在 ```bash docker pull <image-name>:<tag> ``` 2. 验证镜像仓库权限 ```yaml # 查看 Secret 配置 kubectl get secret <regcred> -o yaml ``` ##### 场景 2:`CrashLoopBackOff` **排查步骤**: 1. 查看应用日志 ```bash kubectl logs <pod-name> --tail=50 ``` 2. 检查资源限制 ```yaml resources: limits: memory: "256Mi" cpu: "500m" ``` ##### 场景 3:`Pod 处于 Running 但服务不可用` **排查步骤**: 1. 验证端口映射 ```bash kubectl port-forward <pod-name> 8080:80 curl localhost:8080/health ``` 2. 检查网络策略 ```bash kubectl describe networkpolicy <policy-name> ``` --- #### 五、高级状态控制技巧 1. **自定义终止信号处理**: ```yaml lifecycle: preStop: exec: command: ["/bin/sh", "-c", "nginx -s quit; sleep 10"] terminationGracePeriodSeconds: 30 ``` 2. **Init 容器状态监控**: ```yaml initContainers: - name: db-migration image: alpine/sql:latest command: ['sh', '-c', 'until pg_isready -h db; do sleep 2; done'] ``` 3. **Ephemeral 容器调试**: ```bash kubectl debug <pod-name> -it --image=busybox --target=<container-name> ``` --- ### 状态监控最佳实践 1. **Prometheus 指标采集**: ```yaml annotations: prometheus.io/scrape: "true" prometheus.io/port: "9090" ``` 2. **事件流监控**: ```bash kubectl get events --sort-by=.metadata.creationTimestamp ``` 3. **自动化修复策略**: ```yaml apiVersion: batch/v1 kind: CronJob metadata: name: pod-cleaner spec: schedule: "*/5 * * * *" jobTemplate: spec: template: containers: - name: kubectl image: bitnami/kubectl command: ["kubectl", "delete", "pod", "--field-selector=status.phase=Failed"] ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值