Using kubectl run
to Set Environment Variables for a Container
In Kubernetes, the kubectl run
command is a convenient way to quickly create a deployment or a pod with a single command. One of the useful features of kubectl run
is the ability to set environment variables for the container(s) within the created pod.
Setting Environment Variables with kubectl run
To set environment variables for a container using kubectl run
, you can use the --env
flag followed by the key-value pair of the environment variable. Here's the basic syntax:
kubectl run <pod-name> --image=<image-name> --env="<key>=<value>"
For example, let's say you want to create a pod named my-app
using the nginx:latest
image, and set the APP_ENV
environment variable to production
. You can use the following command:
kubectl run my-app --image=nginx:latest --env="APP_ENV=production"
This will create a pod with the nginx:latest
image, and the APP_ENV
environment variable will be set to production
for the container.
You can also set multiple environment variables by repeating the --env
flag:
kubectl run my-app --image=nginx:latest --env="APP_ENV=production" --env="LOG_LEVEL=info"
This will set both the APP_ENV
and LOG_LEVEL
environment variables for the container.
Using Environment Variables in Kubernetes Manifests
While kubectl run
is a convenient way to quickly create a pod with environment variables, in a production environment, you'll typically want to use Kubernetes manifests (YAML files) to define your deployments, services, and other resources. In this case, you can define environment variables in the container specification of your Kubernetes manifest.
Here's an example Kubernetes deployment manifest that sets the APP_ENV
and LOG_LEVEL
environment variables:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: nginx:latest
env:
- name: APP_ENV
value: production
- name: LOG_LEVEL
value: info
In this example, the environment variables are defined in the env
section of the container specification. This approach allows you to manage your Kubernetes resources more effectively, as you can version control the manifest file and apply it to your cluster using kubectl apply -f <manifest-file.yaml>
.
Visualizing the Kubernetes Deployment Workflow
Here's a Mermaid diagram that illustrates the workflow of creating a Kubernetes deployment with environment variables:
This diagram shows the steps involved in creating a Kubernetes deployment with environment variables, from the developer writing the manifest to the final deployment of the container with the specified environment variables.
In summary, the kubectl run
command provides a convenient way to quickly create a pod with environment variables, while using Kubernetes manifests allows for more robust and maintainable configuration of your applications in a production environment.