kubernetes 容器内获取Pod信息(包括:宿主主机IP)

全栈工程师开发手册 (作者:栾鹏)
架构系列文章


kubernetes 自从1.7开始,可以在pod 的container 内获取pod的spec,metadata 等信息。

为啥可以获取

容器中进程启动顺序:先调度确定pod部署在哪个机器上,部署pod,部署container,启动进程。

所以在启动进程前,就已经有了pod的信息,所以可以获取,然后通过进程启动前设置环境变量的形式来实现。

可以传递的信息

先随便部署一个pod,通过

kubectl get pod  -n your-namespace -o yaml your-app

获取的pod信息为

apiVersion: v1
kind: Pod
metadata:
  annotations:
    cni.projectcalico.org/podIP: 172.16.162.2/32
  creationTimestamp: "2020-03-06T15:11:40Z"
  generateName: your-app-57846cfdbf-
  labels:
    app: your-app
    pod-template-hash: 57846cfdbf
  name: your-app-57846cfdbf-x6nj6
  namespace: your-namespace
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: your-app-57846cfdbf
    uid: 8b88c1f5-9cce-49bf-8b7d-7f90c67483af
  resourceVersion: "62526266"
  selfLink: /api/v1/namespaces/your-namespace/pods/your-app-57846cfdbf-x6nj6
  uid: e86bd373-25bb-4a2d-8a18-49ced8809771
spec:
  containers:
  - command:
    - python
    - server.py
    env:
    - name: user
      value: aaaaa
    - name: password
      value: bbbbb
    image: xxxxxxxxxxxxxxxxxx
    imagePullPolicy: Always
    livenessProbe:
      failureThreshold: 3
      httpGet:
        path: /
        port: 80
        scheme: HTTP
      initialDelaySeconds: 100
      periodSeconds: 300
      successThreshold: 1
      timeoutSeconds: 5
    name: your-app
    ports:
    - containerPort: 80
      protocol: TCP
    readinessProbe:
      failureThreshold: 3
      httpGet:
        path: /
        port: 80
        scheme: HTTP
      initialDelaySeconds: 15
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 5
    resources:
      limits:
        cpu: "5"
        memory: 5000Mi
      requests:
        cpu: 10m
        memory: 100Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /etc/localtime
      name: tz-config
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-sq77d
      readOnly: true
    workingDir: /app/
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  imagePullSecrets:
  - name: hubsecret
  nodeName: ch009022000050
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - hostPath:
      path: /usr/share/zoneinfo/Asia/Shanghai
      type: ""
    name: tz-config
  - name: default-token-sq77d
    secret:
      defaultMode: 420
      secretName: default-token-sq77d
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2020-03-06T15:11:41Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2020-03-09T02:43:51Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2020-03-09T02:43:51Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2020-03-06T15:11:40Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://59b535d6fe210f70b6172a68729d99d7af57489564754a2d97fb224034c2b437
    image: xxxxxxxxxxxxxxxxxx
    imageID: xxxxxxxxxxx-pipline@sha256:812e9d09f8fe8577b5f9c6aa212194c624eea5c7111261d9a8503026a29e6da7
    lastState:
      terminated:
        containerID: docker://a70c979c114ca0131ffeac04e0016c3a0dea9d266f98042e333e9048f3cfa92c
        exitCode: 1
        finishedAt: "2020-03-09T02:43:15Z"
        reason: OOMKilled
        startedAt: "2020-03-09T02:40:11Z"
    name: your-app
    ready: true
    restartCount: 2
    state:
      running:
        startedAt: "2020-03-09T02:43:30Z"
  hostIP: 9.22.0.50
  phase: Running
  podIP: 172.16.162.2
  qosClass: Burstable
  startTime: "2020-03-06T15:11:41Z"

这上面的信息都可以获取。并传给自定义环境变量

获取pod信息,传递给环境变量

具体方法可以通过env获取:

 env:
 - name: MY_NODE_NAME
   valueFrom:
     fieldRef:
       fieldPath: spec.nodeName
 - name: MY_POD_NAME
   valueFrom:
     fieldRef:
       fieldPath: metadata.name
 - name: MY_POD_NAMESPACE
   valueFrom:
     fieldRef:
       fieldPath: metadata.namespace
 - name: MY_POD_IP
   valueFrom:
     fieldRef:
       fieldPath: status.podIP
 - name: MY_POD_SERVICE_ACCOUNT
   valueFrom:
     fieldRef:
       fieldPath: spec.serviceAccountName

spec.nodeName : pod所在节点的IP、宿主主机IP

status.podIP :pod IP

metadata.namespace : pod 所在的namespace

注意:此示例中的字段是Pod字段。它们不是Pod中“容器”的字段。

更多参数:https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用kubernetes-client java获取pod容器内存与CPU使用率,可以按照以下步骤进行操作。 首先,你需要在Java项目中添加kubernetes-client的依赖,例如在pom.xml文件中添加以下代码: ```xml <dependencies> <dependency> <groupId>io.kubernetes</groupId> <artifactId>client-java</artifactId> <version>9.0.0</version> </dependency> </dependencies> ``` 接下来,你可以使用以下代码获取pod的相关信息: ```java import io.kubernetes.client.apis.CoreV1Api; import io.kubernetes.client.custom.Quantity; import io.kubernetes.client.models.V1Container; import io.kubernetes.client.models.V1ContainerStatus; import io.kubernetes.client.models.V1NamespaceList; import io.kubernetes.client.models.V1Pod; import io.kubernetes.client.models.V1PodList; import io.kubernetes.client.models.V1PodMetrics; import io.kubernetes.client.models.V1PodMetricsList; import io.kubernetes.client.util.Config; import java.util.Map; public class KubernetesClientExample { public static void main(String[] args) throws Exception { // 创建Kubernetes客户端 io.kubernetes.client.Configuration config = Config.defaultClientConfig(); io.kubernetes.client.apis.CoreV1Api api = new CoreV1Api(); // 获取pod列表 V1PodList podList = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null); for (V1Pod pod : podList.getItems()) { // 获取pod所属的命名空间和名称 String namespace = pod.getMetadata().getNamespace(); String name = pod.getMetadata().getName(); // 获取pod容器列表和相关状态信息 for (V1Container container : pod.getSpec().getContainers()) { String containerName = container.getName(); V1ContainerStatus containerStatus = pod.getStatus().getContainerStatuses().stream() .filter(status -> status.getName().equals(containerName)) .findFirst().orElse(null); if (containerStatus != null) { // 获取容器的CPU和内存使用率 Map<String, Quantity> usage = containerStatus.getUsage(); Quantity cpuUsage = usage.get("cpu"); Quantity memoryUsage = usage.get("memory"); System.out.println("Namespace: " + namespace + ", Pod: " + name + ", Container: " + containerName + ", CPU Usage: " + cpuUsage + ", Memory Usage: " + memoryUsage); } } } } } ``` 上述代码中,我们首先创建了Kubernetes的客户端,然后通过CoreV1Api实例来获取pod列表。对于每个pod,我们遍历其容器列表,并获取容器的名称以及相关状态信息。在状态信息中,我们可以找到容器的CPU和内存使用率,以及其他相关指标。 需要注意的是,这里获取的是当前时刻的使用率数据,如果你想要定时获取容器的使用率信息,可以使用定时任务等方法来实现。 这是一个简单的示例,你可以根据实际需求和项目结构进行相应的扩展和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾讯数据架构师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值