在Kubernetes中,是否可以从容器内部获取容器名称?

10

假设我有以下的Pod规范。

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  # Unique key of the Deployment instance
  name: deployment-example
spec:
  # 3 Pods should exist at all times.
  replicas: 3
  template:
    metadata:
      labels:
        # Apply this label to pods and default
        # the Deployment label selector to this value
        app: nginx
    spec:
      containers:
      - name: nginx
        # Run this image
        image: nginx:1.10

在这里,容器的名称是nginx。是否有一种方法可以从正在运行的容器中获取“nginx”字符串?
我的意思是,一旦我使用类似于执行以下命令进入容器:
kubectl exec -it <pod-name> -c nginx bash

有没有编程的方法来获取Pod规范中给定容器名称的方式?
注意,这不一定是在 docker ps 中打印的 Docker 容器名称。Kubernetes 为生成的 Docker 容器组合了一个较长的名称。

向下API在这方面看起来很有前途。然而,在{{code1:向下API的功能}}部分中没有提到{{code2:容器名称}}。

3个回答

9

容器名称无法通过向下API获得。您可以使用YAML锚点和别名(引用)。不幸的是,它们没有作用域,因此您必须为锚点想出唯一的名称 - 它们不会出现在解析的文档中,因此名称无关紧要。

Subsequent occurrences of a previously serialized node are presented as alias nodes. The first occurrence of the node must be marked by an anchor to allow subsequent occurrences to be presented as alias nodes.

An alias node is denoted by the “*” indicator. The alias refers to the most recent preceding node having the same anchor. It is an error for an alias node to use an anchor that does not previously occur in the document. It is not an error to specify an anchor that is not used by any alias node.

First occurrence: &anchor Foo
Second occurrence: *anchor
Override anchor: &anchor Bar
Reuse anchor: *anchor
这里是一个完整的工作示例:
apiVersion: v1
kind: Pod
metadata:
  name: reftest
spec:
  containers:
  - name: &container1name first
    image: nginx:1.10
    env:
    - name: MY_CONTAINER_NAME
      value: *container1name
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name
  - name: &container2name second
    image: nginx:1.10
    env:
    - name: MY_CONTAINER_NAME
      value: *container2name
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name

1

不确定如何在部署中获取容器名称。

对于部署名称,在OpenShift中,适用于部署配置(因此可能也适用于Kubernetes部署),一种方法是获取HOSTNAME环境变量的值,该值将采用以下形式:<deployment-name>-<deployment-number>-<random-string>

从倒数第二个-开始删除,并且前导组件即为部署名称。

这可能需要进行大量操作,但可以通过基于该部署名称查询REST API以获取部署资源对象来推断容器名称。

您具体需要容器名称做什么?如果知道您需要它做什么,可能会提供其他选项。


我想把它放到我的提示符中。我需要类似于以下内容的东西:root@$HOSTNAME : $CONTAINER_NAME >$ 在Kubernetes中,$HOSTNAME变成PodName。 - Hakan Baba

0

使用容器主机名,然后剪掉生成的组件怎么样?

$ kubectl exec alpine-tools-645f786645-vfp82 hostname | cut -d- -f1,2
alpine-tools

虽然这很大程度上取决于您如何命名Pods/容器..

$ kubectl exec -it alpine-tools-645f786645-vfp82 /bin/sh
/ # hostname 
alpine-tools-645f786645-vfp82
/ # hostname | cut -d- -f1,2
alpine-tools

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接