That's a great follow-up question! Labby here to help.
You should use environment variables in Kubernetes in the following scenarios:
-
Non-sensitive Configuration for Your Application:
- Externalizing configuration: When your application needs configuration values that might change between different environments (development, testing, production) but are not secret. For example, database connection URLs (if the credentials are handled by Secrets), API endpoints, feature flags, or logging levels.
- Application behavior: To modify the way your application runs without changing its code or rebuilding its image. Many containerized applications and frameworks are designed to be configured via environment variables.
-
Passing Dynamic Information to Containers:
- Pod information: You might want to inject information about the Pod itself, such as its name, namespace, or IP address, into a container. Kubernetes can do this automatically using Downward API.
- Service discovery (basic): While Services are the primary way for Pods to find each other, Kubernetes automatically injects environment variables with the IP address and port combinations for active Services into Pods within the same namespace. Your application can then use these variables to connect to other services.
-
For Simple, Stateless Configuration:
- When the configuration is relatively simple and doesn't require complex data structures or files. For example, setting a
DEBUG_MODE=trueflag.
- When the configuration is relatively simple and doesn't require complex data structures or files. For example, setting a
When NOT to use environment variables (or use with caution):
- Sensitive Data: Do NOT use plain environment variables for sensitive data like passwords, API keys, or private keys. These can be easily exposed through
kubectl describe pod, logs, orexecinto the container. For sensitive data, you should use Kubernetes Secrets, which are designed for this purpose. Secrets can then be mounted as files or injected as environment variables more securely. - Large or Complex Configuration: For very large configuration files (like XML, YAML, or JSON configurations) or configurations that change frequently, ConfigMaps are generally a better choice. ConfigMaps can be mounted as files into your containers, making them easier to manage and update.
In the current step, we're using an environment variable in the my-sidecar container to simply print Hello from the sidecar!. This is a good example of using an echo command which takes parameters that could also come from an environment variable. While this specific example hardcodes the message, it demonstrates where an environment variable could fit in a similar command block.
Does this distinction make sense for when to choose environment variables versus ConfigMaps or Secrets?