Wednesday, December 30, 2020

Kubernetes for Developers #6: Kubernetes Objects

Kubernetes objects are persistent entities and used to represent the state of the cluster.

It will be created by using imperative command on live objects or declaratively from a file.

kubectl command line interface used to send Kubernetes objects to API server and make necessary actions in the cluster.

In general, we specify Kubernetes objects in the .yml file and send to kubectl CLI. Kubectl converts the information to JSON while interacting with API server

Syntax:

apiVersionv1    # v1, apps/v1, and extensions/v1beta1
kindPod   # Pod, Deployment, Service etc.
metadata:
  namenginx-pod
spec:

  • apiVersion - version of the Kubernetes API you are using to create an object
  • kind - kind of object you want to create
  • metadata - It helps to uniquely identify the object, including a name, labels and optional namespace
  • spec – It is used to define desired state for the object

1. Pod

A pod is the most basic unit of the Kubernetes cluster. It usually contains one or more running containers. Pods are designed to be ephemeral in nature which means that they can be destroyed at any time. Containers in a pod share the same network and storage

apiVersionv1
kindPod
metadata:
  namefirst-pod
  labels:
    namefirst-pod
spec:
  containers:
    - namefirst-pod
      imagehello-world
      ports:
        - containerPort8080

containers: It contains,

  • name:The name of the container that you’ll run in your pod.
  • image:The image of the application you want to run in your pods.
  • containerPort:  It is the port of your application container is listening to.


2. ReplicationController

It is used to create multiple instances of same pod in the cluster node. It ensures that at any given time, the desired number of pods specified are in the running state. If a pod stops or dies, the ReplicationController creates another one to replace it.

apiVersionv1
kindReplicationController
metadata:
  namemyapp
spec:
  replicas2
  selector:
    appmyapp
  template:
    metadata:
      namefirst-pod
      labels:
        namefirst-pod
    spec:
      containers:
        - namefirst-pod
          imagehello-world
          ports:
            - containerPort8080

Definition says replicas:2 it means that any given time two pods must be running in the cluster. If any pod fails, replication controller creates new pod immediately.

The template section provides characteristics of the pod. It is like Pod definition.

3. Replicaset

It is the next generation of ReplicationController

Replicaset

ReplicationController

It uses matchLabels specified under selection and works as set-based selector

Ex: env=prod/qa

It selects all the objects where key=env irrespective of the value

It uses labels selected under selector section and works as equality-based selector

Ex:  env=prod

It selects all objects where key=env and value=prod

Selector attribute is mandatory

selector attribute is not required

It uses rollout technique and will be used internally by Deployment objects

It uses rolling update technique. It means, each pod template changes one at a time until all the pods are updated.

It is not meant to be created on their own, it creates automatically when deployment objects are created

It is used to create on their own

It belongs to apiVersion: apps/v1

It belongs to apiVersion: v1


apiVersionapps/v1
kindReplicaSet
metadata:
  namefrontend
  labels:
    appguestbook
    tierfrontend
spec:
  replicas3
  selector:
    matchLabels:
      tierfrontend
  template:
    metadata:
      labels:
        tierfrontend
    spec:
      containers:
        - namephp-redis
          imagegcr.io/google_samples/gb-frontend:v3

4. Deployment

It encapsulates both Replicaset and Pod to provide declarative method for defining a resource.

It is used for managing pods and internally uses Replicaset for creating number of pods.

It can be used to scale your application by increasing the number of running pods, or update the running application

apiVersionapps/v1
kindDeployment
metadata:
  namenginx-deployment
  labels:
    appnginx
spec:
  replicas3
  selector:
    matchLabels:
      appnginx
  template:
    metadata:
      labels:
        appnginx
    spec:
      containers:
        - namenginx
          imagenginx:1.7.9
          ports:
            - containerPort80

5. Namespace

It is used for grouping Kubernetes objects in the cluster and actions will be performed against the namespace.

Example: create namespace for each environment or Team

apiVersionv1
kindNamespace
metadata:
    nameproduction
_ _ _

apiVersionv1
kindNamespace
metadata:
    namestaging

namespace will be referred in the metadata section of Kubernetes object.

apiVersionv1
kindPod
metadata:
  namefirst-pod
  namespacestaging
  labels:
    namefirst-pod
    apphello-world-app
spec:

6. ConfigMap

It is used for creating configurations for the container and will be changed dynamically while containers are running

There are 3 ways to create configMap

a) from a directory:

  • Create a directory and name it my_config
  •  Inside the directory, create two files: name1.txt and name2.txt
  •  In the name1.txt file, add the following lines:
nameRama
gendermale
cityabcd

  •  In the name2.txt file add the following lines:

nameKrishna
gendermale
cityxyz

execute the following command to create the directory

> kubectl create configmap my-config --from-file=my_config/

b) from files:

The approach is the same as the one for creating ConfigMap from a directory. But in this case, we specify the file path instead of a folder

> kubectl create configmap my-config --from-file=my_config/name1.txt

c) from literals:

> kubectl create configmap my-config --from-literal=name=rama --from-literal=gender=male

We can consume ConfigMaps in the pod by specifying “ConfigMapRef”

apiVersionv1
kindPod
metadata:
  nameapi-test-pod
spec:
  containers:
    - nametest-container
      imagek8s.gcr.io/busybox
      command: ["/bin/sh""-c""env"]
      envFrom:
        - configMapRef:
            namemy-config

use “configMapKeyRef” for specifying selected key

apiVersionv1
kindPod
metadata:
  nameapi-test-pod
spec:
  containers:
    - nametest-container
      imagek8s.gcr.io/busybox
      command: ["/bin/sh""-c""env"]
      env:
        - nametest
          valuetest123
        - nameRAMA_CITY
          valueFrom:
            configMapKeyRef:
              namemy-config
              keycity


Kubernetes for Developers Journey.

Happy Coding :)

Tuesday, December 29, 2020

Kubernetes for Developers #5: Kubernetes Web UI Dashboard

 It is a web-based UI for viewing entire Kubernetes cluster information like Nodes, Deployments, Pods, Services, Jobs, Secrets etc.

It is used to deploy containers into the Kubernetes cluster and troubleshoot the containers in the K8 cluster.

It is used to create or modify individual Kubernetes resources like Deployments, Pods, Services, Jobs etc.


 Enable Web UI Dashboard using Kubectl:

Make sure Kubernetes cluster up and running before executing following kubectl commands

a) run the following command to enable Dashboard



> kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml


Alternately, you can download same .yaml file into local computer, save as kubernetes-dashboard.yaml and run the following command

> kubectl apply -f ./kubernetes-dashboard.yaml


The above command creates dashboard deployment, service, service account, roles, role binding and secret.












b) run the following command for enabling proxy between local computer and Kubernetes Apiserver.

> Kubectl proxy


Go to the browser and hit the following url to view Web UI Dashboard login page

 http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

c) run the following command to get valid bearer token for login


> kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user | awk '{print $1}')






copy the bearer token and enter it into the Web UI Dashboard login page

Kubernetes dashboard has four main sections i.e.

1. Cluster:

It shows information about Nodes, Namespaces, Persistent Volumes, Roles and Storage Classes. Node list view contains CPU and memory usage metrics aggregated across all Nodes. On click of each node, it shows node status, allocated resources, events and pods running on the node.

2. Workloads:

It shows all applications running in the selected namespace including Deployments, Replica sets, Pods, Jobs, Daemon Sets, etc.

3. Discovery and Load Balancing:

It shows information about services which exposed to external world and internal endpoints within a cluster.

4. Config and Storage:

It shows information about configurations and secrets which is used for the containers. 

Kubernetes for Developers Journey.

Happy Coding :)

Saturday, December 19, 2020

Kubernetes for Developers #4: Enable kubectl bash autocompletion

Kubectl provides autocomplete support for bash which can save us lot of typing.

Bash on Windows using Git bash

1. Install Git bash from https://git-scm.com/downloads if it is not available in your computer

2. Navigate to “C:\Users\<yourname>” from Git bash cli

3. Run following command to get kubectl autocompletion bash commands and save into “kubectl-completion.bash” file


> kubectl completion bash > ~/kubectl-completion.bash

4. Create or Update .bashrc file source


> echo 'source ~/kubectl-completion.bash' >> .bashrc

5. Restart Git bash and start typing kubectl get po          ( press [TAB] key )














Bash on Windows using Conemu/Cmder

It is an another handy multi and split tab windows terminal. It supports multiple command terminals like cmd, PowerShell, bash and etc.

1. Install Git bash from https://git-scm.com/downloads if it is not available in your computer

2. Install Conemu from https://conemu.github.io/ if it is not available in your computer.

3. Open new Git Bash console from Conemu terminal

4. Navigate to “C:\Users\<yourname>”

5. Run following command to get kubectl autocompletion bash commands and save into “kubectl-completion.bash” file


> kubectl completion bash > ~/kubectl-completion.bash

6. Create or Update .bashrc file source


> echo 'source ~/kubectl-completion.bash' >> .bashrc

7. Restart Conemu terminal and start typing kubectl get po   ( press [TAB] key )


Bash on Linux/macOS

Please go through below link to enable kubectl autocompletion on Linux/macOS

https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion


Kubernetes for Developers Journey.
Happy Coding :)

Thursday, December 17, 2020

Kubernetes for Developers #3: kubectl CLI

It is a command line interface used for running commands against K8 cluster master node API server. It has a config file called “kubeconfig” which maintains cluster information for authentication and connecting to API server.

kubectl


Syntax

kubectl [command] [TYPE] [NAME] [flags]

a) command: It accepts operation name i.e. create, apply, get, delete, describe, exec, log

b) Type: It accepts resource type in the form of singular, plural or abbreviated. Resource types are case-insensitive

The below three commands gives same result

> kubectl get pod 
> kubectl get pods 
> kubectl get po 


See the following table data with resource type and abbreviated name (i.e. short name)

Name

ShortName

KIND

pods

po

Pod

configmaps

cm

ConfigMap

namespaces

ns

Namespace

nodes

no

Node

replicationcontrollers

rc

ReplicationController

secrets

 

Secret

services

svc

Service

deployments

deploy

Deployment

replicasets

rs

ReplicaSet

ingresses

ing

Ingress

cronjobs

cj

CronJob

c) Name: It is used for specifying name of the resource and it is case-sensitive.

> kubectl get pod helloworld
> kubectl get pod helloworld helloworld2  
> kubectl get -f ./helloworld.yml 
> kubectl get -f ./helloworld.yml  -f ./helloworld2.yml

Examples:

// Display endpoint information about the master and services in the cluster
> kubectl cluster-info

// Display both kubectl client version and Kubernetes API server version
> kubectl version

// Display cluster configuration settings like contexts, users and etc. 
> kubectl config view

// Display all resources of bindings, shotnames and KIND
> kubectl api-resources

// Display all resources info from default namespace
> kubectl get all

// Display all resources info from all namespaces
> kubectl get all --all-namespaces

// Create resource from a file
> kubectl create -f ./helloworld.yml

// Create resources from multiple files
> kubectl create -f ./helloworld.yml -f ./helloworld2.yml

// Create resources from the given directory
> kubectl create -f ./dir

// Create/Update resource from a file
> kubectl apply -f ./helloworld.yml

// Create/Update resources from multiple files
> kubectl apply -f ./helloworld.yml -f ./helloworld2.yml

// Create/Update resources from the given directory
> kubectl apply -f ./dir

// switch to my-namespace 
> kubectl config set-context --current --namespace=my-namespace

// List all pods 
> kubectl get pods

// List all pods with additional information
> kubectl get pods -o wide

// Get pod yml file
> kubectl get pod my-pod -o yml

// List all services and deployments together
> kubectl get services,deployments

// Display detail state of pod
> kubectl describe pods my-pod

// Delete a pod which specifed in the my-pod.yml
> kubectl delete -f ./my-pod.yml

// Delete pods with name pod1 and pod2
> kubectl delete pod pod1 pod2

// Delete pods with label name=mylabel
> kubectl delete pods -l name=mylabel

// Display logs from mypod
> kubectl logs mypod

// Stream logs from mypod
> kubectl logs -f mypod

// Execute command against a container 
> kubectl exec <pod_name> -c <container_name> -- ls

// Get interactive shell on a first-container pod
> kubectl exec -it <pod_name> -- /bin/sh


Kubernetes for Developers Journey.

Happy Coding :)