Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 78 ยท Configuration and Secrets

Environment Variables and the Downward API

Set container environment variables in Kubernetes with env, envFrom and valueFrom, expose pod metadata with the Downward API, and override command and args.

Almost every container reads part of its configuration from environment variables: a database host, a log level, a feature flag. Kubernetes gives you several ways to fill them. You can write a value directly, copy it from a ConfigMap or Secret, or ask the cluster about the pod itself, such as its name, its IP address or its memory limit. That last trick is called the Downward API, because information flows "down" from the pod object into the container.

This lesson covers the env and envFrom fields, valueFrom references, the Downward API (as environment variables and as files), and how command and args relate to Docker's ENTRYPOINT and CMD. It builds on ConfigMaps and Secrets. The cluster itself cannot run on this site, so manifests are read-only; the runnable examples are Python stand-ins that imitate how the kubelet builds the environment of a container.

Four sources for one variable

Literal A fixed value written in the manifest.
ConfigMap A key copied from a ConfigMap.
Secret A key copied from a Secret.
Downward API Facts about the pod itself.

All four end up as plain strings in the container's environment.

1 / 2

Literal values with env

The simplest form is a list of name and value pairs under the container:

YAML
containers:
  - name: web
    image: example/web:1.4
    env:
      - name: LOG_LEVEL
        value: "info"
      - name: PORT
        value: "8080"

Values must be strings. Write "8080" in quotes; an unquoted 8080 or true is parsed by YAML as a number or boolean and the API server rejects it. This is one of the most common first-day mistakes (see YAML and manifests).

A value can refer to variables defined earlier in the same list using $(NAME):

YAML
env:
  - name: DB_HOST
    value: "postgres.shop.svc"
  - name: DB_URL
    value: "postgres://$(DB_HOST):5432/shop"

Two rules matter. The reference only sees variables defined above it, so order matters. And if the name cannot be resolved, the text is left as written, $(DB_HOST) and all, with no error. To write a literal $(NAME), double the dollar sign: $$(NAME).

Values from ConfigMaps and Secrets

Use valueFrom to pull a single key:

YAML
env:
  - name: LOG_LEVEL
    valueFrom:
      configMapKeyRef:
        name: web-config
        key: log-level
  - name: DB_PASSWORD
    valueFrom:
      secretKeyRef:
        name: db-credentials
        key: password
        optional: false

By default the reference is required: if the ConfigMap, the Secret or the key does not exist, the container cannot start and the pod shows CreateContainerConfigError. Setting optional: true lets the pod start without the variable instead. Treat optional with care, because a silently missing password is harder to debug than a loud failure.

To import every key of a ConfigMap or Secret, use envFrom:

YAML
envFrom:
  - configMapRef:
      name: web-config
  - secretRef:
      name: db-credentials
    prefix: DB_

A prefix is prepended to each key, which avoids collisions. Keys that are not valid environment variable names (for instance my-key.json contains characters the shell cannot use) are skipped, and the kubelet records an event instead of failing. If two sources define the same name, the one listed last wins. And a variable in env always beats one from envFrom.

Simulating the resolver

The next stand-in is not Kubernetes code, but it follows the same rules: envFrom first (later sources override earlier ones, with prefixes), then env in order with $(VAR) expansion, and required references that fail loudly.

Python An environment resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run fails because the token key does not exist, exactly like a real pod stuck in CreateContainerConfigError. After marking the reference optional the container starts, and you can check each rule in the output: LOG_LEVEL is info, DB_URL is expanded, BAD keeps its literal text and ESCAPED prints $(DB_HOST).

The Downward API

Containers often need to know things only the cluster knows: "which pod am I?", "what IP did I get?", "how much memory may I use?". Hard-coding them is impossible, because they are different for every replica. The Downward API exposes them without giving the container any access to the API server.

Pod fields use fieldRef:

YAML
env:
  - name: POD_NAME
    valueFrom:
      fieldRef:
        fieldPath: metadata.name
  - name: POD_NAMESPACE
    valueFrom:
      fieldRef:
        fieldPath: metadata.namespace
  - name: POD_IP
    valueFrom:
      fieldRef:
        fieldPath: status.podIP
  - name: NODE_NAME
    valueFrom:
      fieldRef:
        fieldPath: spec.nodeName
  - name: APP_VERSION
    valueFrom:
      fieldRef:
        fieldPath: "metadata.labels['app.kubernetes.io/version']"

Other useful paths as environment variables include metadata.uid, spec.serviceAccountName, status.hostIP and metadata.annotations['key']. Note the quoting for labels and annotations: the key goes inside square brackets and single quotes.

Container resources use resourceFieldRef, with an optional divisor that sets the unit:

YAML
env:
  - name: MEMORY_LIMIT_MIB
    valueFrom:
      resourceFieldRef:
        containerName: web
        resource: limits.memory
        divisor: 1Mi
  - name: CPU_REQUEST_MILLI
    valueFrom:
      resourceFieldRef:
        resource: requests.cpu
        divisor: 1m

This is how a JVM or a Go program can size its heap or its worker pool from the limit in the manifest (resource requests and limits). If a limit is not set, the value falls back to the node's allocatable amount, which is rarely what you want, so set the limit.

As files: the downwardAPI volume

Environment variables are frozen at start. When you need a pod's labels or annotations to stay current, mount them as files instead; the kubelet rewrites the files when the metadata changes. Whole metadata.labels and metadata.annotations are only available this way:

YAML
volumes:
  - name: podinfo
    downwardAPI:
      items:
        - path: labels
          fieldRef:
            fieldPath: metadata.labels
        - path: cpu_limit
          resourceFieldRef:
            containerName: web
            resource: limits.cpu
            divisor: 1m

The labels file then contains lines such as app="web". More on volumes in the next chapter.

Python Downward API: fields and divisors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A CPU limit of 500m with the default divisor of 1 becomes 1, because values are rounded up to whole units. That is why divisor: 1m exists: ask for millicores and you get 500.

command and args versus ENTRYPOINT and CMD

Docker images define a default program with ENTRYPOINT and default arguments with CMD (see CMD and ENTRYPOINT). In a pod spec, two fields override them, and the names are easy to mix up:

Pod field Replaces Meaning
command ENTRYPOINT The executable to run
args CMD Arguments passed to it

The combinations follow simple rules:

You set Result
nothing image ENTRYPOINT + image CMD
only args image ENTRYPOINT + your args
only command your command alone (the image CMD is ignored)
both your command + your args
YAML
containers:
  - name: migrate
    image: example/web:1.4
    command: ["php", "artisan"]
    args: ["migrate", "--force"]

Environment variables defined with env can be used inside command and args with the same $(NAME) syntax, which is handy because there is no shell by default, so $NAME is not expanded. To use shell features, run a shell explicitly: command: ["sh", "-c", "echo $POD_NAME"].

Python What actually runs: command and args

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the third line: setting only command drops the image's --port 80 entirely. This surprises people who override the entrypoint and then wonder where their default arguments went.

Service environment variables

Kubernetes also injects variables for every Service that existed in the namespace when the pod started: for a Service named redis-cache you get REDIS_CACHE_SERVICE_HOST and REDIS_CACHE_SERVICE_PORT and a few Docker-link style names. This depends on creation order (the Service must exist first) and clutters the environment in large namespaces, so prefer DNS names. You can turn the feature off per pod with enableServiceLinks: false.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A container defines env DB_URL with the value postgres://$(DB_HOST)/shop, but DB_HOST is defined further down the list. What happens?

    References only see variables defined above them in the same list. An unresolved reference is left unchanged and no error is raised.
  2. 2. A variable is set both in env and in an envFrom ConfigMap. Which value does the container get?

    Variables in env take precedence over those imported with envFrom. Among several envFrom sources, the last one wins.
  3. 3. A pod uses resourceFieldRef for limits.cpu of 500m without a divisor. What does the container see?

    The default divisor is 1 and the result is rounded up to a whole unit, so 500m becomes 1. Use divisor 1m to get 500.
  4. 4. An image has ENTRYPOINT ["python", "app.py"] and CMD ["--port", "80"]. The pod sets only command to ["python", "worker.py"]. What runs?

    When command is set and args is not, the image CMD is ignored, so only the command you gave runs.
  5. 5. Why mount pod labels with a downwardAPI volume instead of an environment variable?

    Environment variables are built once when the container starts. Downward API files are refreshed by the kubelet, and whole labels or annotations are only available through the volume.

Summary

  • env sets variables from literals (always strings), ConfigMap or Secret keys, or the Downward API; $(NAME) expands earlier variables and $$(NAME) escapes it.
  • envFrom imports whole ConfigMaps or Secrets, optionally with a prefix; env wins over envFrom, and later sources win over earlier ones.
  • Required references that cannot be resolved cause CreateContainerConfigError; optional: true skips them.
  • fieldRef exposes pod metadata and status, resourceFieldRef exposes requests and limits with a divisor.
  • Environment variables are fixed at container start; downward API volumes stay current.
  • command replaces ENTRYPOINT and args replaces CMD; setting only command discards the image CMD.

Next: Volumes