如何访问容器内的Kubernetes集群环境变量?



例如,我在公共云集群中运行Pod。Pod有一个运行应用程序的主容器。集群有一个名为ABC的环境变量。在主容器中,我希望访问环境变量ABC。最好的方法是什么?

非常简单的选项

apiVersion: v1
kind: Pod
metadata:
name: envar-demo
labels:
purpose: demonstrate-envars
spec:
containers:
- name: envar-demo-container
image: gcr.io/google-samples/node-hello:1.0
env:
- name: DEMO_GREETING
value: "Hello from the environment"
- name: DEMO_FAREWELL
value: "Such a sweet sorrow"

阅读更多:https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

选项1

如果变量不是很重要,你可以使用configmap来存储,配置映射将被注入到POD中,你的应用可以从操作系统访问这些变量。

阅读更多关于configmap的信息:https://kubernetes.io/docs/concepts/configuration/configmap/

示例configmap:

apiVersion: v1
kind: ConfigMap
metadata:
name: special-config
namespace: default
data:
SPECIAL_LEVEL: very
SPECIAL_TYPE: charm 

荚例子

apiVersion: v1
kind: Pod
metadata:
name: dapi-test-pod
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
command: [ "/bin/sh", "-c", "ls /etc/config/" ]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
# Provide the name of the ConfigMap containing the files you want
# to add to the container
name: special-config
restartPolicy: Never

你也可以根据需要注入带有变量列表的文件。

选项2:

如果变量很重要,也可以使用secret: https://kubernetes.io/docs/concepts/configuration/secret/

选项3:

如果你想使用最佳实践和选项,你可以使用目录使用Kubernetes来管理所有不同的微服务变量。

Vault: https://www.vaultproject.io/

示例:https://github.com/travelaudience/kubernetes-vault-example

它的键值对管理,并提供良好的安全选项。

最新更新