1. 程式人生 > >Kubernetes 1.5 實踐 如何給pod中的容器設定環境變數

Kubernetes 1.5 實踐 如何給pod中的容器設定環境變數

Kubernetes 1.5 給POD設定變數

When you create a Pod, you can set environment variables for the containers that run in the Pod. To set environment variables, include the env field in the configuration file.
在建立pod時,你可以為執行在pod中的容器設定環境變數。當我們需要設定變數時,我們只需要在配置檔案中(yaml)中加入env選項。

In this exercise, you create a Pod that runs one container. The configuration file for the Pod defines an environment variable with name DEMO_GREETING and value “Hello from the environment”. Here is the configuration file for the Pod:
在這個練習中,你將建立一個運行了一個容器的pod。在配置檔案中為pod定義的的一個環境變數名為 DEMO_GREETING,值為 “Hello from the environment”。這個pod的配置檔案envars.yaml如下:

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"

Create a Pod based on the YAML configuration file:
通過YAML配置檔案建立Pod:

kubectl create -f http://k8s.io/docs/tasks/configure-pod-container/envars.yaml

List the running Pods:
檢視正在執行的Pods

kubectl get pods -l purpose=demonstrate-envars

The output is similar to this:
輸出內容如下:

     NAME            READY     STATUS    RESTARTS   AGE
     envar-demo      1/1       Running   0
9s

Get a shell to the container running in your Pod:
連線到Pod中的容器:

kubectl exec -it envar-demo -- /bin/bash

In your shell, run the printenv command to list the environment variables.
在這個shell中,執行命令printenv命令檢視環境變數。

root@envar-demo:/# printenv

The output is similar to this:
輸出內容如下:

     NODE_VERSION=4.4.2
     EXAMPLE_SERVICE_PORT_8080_TCP_ADDR=10.3.245.237
     HOSTNAME=envar-demo
     ...
     DEMO_GREETING=Hello from the environment

To exit the shell, enter exit.
執行命令exit退出。