Application lifecycle management

rollingupdate_rollbacks

rollingupdate_rollbacks
# Rolling Updates and Rollbacks

Rollouts and version

kubectl rollout status deploy webapp
kubectl rollout history deploy webapp

Deployment stratefy:
----------------------->
1.Rolling Update --> its the default deployment strategy

RollingUpdateStrategy:  25% max unavailable, 25% max surge

in this unavailable means lets say the deployment set replicas as 4.
Whenever the rolling update happens the 25% pods are unavailable that means 1 pod is unavailable at a time.

rollback:
-------------->
kubectl rollout undo deploy webapp

rollingupdate_rollbackslabs

rollingupdate_rollbackslabs
root@controlplane:~# kubectl get all 
NAME                            READY   STATUS    RESTARTS   AGE
pod/frontend-7776cb7d57-9gd9n   1/1     Running   0          29s
pod/frontend-7776cb7d57-nfgrt   1/1     Running   0          29s
pod/frontend-7776cb7d57-t7gvg   1/1     Running   0          29s
pod/frontend-7776cb7d57-vr7zg   1/1     Running   0          29s

NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes       ClusterIP   10.96.0.1        <none>        443/TCP          116s
service/webapp-service   NodePort    10.104.185.173   <none>        8080:30080/TCP   29s

NAME                       READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/frontend   4/4     4            0           29s

NAME                                  DESIRED   CURRENT   READY   AGE
replicaset.apps/frontend-7776cb7d57   4         4         4       29s
root@controlplane:~# 


root@controlplane:~# ls -rtlh
total 8.0K
-rwxr-xr-x 1 root root 216 Sep 14 01:32 curl-test.sh
-rw-rw-rw- 1 root root 186 Sep 14 01:32 curl-pod.yaml
root@controlplane:~# 



root@controlplane:~# ./curl-test.sh 
Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

Hello, Application Version: v1 ; Color: blue OK

root@controlplane:~# 



root@controlplane:~# kubectl describe deploy frontend
Name:                   frontend
Namespace:              default
CreationTimestamp:      Mon, 20 Sep 2021 12:54:01 +0000
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               name=webapp
Replicas:               4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        20
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  name=webapp
  Containers:
   simple-webapp:
    Image:        kodekloud/webapp-color:v1
    Port:         8080/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   frontend-7776cb7d57 (4/4 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  5m50s  deployment-controller  Scaled up replica set frontend-7776cb7d57 to 4
root@controlplane:~# 


root@controlplane:~# kubectl describe deploy frontend | grep -i strategy
StrategyType:           RollingUpdate
RollingUpdateStrategy:  25% max unavailable, 25% max surge
root@controlplane:~# 

root@controlplane:~# kubectl edit deploy frontend
deployment/frontend edited
root@controlplane:~#


root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   3         3         3       8m25s
frontend-7c7fcfc8cb   2         2         0       10s
root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   3         3         3       8m28s
frontend-7c7fcfc8cb   2         2         2       13s
root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   3         3         3       8m33s
frontend-7c7fcfc8cb   2         2         2       18s
root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   1         1         1       8m47s
frontend-7c7fcfc8cb   4         4         2       32s
root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   1         1         1       9m5s
frontend-7c7fcfc8cb   4         4         4       50s
root@controlplane:~# kubectl get rs
NAME                  DESIRED   CURRENT   READY   AGE
frontend-7776cb7d57   0         0         0       9m21s
frontend-7c7fcfc8cb   4         4         4       66s
root@controlplane:~#


root@controlplane:~# ./curl-test.sh 
Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

Hello, Application Version: v2 ; Color: green OK

root@controlplane:~# 


root@controlplane:~# kubectl edit deploy frontend 
deployment.apps/frontend edited
root@controlplane:~# 


root@controlplane:~# kubectl edit deploy frontend 
deployment.apps/frontend edited
root@controlplane:~# 

root@controlplane:~# ./curl-test.sh 
Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

Hello, Application Version: v3 ; Color: red OK

root@controlplane:~# 

curl_test

curl_test
for i in {1..10}; do
   kubectl exec --namespace=kube-public curl -- sh -c 'test=`wget -qO- -T 2  http://webapp-service.default.svc.cluster.local:8080/info 2>&1` && echo "$test OK" || echo "Failed"';
   echo ""
done

configureapp

configureapp
Configuring Command and Arguments on applications
Configuring Environment Variables
Configuring Secrets

dockercommands

dockercommands
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker run ubuntu
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
37797d16b7bf        ubuntu              "bash"              14 seconds ago      Exited (0) 13 seconds ago                       amazing_sinoussi
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker run ubuntu sleep 100
...
...
...

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
d7cf7e1b851a        ubuntu              "sleep 100"         27 seconds ago      Up 26 seconds                           zen_poincare
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker build -t ubuntu-sleeper .
Sending build context to Docker daemon  14.34kB
Step 1/2 : FROM ubuntu
 ---> 1318b700e415
Step 2/2 : CMD ["sleep", "10"]
 ---> Running in fb7ee02bbaee
Removing intermediate container fb7ee02bbaee
 ---> a1b5b5b1a7f0
Successfully built a1b5b5b1a7f0
Successfully tagged ubuntu-sleeper:latest
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker run ubuntu-sleeper
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
f617feb39df1        ubuntu-sleeper      "sleep 10"          6 seconds ago       Up 6 seconds                            naughty_cannon
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 


for CMD --> Command line parameters gets replaced entirely.
for ENTRYPOINT --> Command line parameters gets appended.



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker build -t docker-sleeper-entry .
Sending build context to Docker daemon  15.36kB
Step 1/2 : FROM ubuntu
 ---> 1318b700e415
Step 2/2 : ENTRYPOINT [ "sleep" ]
 ---> Running in 4f01af5f85d2
Removing intermediate container 4f01af5f85d2
 ---> a0374708bc2d
Successfully built a0374708bc2d
Successfully tagged docker-sleeper-entry:latest
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker run docker-sleeper-entry 30

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE                  COMMAND             CREATED             STATUS              PORTS               NAMES
8bf99af8cc28        docker-sleeper-entry   "sleep 30"          5 seconds ago       Up 4 seconds                            practical_keller
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker build -t ubuntu-sleeper-entry-cmd .
Sending build context to Docker daemon   16.9kB
Step 1/3 : FROM ubuntu
 ---> 1318b700e415
Step 2/3 : ENTRYPOINT [ "sleep" ]
 ---> Using cache
 ---> a0374708bc2d
Step 3/3 : CMD ["5"]
 ---> Using cache
 ---> eb7d440ee852
Successfully built eb7d440ee852
Successfully tagged ubuntu-sleeper-entry-cmd:latest
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker run ubuntu-sleeper-entry-cmd
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ docker ps
CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS               NAMES
4ca3f97c129a        ubuntu-sleeper-entry-cmd   "sleep 5"           4 seconds ago       Up 4 seconds                            determined_bose
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

k8s_commands

k8s_commands
How to specify arguments in pod definition file

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: ubuntu-sleeper
  name: ubuntu-sleeper
spec:
  containers:
  - image: ubuntu-sleeper-entry-cmd
    name: ubuntu-sleeper
    command: ["sleep2.0"] # It overwrites the ENTRYPOINT in docker
    args: ["35"] # It overwrites the CMD field in docker

k8s_commandslabs

k8s_commandslabs
root@controlplane:~# kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
ubuntu-sleeper   1/1     Running   0          2m25s
root@controlplane:~# 

root@controlplane:~# cat ubuntu-sleeper-2.yaml 
apiVersion: v1 
kind: Pod 
metadata:
  name: ubuntu-sleeper-2 
spec:
  containers:
  - name: ubuntu
    image: ubuntu
    command:
    - "sleep"
    - "5000"
root@controlplane:~# 

root@controlplane:~# vim ubuntu-sleeper-2.yaml 
root@controlplane:~# kubectl apply -f ubuntu-sleeper-2.yaml
pod/ubuntu-sleeper-2 created
root@controlplane:~#


root@controlplane:~# cat ubuntu-sleeper-2.yaml 
apiVersion: v1 
kind: Pod 
metadata:
  name: ubuntu-sleeper-2 
spec:
  containers:
  - name: ubuntu
    image: ubuntu
    command:
    - "sleep"
    - "5000"
root@controlplane:~# 



root@controlplane:~# kubectl edit pod ubuntu-sleeper-3
error: pods "ubuntu-sleeper-3" is invalid
A copy of your changes has been stored to "/tmp/kubectl-edit-wyzn1.yaml"
error: Edit cancelled, no valid changes were saved.
root@controlplane:~# kubectl delete pod ubuntu-sleeper-3
pod "ubuntu-sleeper-3" deleted
kubectl apply -f /tmp/kubectl-edit-wyzn1.yaml
root@controlplane:~# kubectl apply -f /tmp/kubectl-edit-wyzn1.yaml
pod/ubuntu-sleeper-3 created
root@controlplane:~# 



root@controlplane:~/webapp-color# kubectl run webapp-green --image=kodekloud/webapp-color --dry-run=client -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: webapp-green
  name: webapp-green
spec:
  containers:
  - image: kodekloud/webapp-color
    name: webapp-green
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

configmap

configmap
ENV variables in kubernetes

1. use directly as env in pod specification file
2. use configMaps
3. Use secrets

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: webapp-green
  name: webapp-green
spec:
  containers:
  - image: kodekloud/webapp-color
    name: webapp-green
    env:
     - name: APP_COLOR
       value: pink
     - name: APP_VERSION
       valueFrom:
         configMapKeyRef:
     - name: APP_BUILD
       valueFrom:
         secretKeyRef:


1. Create configMaps
2. Inject configMaps into the pod

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl create configmap applicatio-config --from-literal=APP_COLOR=pink --from-literal=APP_BUILD=prod --from-literal=APP_VERSION=1.0
configmaps "applicatio-config" created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl get cm 
NAME                DATA   AGE
applicatio-config   3      44s
kube-root-ca.crt    1      16d
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl get cm applicatio-config -o yaml
apiVersion: v1
data:
  APP_BUILD: prod
  APP_COLOR: pink
  APP_VERSION: "1.0"
kind: ConfigMap
metadata:
  creationTimestamp: "2021-09-20T23:41:13Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:APP_BUILD: {}
        f:APP_COLOR: {}
        f:APP_VERSION: {}
    manager: kubectl-create
    operation: Update
    time: "2021-09-20T23:41:13Z"
  name: applicatio-config
  namespace: default
  resourceVersion: "100911"
  uid: 5495db4a-30e6-45cf-bfb1-923ab7e75791


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl create cm  bkapp-config1 --from-file=./app_config.properties 
configmap/bkapp-config1 created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl get cm bkapp-config1 -o yaml
apiVersion: v1
data:
  app_config.properties: |-
    APP_COLOR=red
    APP_BUILD=preprod
    APP_VERSION=2.0
kind: ConfigMap
metadata:
  creationTimestamp: "2021-09-20T23:45:36Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:app_config.properties: {}
    manager: kubectl-create
    operation: Update
    time: "2021-09-20T23:45:36Z"
  name: bkapp-config1
  namespace: default
  resourceVersion: "101103"
  uid: 684590da-7d86-4214-b67e-79bdfa7c06fc
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$


Declaratively create configmaps:
---------------------------------------------------------------->
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f demo_configmap.yaml 
configmap/bkconfigmap created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl get cm bkconfigmap -o yaml
apiVersion: v1
data:
  APP_BUID: dev
  APP_COLOR: pink
  APP_VERSION: "3.0"
kind: ConfigMap
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"APP_BUID":"dev","APP_COLOR":"pink","APP_VERSION":"3.0"},"kind":"ConfigMap","metadata":{"annotations":{},"labels":{"app":"bkapplication"},"name":"bkconfigmap","namespace":"default"}}
  creationTimestamp: "2021-09-20T23:49:38Z"
  labels:
    app: bkapplication
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:APP_BUID: {}
        f:APP_COLOR: {}
        f:APP_VERSION: {}
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:labels:
          .: {}
          f:app: {}
    manager: kubectl-client-side-apply
    operation: Update
    time: "2021-09-20T23:49:38Z"
  name: bkconfigmap
  namespace: default
  resourceVersion: "101273"
  uid: 9e2932e7-06db-4a0c-b855-146a80928ad3
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl describe cm bkconfigmap
Name:         bkconfigmap
Namespace:    default
Labels:       app=bkapplication
Annotations:  <none>

Data
====
APP_BUID:
----
dev
APP_COLOR:
----
pink
APP_VERSION:
----
3.0
Events:  <none>
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl run nginx --image=nginx --port=8080 --dry-run=client -o yaml > use_configmaps_in_pod.yaml
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f use_configmaps_in_pod.yaml 
pod/nginx created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 21 Sep 2021 07:57:25 +0800
Labels:       run=nginx
Annotations:  <none>
Status:       Running
IP:           172.17.0.3
IPs:
  IP:  172.17.0.3
Containers:
  nginx:
    Container ID:   docker://c3ef07e5d47eb4c688c6096ce122cbe0d0bf8e32861c9c76789ebab030a4bb37
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:853b221d3341add7aaadf5f81dd088ea943ab9c918766e295321294b035f3f3e
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 21 Sep 2021 07:57:32 +0800
    Ready:          True
    Restart Count:  0
    Environment Variables from:
      bkconfigmap  ConfigMap  Optional: false
    Environment:   <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-lxpp9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-lxpp9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  9s    default-scheduler  Successfully assigned default/nginx to minikube
  Normal  Pulling    8s    kubelet            Pulling image "nginx"
  Normal  Pulled     2s    kubelet            Successfully pulled image "nginx" in 5.7820856s
  Normal  Created    2s    kubelet            Created container nginx
  Normal  Started    2s    kubelet            Started container nginx
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

configmaplabs

configmaplabs
root@controlplane:~# kubectl get pods
NAME           READY   STATUS    RESTARTS   AGE
webapp-color   1/1     Running   0          23s
root@controlplane:~# 


root@controlplane:~# kubectl describe pod webapp-color | grep -iC5 "environment"
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 Sep 2021 00:06:12 +0000
    Ready:          True
    Restart Count:  0
    Environment:
      APP_COLOR:  pink
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-rrblh (ro)
Conditions:
  Type              Status
root@controlplane:~# 




root@controlplane:~# kubectl get pod webapp-color -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-09-21T00:05:54Z"
  labels:
    name: webapp-color
spec:
  containers:
  - env:
    - name: APP_COLOR
      value: pink
    image: kodekloud/webapp-color
    imagePullPolicy: Always
    name: webapp-color
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-rrblh
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: controlplane
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-rrblh
    secret:
      defaultMode: 420
      secretName: default-token-rrblh
root@controlplane:~# 


root@controlplane:~# kubectl get cm
NAME               DATA   AGE
db-config          3      7s
kube-root-ca.crt   1      17m
root@controlplane:~# 

root@controlplane:~# kubectl describe cm db-config
Name:         db-config
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
DB_PORT:
----
3306
DB_HOST:
----
SQL01.example.com
DB_NAME:
----
SQL01
Events:  <none>
root@controlplane:~# 


root@controlplane:~# kubectl create cm webapp-config-map --from-literal=APP_COLOR=darkblue --dry-run=client -o yaml
apiVersion: v1
data:
  APP_COLOR: darkblue
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: webapp-config-map
root@controlplane:~# 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl create cm webapp-config-map --from-literal=APP_COLOR=darkblue --dry-run=client -o yaml > webapp-config-map.yaml
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f webapp-config-map.yaml
configmap/webapp-config-map created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f use_configmaps_envFrom.yaml 
pod/webapp-color created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 




root@controlplane:~# kubectl apply -f /tmp/kubectl-edit-roe4a.yaml
pod/webapp-color created
root@controlplane:~# 



root@controlplane:~# cat /tmp/kubectl-edit-roe4a.yaml
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
# pods "webapp-color" was not valid:
# * <nil>: Invalid value: "The edited file failed validation": [yaml: line 18: did not find expected '-' indicator, invalid character 'a' looking for beginning of value]
#
apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"creationTimestamp":"2021-09-21T00:12:58Z","labels":{"name":"webapp-color"},"name":"webapp-color","namespace":"default","resourceVersion":"1669","uid":"f5a9535d-c25f-4ecd-91e0-1b46d9aa4fdd"},"spec":{"containers":[{"env":[{"name":"APP_COLOR","value":"green"}],"envFrom":[{"configMapRef":{"name":"webapp-config-map"}}],"image":"kodekloud/webapp-color","imagePullPolicy":"Always","name":"webapp-color","resources":{},"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","volumeMounts":[{"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount","name":"default-token-rrblh","readOnly":true}]}],"dnsPolicy":"ClusterFirst","enableServiceLinks":true,"nodeName":"controlplane","preemptionPolicy":"PreemptLowerPriority","priority":0,"restartPolicy":"Always","schedulerName":"default-scheduler","securityContext":{},"serviceAccount":"default","serviceAccountName":"default","terminationGracePeriodSeconds":30,"tolerations":[{"effect":"NoExecute","key":"node.kubernetes.io/not-ready","operator":"Exists","tolerationSeconds":300},{"effect":"NoExecute","key":"node.kubernetes.io/unreachable","operator":"Exists","tolerationSeconds":300}],"volumes":[{"name":"default-token-rrblh","secret":{"defaultMode":420,"secretName":"default-token-rrblh"}}]},"status":{"conditions":[{"lastProbeTime":null,"lastTransitionTime":"2021-09-21T00:12:58Z","status":"True","type":"Initialized"},{"lastProbeTime":null,"lastTransitionTime":"2021-09-21T00:13:01Z","status":"True","type":"Ready"},{"lastProbeTime":null,"lastTransitionTime":"2021-09-21T00:13:01Z","status":"True","type":"ContainersReady"},{"lastProbeTime":null,"lastTransitionTime":"2021-09-21T00:12:58Z","status":"True","type":"PodScheduled"}],"containerStatuses":[{"containerID":"docker://4061cfcda617f577f11ff5ab34a8e941a9a898c5da636899d3ec1be18ef8d378","image":"kodekloud/webapp-color:latest","imageID":"docker-pullable://kodekloud/webapp-color@sha256:99c3821ea49b89c7a22d3eebab5c2e1ec651452e7675af243485034a72eb1423","lastState":{},"name":"webapp-color","ready":true,"restartCount":0,"started":true,"state":{"running":{"startedAt":"2021-09-21T00:13:01Z"}}}],"hostIP":"10.58.226.9","phase":"Running","podIP":"10.244.0.5","podIPs":[{"ip":"10.244.0.5"}],"qosClass":"BestEffort","startTime":"2021-09-21T00:12:58Z"}}
  creationTimestamp: "2021-09-21T00:22:48Z"
  labels:
    name: webapp-color
  name: webapp-color
  namespace: default
  resourceVersion: "2395"
  uid: 7af0cf70-d31f-4e82-bf90-b1edf045d6a8
spec:
  containers:
  - envFrom:
     - configMapRef:
         name: webapp-config-map
    image: kodekloud/webapp-color
    imagePullPolicy: Always
    name: webapp-color
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-rrblh
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: controlplane
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-rrblh
    secret:
      defaultMode: 420
      secretName: default-token-rrblh
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2021-09-21T00:22:48Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2021-09-21T00:22:52Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2021-09-21T00:22:52Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2021-09-21T00:22:48Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://93a644dc8e6283b359c1404c42d56fecc679fb54e4b3a65d2ebd8ab149c83567
    image: kodekloud/webapp-color:latest
    imageID: docker-pullable://kodekloud/webapp-color@sha256:99c3821ea49b89c7a22d3eebab5c2e1ec651452e7675af243485034a72eb1423
    lastState: {}
    name: webapp-color
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2021-09-21T00:22:51Z"
  hostIP: 10.58.226.9
  phase: Running
  podIP: 10.244.0.6
  podIPs:
  - ip: 10.244.0.6
  qosClass: BestEffort
  startTime: "2021-09-21T00:22:48Z"
root@controlplane:~# 


MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl explain pods --recursive | grep -iA5 "envFrom"
         envFrom        <[]Object>      
            configMapRef        <Object>
               name     <string>
               optional <boolean>
            prefix      <string>
            secretRef   <Object>
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$

 envFrom        <[]Object>  --> it is a list []

secrets

secrets
if we have application that uses to connect to databse we need to pass the password in secured way...

so k8s secrets helps us to provide secrets to pod specification file

1. Create a secret
2. Inject the secret to the pod specification file


kubectl create secret generic app-secret --from-literal=DB_password=password123456

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl create secret generic app-secret --from-literal=DB_password=password123456 --dry-run=client -o yaml > create_secret.yaml
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f create_secret.yaml
secret/app-secret created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl describe secret app-secret 
Name:         app-secret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
DB_password:  14 bytes
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl create secret generic db-secret --from-file=app_secrets.properties 
secret/db-secret created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ echo "cGFzc3dvcmQxMjM0NTY=" | base64 --decode
password123456MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$
password123456MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ echo -n "mysqluser" | base64
bXlzcWx1c2Vy
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ echo -n "mysqldb" | base64
bXlzcWxkYg==
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

Secrets specification file:
------------------------------------------->
apiVersion: v1
data:
  DB_password: cGFzc3dvcmQxMjM0NTY=
  DB_user: bXlzcWx1c2Vy
  DB_Name: bXlzcWxkYg==
kind: Secret
metadata:
  name: app-secret




apiVersion: v1
kind: Pod
metadata:
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
    ports:
    - containerPort: 80
    envFrom:
      - secretRef:
          name: db-secret

secretslabs

secretslabs
root@controlplane:~# kubectl get secrets
NAME                  TYPE                                  DATA   AGE
default-token-2sjz4   kubernetes.io/service-account-token   3      10m
root@controlplane:~# kubectl describe secret default-token-2sjz4                   
Name:         default-token-2sjz4
Namespace:    default
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: default
              kubernetes.io/service-account.uid: 90c997a2-3d2f-4d56-ae75-37f1950e68d8

Type:  kubernetes.io/service-account-token

Data
====
ca.crt:     1066 bytes
namespace:  7 bytes
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6ImhzVDRDcHQwdVFRYTZQSTFVYlRFcUZVX3JIbmxxWE9EcWxDWUpaUmpkdlUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tMnNqejQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjkwYzk5N2EyLTNkMmYtNGQ1Ni1hZTc1LTM3ZjE5NTBlNjhkOCIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.thnQGTwepuST8EFY9lzMLDTqWZk87q_9nQ1sNMEaqxToxNgba7feuvjK7TQjIt9mwhSMRGym8LaztUAfP8QcYRjGlUR_hb91pJGsYA09d4XpYkycMUk5xpYPa6ppzndzkdYeLEaXZHXBbI6eESuolyjdvhlgDq9z-zjxc0wnnClW9xs_WYVacQx9j6qBRPonwlmNfykboK2SKQu-Uex4VPD2ksWVX_64mf7CmiGMbzqzO52V977vvsQFZ8VZ7465LTtaupgyj2wZ23I2R-85Uich22z3CX-wWKK3RmbGjSBjvQkH1E3Uu9CoBnFOBPJipM1PVkA5fXx1xQhMcQ5ROA
root@controlplane:~# 


root@controlplane:~# kubectl get all
NAME             READY   STATUS    RESTARTS   AGE
pod/mysql        1/1     Running   0          65s
pod/webapp-pod   1/1     Running   0          65s

NAME                     TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes       ClusterIP   10.96.0.1        <none>        443/TCP          13m
service/sql01            ClusterIP   10.103.199.107   <none>        3306/TCP         65s
service/webapp-service   NodePort    10.98.251.213    <none>        8080:30080/TCP   65s
root@controlplane:~# 



root@controlplane:~# kubectl create secret generic db-secret --from-literal=DB_Host=sql01 --dry-run=client -o yaml > db-secret.yaml
root@controlplane:~# vim db-secret.yaml 
root@controlplane:~# echo -n "root" | base64
cm9vdA==
root@controlplane:~# echo -n "password123" | base64
cGFzc3dvcmQxMjM=
root@controlplane:~# vim db-secret.yaml 
root@controlplane:~# vim db-secret.yaml 
root@controlplane:~# kubectl apply -f db-secret.yaml
secret/db-secret created
root@controlplane:~# 



root@controlplane:~# kubectl get secrets
NAME                  TYPE                                  DATA   AGE
db-secret             Opaque                                3      5m5s
default-token-2sjz4   kubernetes.io/service-account-token   3      22m
root@controlplane:~# 


root@controlplane:~# kubectl describe pod webapp-pod 
Name:         webapp-pod
Namespace:    default
Priority:     0
Node:         controlplane/10.3.212.3
Start Time:   Tue, 21 Sep 2021 03:36:02 +0000
Labels:       name=webapp-pod
Annotations:  <none>
Status:       Running
IP:           10.244.0.6
IPs:
  IP:  10.244.0.6
Containers:
  webapp:
    Container ID:   docker://58376983854ab2f58fccca3623fb6f0a5b79439dfe2a5a8d612320a9cde9c901
    Image:          kodekloud/simple-webapp-mysql
    Image ID:       docker-pullable://kodekloud/simple-webapp-mysql@sha256:92943d2b3ea4a1db7c8a9529cd5786ae3b9999e0246ab665c29922e9800d1b41
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 Sep 2021 03:36:41 +0000
    Ready:          True
    Restart Count:  0
    Environment Variables from:
      db-secret   Secret  Optional: false
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-2sjz4 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-2sjz4:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-2sjz4
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason   Age   From     Message
  ----    ------   ----  ----     -------
  Normal  Pulling  67s   kubelet  Pulling image "kodekloud/simple-webapp-mysql"
  Normal  Pulled   67s   kubelet  Successfully pulled image "kodekloud/simple-webapp-mysql" in 253.892074ms
  Normal  Created  66s   kubelet  Created container webapp
  Normal  Started  65s   kubelet  Started container webapp
root@controlplane:~# 

multicontainer_pods

multicontainer_pods
In a single pod we can use two containers like 1.WEB Server and 2.Logging Agent
can share same storage and network, can communicate via localhost

MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl run nginx --image=nginx --dry-run=client -o yaml > multi_container_pod.yaml
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f multi_container_pod.yaml
pod/nginx created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 21 Sep 2021 12:32:17 +0800
Labels:       run=nginx
Annotations:  <none>
Status:       Pending
IP:           
IPs:          <none>
Containers:
  nginx:
    Container ID:   
    Image:          nginx
    Image ID:       
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
  busybox:
    Container ID:   
    Image:          busybox
    Image ID:       
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-lxpp9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-lxpp9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  15s   default-scheduler  Successfully assigned default/nginx to minikube
  Normal  Pulling    14s   kubelet            Pulling image "nginx"
  Normal  Pulled     8s    kubelet            Successfully pulled image "nginx" in 6.110889s
  Normal  Created    8s    kubelet            Created container nginx
  Normal  Started    8s    kubelet            Started container nginx
  Normal  Pulling    8s    kubelet            Pulling image "busybox"
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

multicontainer_podslabs

multicontainer_podslabs
root@controlplane:~# kubectl get pods
NAME        READY   STATUS              RESTARTS   AGE
app         0/1     ContainerCreating   0          44s
blue        0/2     ContainerCreating   0          5s
fluent-ui   1/1     Running             0          45s
red         0/3     ContainerCreating   0          34s
root@controlplane:~# kubectl describe pod blue
Name:         blue
Namespace:    default
Priority:     0
Node:         controlplane/10.6.30.8
Start Time:   Tue, 21 Sep 2021 04:34:53 +0000
Labels:       <none>
Annotations:  <none>
Status:       Pending
IP:           
IPs:          <none>
Containers:
  teal:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      4500
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9gh8c (ro)
  navy:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      4500
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9gh8c (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9gh8c:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9gh8c
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  23s   default-scheduler  Successfully assigned default/blue to controlplane
  Normal  Pulling    20s   kubelet            Pulling image "busybox"
root@controlplane:~# 


Create a multi-container pod with 2 containers.

Name: yellow
Container 1 Name: lemon
Container 1 Image: busybox
Container 2 Name: gold
Container 2 Image: redi

If the pod goes into the crashloopbackoff then add sleep 1000 in the lemon container.

root@controlplane:~# cat multi_contianer.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: yellow
  name: yellow
spec:
  containers:
  - image: busybox
    name: lemon 
    command:
     - "sleep"
     - "1000"
  - image: redis
    name: gold
root@controlplane:~# 


root@controlplane:~# kubectl apply -f multi_contianer.yaml
pod/yellow created
root@controlplane:~# 


root@controlplane:~# kubectl describe pod yellow
Name:         yellow
Namespace:    default
Priority:     0
Node:         controlplane/10.6.30.8
Start Time:   Tue, 21 Sep 2021 04:46:45 +0000
Labels:       run=yellow
Annotations:  <none>
Status:       Running
IP:           10.244.0.11
IPs:
  IP:  10.244.0.11
Containers:
  lemon:
    Container ID:  docker://d2ac7da68aeeddc4a7661576c0d776ad4ae8506e78ae757a1243d90d1eab1bc9
    Image:         busybox
    Image ID:      docker-pullable://busybox@sha256:52f73a0a43a16cf37cd0720c90887ce972fe60ee06a687ee71fb93a7ca601df7
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      1000
    State:          Running
      Started:      Tue, 21 Sep 2021 04:46:49 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9gh8c (ro)
  gold:
    Container ID:   docker://57bec715dc98f4bd723f17b0170f4467ca10a7496d0d518ec79781c9e29b7555
    Image:          redis
    Image ID:       docker-pullable://redis@sha256:e595e79c05c7690f50ef0136acc9d932d65d8b2ce7915d26a68ca3fb41a7db61
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 Sep 2021 04:47:01 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9gh8c (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-9gh8c:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9gh8c
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  28s   default-scheduler  Successfully assigned default/yellow to controlplane
  Normal  Pulling    25s   kubelet            Pulling image "busybox"
  Normal  Pulled     25s   kubelet            Successfully pulled image "busybox" in 264.575064ms
  Normal  Created    25s   kubelet            Created container lemon
  Normal  Started    24s   kubelet            Started container lemon
  Normal  Pulling    24s   kubelet            Pulling image "redis"
  Normal  Pulled     13s   kubelet            Successfully pulled image "redis" in 11.216716468s
  Normal  Created    12s   kubelet            Created container gold
  Normal  Started    12s   kubelet            Started container gold
root@controlplane:~# 


root@controlplane:~# kubectl get all -n elastic-stack
NAME                 READY   STATUS    RESTARTS   AGE
pod/app              1/1     Running   0          14m
pod/elastic-search   1/1     Running   0          14m
pod/kibana           1/1     Running   0          14m

NAME                    TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)                         AGE
service/elasticsearch   NodePort   10.102.56.7      <none>        9200:30200/TCP,9300:30300/TCP   14m
service/kibana          NodePort   10.109.206.204   <none>        5601:30601/TCP                  14m
root@controlplane:~# 


root@controlplane:~# kubectl logs kibana -n elastic-stack | tail
{"type":"log","@timestamp":"2021-09-21T04:37:42Z","tags":["status","plugin:logstash@6.4.2","info"],"pid":1,"state":"green","message":"Status changed from red to green - Ready","prevState":"red","prevMsg":"Request Timeout after 3000ms"}
{"type":"log","@timestamp":"2021-09-21T04:37:42Z","tags":["status","plugin:reporting@6.4.2","info"],"pid":1,"state":"green","message":"Status changed from red to green - Ready","prevState":"red","prevMsg":"Request Timeout after 3000ms"}
{"type":"log","@timestamp":"2021-09-21T04:37:42Z","tags":["info","monitoring-ui","kibana-monitoring"],"pid":1,"message":"Starting monitoring stats collection"}
{"type":"log","@timestamp":"2021-09-21T04:37:42Z","tags":["status","plugin:security@6.4.2","info"],"pid":1,"state":"green","message":"Status changed from red to green - Ready","prevState":"red","prevMsg":"Request Timeout after 3000ms"}
{"type":"log","@timestamp":"2021-09-21T04:37:43Z","tags":["license","info","xpack"],"pid":1,"message":"Imported license information from Elasticsearch for the [monitoring] cluster: mode: basic | status: active"}
{"type":"log","@timestamp":"2021-09-21T04:37:45Z","tags":["status","plugin:elasticsearch@6.4.2","info"],"pid":1,"state":"green","message":"Status changed from red to green - Ready","prevState":"red","prevMsg":"Request Timeout after 3000ms"}
{"type":"log","@timestamp":"2021-09-21T04:37:56Z","tags":["info","http","server","listening"],"pid":1,"message":"Server running at http://0:5601"}
{"type":"response","@timestamp":"2021-09-21T04:37:57Z","tags":[],"pid":1,"method":"head","statusCode":200,"req":{"url":"/","method":"head","headers":{"host":"0.0.0.0:30601","user-agent":"curl/7.58.0","accept":"*/*"},"remoteAddress":"10.244.0.1","userAgent":"10.244.0.1"},"res":{"statusCode":200,"responseTime":37,"contentLength":9},"message":"HEAD / 200 37ms - 9.0B"}
{"type":"response","@timestamp":"2021-09-21T04:38:07Z","tags":[],"pid":1,"method":"post","statusCode":200,"req":{"url":"/api/saved_objects/index-pattern/filebeat-*?overwrite=false","method":"post","headers":{"host":"0.0.0.0:30601","user-agent":"curl/7.58.0","accept":"*/*","content-type":"application/json","kbn-xsrf":"athing","content-length":"66"},"remoteAddress":"10.244.0.1","userAgent":"10.244.0.1"},"res":{"statusCode":200,"responseTime":1425,"contentLength":9},"message":"POST /api/saved_objects/index-pattern/filebeat-*?overwrite=false 200 1425ms - 9.0B"}
{"type":"response","@timestamp":"2021-09-21T04:38:08Z","tags":[],"pid":1,"method":"post","statusCode":200,"req":{"url":"/api/kibana/settings/defaultIndex","method":"post","headers":{"host":"0.0.0.0:30601","user-agent":"curl/7.58.0","accept":"*/*","content-type":"application/json","kbn-xsrf":"anytng","content-length":"22"},"remoteAddress":"10.244.0.1","userAgent":"10.244.0.1"},"res":{"statusCode":200,"responseTime":2068,"contentLength":9},"message":"POST /api/kibana/settings/defaultIndex 200 2068ms - 9.0B"}
root@controlplane:~# 


root@controlplane:~# kubectl logs elastic-search -n elastic-stack | tail
[2021-09-21T04:38:07,531][INFO ][o.e.c.m.MetaDataCreateIndexService] [gTtv6_7] [.kibana] creating index, cause [auto(bulk api)], templates [kibana_index_template:.kibana], shards [1]/[1], mappings [doc]
[2021-09-21T04:38:07,541][INFO ][o.e.c.r.a.AllocationService] [gTtv6_7] updating number_of_replicas to [0] for indices [.kibana]
[2021-09-21T04:38:08,123][INFO ][o.e.c.r.a.AllocationService] [gTtv6_7] Cluster health status changed from [YELLOW] to [GREEN] (reason: [shards started [[.kibana][0]] ...]).
[2021-09-21T04:38:08,844][WARN ][o.e.d.a.a.i.t.p.PutIndexTemplateRequest] Deprecated field [template] used, replaced by [index_patterns]
[2021-09-21T04:38:08,920][INFO ][o.e.c.m.MetaDataIndexTemplateService] [gTtv6_7] adding template [kibana_index_template:.kibana] for index patterns [.kibana]
[2021-09-21T04:38:09,119][WARN ][o.e.d.a.a.i.t.p.PutIndexTemplateRequest] Deprecated field [template] used, replaced by [index_patterns]
[2021-09-21T04:38:09,127][INFO ][o.e.c.m.MetaDataIndexTemplateService] [gTtv6_7] adding template [kibana_index_template:.kibana] for index patterns [.kibana]
[2021-09-21T04:38:09,836][WARN ][o.e.d.a.a.i.t.p.PutIndexTemplateRequest] Deprecated field [template] used, replaced by [index_patterns]
[2021-09-21T04:38:09,845][INFO ][o.e.c.m.MetaDataIndexTemplateService] [gTtv6_7] adding template [kibana_index_template:.kibana] for index patterns [.kibana]
[2021-09-21T04:38:09,923][INFO ][o.e.c.m.MetaDataMappingService] [gTtv6_7] [.kibana/3bcSc1d9S1CcqH-FLhLPaw] update_mapping [doc]
root@controlplane:~# 



Edit the pod to add a sidecar container to send logs to Elastic Search. Mount the log volume to the sidecar container.
Only add a new container.


Name: app
Container Name: sidecar
Container Image: kodekloud/filebeat-configured
Volume Mount: log-volume
Mount Path: /var/log/event-simulator/
Existing Container Name: app
Existing Container Image: kodekloud/event-simulator


spec:
  containers:
  - image: kodekloud/filebeat-configured
    name: sidecar
    volumeMounts:
    - mountPath: /var/log/event-simulator/
      name: log-volume
  - image: kodekloud/event-simulator
    imagePullPolicy: Always
    name: app
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /log
      name: log-volume
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-9tt4w
      readOnly: true




root@controlplane:~# kubectl edit pod app -n elastic-stack
error: pods "app" is invalid
A copy of your changes has been stored to "/tmp/kubectl-edit-cao9c.yaml"
error: Edit cancelled, no valid changes were saved.
root@controlplane:~# kubectl edit pod app -n elastic-stack
Edit cancelled, no changes made.
root@controlplane:~# kubectl delete pod app -n elastic-stack
pod "app" deleted
kubectl apply -f /tmp/kubectl-edit-cao9c.yaml
root@controlplane:~# kubectl apply -f /tmp/kubectl-edit-cao9c.yaml
pod/app created
root@controlplane:~# 

initcontainers

initcontainers
if we want to run a process that runs to completion in a container. 
For example a process that pulls a code or binary from a repository that will be used by the main web application.


That is a task that will be run only one time when the pod is first created. 
Or a process that waits for an external service or database to be up before the actual application starts. 
That’s where initContainers comes in



MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl apply -f 14.demo_init_container_example.yaml 
pod/bkapp-pod created
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl get pods
NAME        READY   STATUS             RESTARTS   AGE
bkapp-pod   0/1     Init:Error         0          10s
nginx       1/2     CrashLoopBackOff   16         59m
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ kubectl describe pod bkapp-pod
Name:         bkapp-pod
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 21 Sep 2021 13:31:40 +0800
Labels:       app=bkapp
Annotations:  <none>
Status:       Pending
IP:           172.17.0.4
IPs:
  IP:  172.17.0.4
Init Containers:
  init-bkservice:
    Container ID:  docker://56d6fdf4e53adf06947b10fa1457c2ae266ba5e3110a99a10091af8d9ae09101
    Image:         busybox
    Image ID:      docker-pullable://busybox@sha256:52f73a0a43a16cf37cd0720c90887ce972fe60ee06a687ee71fb93a7ca601df7
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      git clone git@github.com:Bharathkumarraju/certified_kubernetes_administrator.git;
    State:          Terminated
      Reason:       Error
      Exit Code:    127
      Started:      Tue, 21 Sep 2021 13:32:12 +0800
      Finished:     Tue, 21 Sep 2021 13:32:12 +0800
    Last State:     Terminated
      Reason:       Error
      Exit Code:    127
      Started:      Tue, 21 Sep 2021 13:31:50 +0800
      Finished:     Tue, 21 Sep 2021 13:31:50 +0800
    Ready:          False
    Restart Count:  2
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
  init-bkdb:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      until nslookup mydb; do echo waiting for mydb; sleep 2; done;
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
Containers:
  bkapp-container:
    Container ID:  
    Image:         busybox:1.28
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      echo the app is running!! && sleep 3600
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-lxpp9 (ro)
Conditions:
  Type              Status
  Initialized       False 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-lxpp9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-lxpp9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  37s                default-scheduler  Successfully assigned default/bkapp-pod to minikube
  Normal   Pulled     32s                kubelet            Successfully pulled image "busybox" in 4.0991627s
  Normal   Pulled     27s                kubelet            Successfully pulled image "busybox" in 3.8770697s
  Normal   Pulling    10s (x3 over 36s)  kubelet            Pulling image "busybox"
  Normal   Created    5s (x3 over 32s)   kubelet            Created container init-bkservice
  Normal   Started    5s (x3 over 31s)   kubelet            Started container init-bkservice
  Normal   Pulled     5s                 kubelet            Successfully pulled image "busybox" in 5.2892604s
  Warning  BackOff    4s (x3 over 25s)   kubelet            Back-off restarting failed container
MacBook-Pro:4.Application_lifecycle_mgmt bharathdasaraju$ 

initcontainerlabs

initcontainerlabs
root@controlplane:~# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
blue    1/1     Running   0          103s
green   2/2     Running   0          103s
red     1/1     Running   0          103s
root@controlplane:~#


root@controlplane:~# kubectl describe pod blue                 
Name:         blue
Namespace:    default
Priority:     0
Node:         controlplane/10.8.36.3
Start Time:   Tue, 21 Sep 2021 05:35:44 +0000
Labels:       <none>
Annotations:  <none>
Status:       Running
IP:           10.244.0.6
IPs:
  IP:  10.244.0.6
Init Containers:
  init-myservice:
    Container ID:  docker://cb6b4b67652aaab333bc31891c817b30804888aa1070f310d8bcd278d65e93ef
    Image:         busybox
    Image ID:      docker-pullable://busybox@sha256:52f73a0a43a16cf37cd0720c90887ce972fe60ee06a687ee71fb93a7ca601df7
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 5
    State:          Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Tue, 21 Sep 2021 05:35:53 +0000
      Finished:     Tue, 21 Sep 2021 05:35:58 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-5lj6j (ro)
Containers:
  green-container-1:
    Container ID:  docker://e4e921212ffdb2dde1ea8823172327b8cdce5ff51dbc4cdeca704ef5b7280d5a
    Image:         busybox:1.28
    Image ID:      docker-pullable://busybox@sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      echo The app is running! && sleep 3600
    State:          Running
      Started:      Tue, 21 Sep 2021 05:35:59 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-5lj6j (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-5lj6j:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-5lj6j
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  67s   default-scheduler  Successfully assigned default/blue to controlplane
  Normal  Pulling    63s   kubelet            Pulling image "busybox"
  Normal  Pulled     59s   kubelet            Successfully pulled image "busybox" in 3.086779983s
  Normal  Created    59s   kubelet            Created container init-myservice
  Normal  Started    58s   kubelet            Started container init-myservice
  Normal  Pulled     53s   kubelet            Container image "busybox:1.28" already present on machine
  Normal  Created    53s   kubelet            Created container green-container-1
  Normal  Started    52s   kubelet            Started container green-container-1
root@controlplane:~#



root@controlplane:~# kubectl get pods
NAME     READY   STATUS     RESTARTS   AGE
blue     1/1     Running    0          3m2s
green    2/2     Running    0          3m2s
purple   0/1     Init:0/2   0          9s
red      1/1     Running    0          3m2s
root@controlplane:~# 

yaml specifications for application

poddefinition

poddefinition
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: ubuntu-sleeper
  name: ubuntu-sleeper
spec:
  containers:
  - image: ubuntu-sleeper-entry-cmd
    name: ubuntu-sleeper
    command: ["sleep2.0"]  # Overwrites the ENTRYPOINT filed in docker
    args: ["35"]  #Overwrites the CMD field in docker

overwritepodargs

overwritepodargs
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: webapp-green
  name: webapp-green
spec:
  containers:
  - image: kodekloud/webapp-color
    name: webapp-green
    args: ["--color", "green"]

envs_in_poddefinition

envs_in_poddefinition
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: webapp-green
  name: webapp-green
spec:
  containers:
  - image: kodekloud/webapp-color
    name: webapp-green
    env:
     - name: APP_COLOR
       value: pink
     - name: APP_VERSION
       valueFrom:
         configMapKeyRef:
     - name: APP_BUILD
       valueFrom:
         secretKeyRef:

app_config_properties

app_config_properties
APP_COLOR=red
APP_BUILD=preprod
APP_VERSION=2.0

configmap

configmap
apiVersion: v1
kind: ConfigMap
metadata:
  name: bkconfigmap
  labels:
    app: bkapplication
data:
  APP_COLOR: pink
  APP_BUID: dev
  APP_VERSION: "3.0"

configmap_in_pods

configmap_in_pods
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
    ports:
    - containerPort: 80
    envFrom:                # can use entire configmap like this
      - configMapRef:
          name: bkconfigmap
    env:                  # can specify the single key from  the configMap
      - name: APP_COLOR
        valueFrom:
          configMapKeyRef:
            name: bkconfigmap
            key: APP_COLOR
    volumes:               # Can use configMap as a Separate Volume as well
      - name:  app-config-volume
        configMap:
          name: bkconfigmap
        

webconfigmap

webconfigmap
apiVersion: v1
data:
  APP_COLOR: darkblue
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: webapp-config-map

configmap_use_envFrom

configmap_use_envFrom
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: webapp-color
  name: webapp-color
  namespace: default
spec:
  containers:
    - envFrom:
      - configMapRef:
          name: webapp-config-map
      image: kodekloud/webapp-color
      name: webapp-color

createsecrets

createsecrets
apiVersion: v1
data:
  DB_password: cGFzc3dvcmQxMjM0NTY=
  DB_user: bXlzcWx1c2Vy
  DB_Name: bXlzcWxkYg==
kind: Secret
metadata:
  name: app-secret

app_secrets

app_secrets
DB_HOST=mysql
DB_USER=root
DB_Password=password12345a

usesecrets_in_app

usesecrets_in_app
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
    ports:
    - containerPort: 80
    envFrom:                    # whole secret as secretRef
      - secretRef:
          name: db-secret
    env:                       # Add a single secret env 
      - name: DB_Password
        valueFrom:
          secretKeyRef:
            key: DB_password
            name: db-secret
    volumes:                          # Add whole secret object as a volume
      - name:  db-secret-volume
        secret:
          secretName: db-secret

multicontainerpods

multicontainerpods
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
  - image: busybox
    name: busybox

configure_sidecar

configure_sidecar
apiVersion: v1
kind: Pod
metadata:
  name: app
  namespace: elastic-stack
  labels:
    name: app
spec:
  containers:
  - name: app
    image: kodekloud/event-simulator
    volumeMounts:
    - mountPath: /log
      name: log-volume

  - name: sidecar
    image: kodekloud/filebeat-configured
    volumeMounts:
    - mountPath: /var/log/event-simulator/
      name: log-volume

  volumes:
  - name: log-volume
    hostPath:
      # directory location on host
      path: /var/log/webapp
      # this field is optional
      type: DirectoryOrCreate

init_container

init_container
apiVersion: v1
kind: Pod
metadata:
  name: bkapp-pod
  labels:
    app: bkapp
spec:
  containers:
  - name: bkapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo the app is running!! && sleep 3600']
  initContainers:
  - name: init-bkservice
    image: busybox
    command: ['sh', '-c', 'git clone git@github.com:Bharathkumarraju/certified_kubernetes_administrator.git;']
  - name: init-bkdb
    image: busybox
    command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']




root@controlplane:~# kubectl edit pod red
error: pods "red" is invalid
A copy of your changes has been stored to "/tmp/kubectl-edit-phwq3.yaml"
error: Edit cancelled, no valid changes were saved.
root@controlplane:~# kubectl delete pod red
pod "red" deleted
kubectl apply -f /tmp/kubectl-edit-phwq3.yaml


root@controlplane:~# kubectl apply -f /tmp/kubectl-edit-phwq3.yaml
pod/red created
root@controlplane:~# cat /tmp/kubectl-edit-phwq3.yaml
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
# pods "red" was not valid:
# * spec.initContainers: Forbidden: pod updates may not add or remove containers
#
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-09-21T05:35:44Z"
  name: red
  namespace: default
  resourceVersion: "984"
  uid: 129100ea-eaf6-45f5-b3b1-35038703b508
spec:
  initContainers:
  - name: init-busybox
    image: busybox
    command:
      - sh
      - c
      - sleep 20
  containers:
  - command:
    - sh
    - -c
    - echo The app is running! && sleep 3600
    image: busybox:1.28
    imagePullPolicy: IfNotPresent
    name: red-container
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-5lj6j
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: controlplane
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-5lj6j
    secret:
      defaultMode: 420
      secretName: default-token-5lj6j
root@controlplane:~# 

configure sidecar to send logs to elasticsearch

used below code to to configure ELK

ELK code at ELK-CODE.

command args in pod specification

pod specifications at webpods.