DEV Community

Cover image for #053 Kubernetes - Environment Variables
Omar
Omar

Posted on

#053 Kubernetes - Environment Variables

Introduction

intro

this is part 53 from the journey it's a long journey(360 day) so go please check previous parts , and if you need to walk in the journey with me please make sure to follow because I may post more than once in 1 Day but surely I will post daily at least one 😍.

And I will cover lot of tools as we move on.


Environment Variables

if we remember the example of voting app we have something in the yml file > spec called env , it's our environment variables it's same as docker where you can pass variables between container in case of docker and Pods in case of Kubernetes.

# db-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: db
  name: db
spec:
  replicas: 1
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
      - image: postgres:9.4
        name: postgres
        env:
        - name: POSTGRES_USER
          value: postgres
        - name: POSTGRES_PASSWORD
          value: postgres
        ports:
        - containerPort: 5432
          name: postgres
        volumeMounts:
        - mountPath: /var/lib/postgresql/data
          name: db-data
      volumes:
      - name: db-data
        emptyDir: {} 
Enter fullscreen mode Exit fullscreen mode

this is the old file from voting app , if we just focus on this part

 env:
        - name: POSTGRES_USER
          value: postgres
        - name: POSTGRES_PASSWORD
          value: postgres
Enter fullscreen mode Exit fullscreen mode

we can see that we are passing the username and the password as variables so we didn't hard coded inside our code.
but wait we have now 2 variables one in docker and one in Kubernetes with same env names ?
Kubernetes will override your environment variables in the docker file.
example let's say that we specify an environment variable inside of docker

ENV DBURL mongodb://localhost:27017/OrdersDB
Enter fullscreen mode Exit fullscreen mode

and inside our Kubernetes config we override it

env:
  - name: DBURL
    value: mongodb://mongo:80/OdersDB
Enter fullscreen mode Exit fullscreen mode

mongo is the name of our service in this case and 80 is the port of the service.

we can control our environment variables , in big projects we have lot of environment variables so it's very hard to manage them in this way , also maybe some of them are secretes like tokens.

Top comments (0)