Friday, September 9, 2022

Kubernetes Commands

#kubectl run mypod --image=nginx

#kubectl get pods -o wide

#kubectl get pods -o yml

#kubectl get pods -o json

#kubectl explain pods|less  --> Provide detail information about POD

#kubectl explain rc|less

#kubectl describe pod <pod-name>  -> Provide us pod information

#Try to delete container which is running on worker node

#kubectl get pods

#kubectl delete pod <pod-name>

#kubectl get ns --> It will show us namespaces



Label:

kubectl label pod mypod env=uat

kubectl get pods -o wide

Create POD:
====
K8 Architecture:

=======

K8 Installation using kubeadm
Minikube
============

POD:

A pod is the smallest execution unit in Kubernetes. A pod encapsulates one or more applications. Pods are ephemeral by nature, if a pod (or the node it executes on) fails, Kubernetes can automatically create a new replica of that pod to continue operations.

Create POD
#kubectl run myfirstpod --image=nginx

Delete POD
Syntax: kubectl delete  resourcetype resourcename
#kubectl delete pod pod-name

Create POD using YAML file:

---

$ kubectl explain pod
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status       <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status


First YAML:

apiVersion: v1
kind: Pod
metadata:
  name: mypod1
spec:
  containers:
  - name: mycont
    image: httpd

NAME     READY   STATUS    RESTARTS   AGE
mypod1   1/1     Running   0          104s


Validate YML file using dry run:

$ kubectl create -f mypod.yml  --dry-run
W0909 17:40:59.349555    6142 helpers.go:553] --dry-run is deprecated and can be replaced with --dry-run=client.
pod/mypod1 created (dry run)


$ kubectl explain pod --recursive |less
 It will show us field inside yaml file.

$ kubectl explain pod --recursive |head -20
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
   kind <string>
   metadata     <Object>
      annotations       <map[string]string>
      clusterName       <string>
      creationTimestamp <string>
      deletionGracePeriodSeconds        <integer>
      deletionTimestamp <string>
      finalizers        <[]string>
      generateName      <string>
      generation        <integer>
      labels    <map[string]string>


Create yaml using command:

kubectl run demopod1 --image=nginx --dry-run -o yaml >test

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: demopod1
  name: demopod1
spec:
  containers:
  - image: nginx
    name: demopod1
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}


Delete POD using YML:
$ kubectl delete -f mypod.yml 
pod "mypod1" deleted

=========
edit POD
#kubectl edit pod myfirstpod
--> We can change label details

===================


Create and apply Difference:

Object/Resources creation:

Imperative command: Without using yaml

Imperative Object configuration:   #kubectl create -f file-name
If you want to edit configuration then we will use edit command.
#kubectl edit pod mypod
Manually we have to edit configuration.


Declarative Object configuration: #kubectl apply -f file-name
In declarative you have to edit yaml file and then execute apply command once again.


Dry Run:
$ kubectl run demopod --dry-run  --image=nginx
W0909 17:08:34.392782   12400 helpers.go:553] --dry-run is deprecated and can be replaced with --dry-run=client.
pod/demopod created (dry run)



#kubectl diff -f mypod.yml

showing difference in yml file

============

Lables:

kubectl label pod mypod env=uat

Selectors:

ReplicationController

ReplicaSet

Scaling

Deployment

Kubernestes Networking
Types of Services
Persistent Volume
Liveness Probe
ConfigMap
Secrets
Namespaces
Resources
Horizontal Pod Autoscaling
Kubernestes Jobs
Init Container


Statefull and Stateless Application
Deploy Webserver
Scale Webserver
Kubernestes Ingress
Deploy Wordpress Website
Attach Persistant Volume to wordpress site

Helm Chart:





$ kubectl get pods
No resources found in default namespace.
$ kubectl run mypod --image=nginx
pod/mypod created
$ kubectl get pods
NAME    READY   STATUS              RESTARTS   AGE
mypod   0/1     ContainerCreating   0          6s
$ kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
mypod   1/1     Running   0          12s
$ kubectl describe pod mypod
Name:         mypod
Namespace:    default
Priority:     0
Node:         minikube/10.0.0.6
Start Time:   Fri, 09 Sep 2022 16:42:58 +0000
Labels:       run=mypod
Annotations:  <none>
Status:       Running
IP:           172.18.0.3
IPs:
  IP:  172.18.0.3
Containers:
  mypod:
    Container ID:   docker://5f49779cfb23fb29db1c660593fe1ba3de027b9a543282cc5498b3170fcf35fb
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f


Label:
Using metadata tags attached to different resources and objects is a must-have requirement for any Kubernetes (K8s) environment. Kubernetes labels allow DevOps teams to perform in-cluster object searches, apply bulk configuration changes, and more. Labels can help simplify and solve many day-to-day challenges encountered in Kubernetes environments:

Assigning Label to Pod
#kubectl label pod mypod  env=dev

$ kubectl describe pod mypod
Name:         mypod
Namespace:    default
Priority:     0
Node:         minikube/10.0.0.6
Start Time:   Fri, 09 Sep 2022 16:42:58 +0000
Labels:       env=dev
              run=mypod


Override Label:
#kubectl label --overwrite pod mypod env=uat

$ kubectl label --overwrite pod mypod env=uat
pod/mypod labeled

$ kubectl describe pod mypod
Name:         mypod
Namespace:    default
Priority:     0
Node:         minikube/10.0.0.6
Start Time:   Fri, 09 Sep 2022 16:42:58 +0000
Labels:       env=uat
              run=mypod


Remove Label:
$ kubectl label pod mypod env-
pod/mypod labeled
$ kubectl describe pod mypod
Name:         mypod
Namespace:    default
Priority:     0
Node:         minikube/10.0.0.6
Start Time:   Fri, 09 Sep 2022 16:42:58 +0000
Labels:       run=mypod

Assign Label to All Pods in same Namespace:
$ kubectl label pod --all env=dev
pod/mypod labeled
pod/mypod1 labeled


$ kubectl get pods --show-labels
NAME     READY   STATUS    RESTARTS   AGE     LABELS
mypod    1/1     Running   0          13m     env=dev,run=mypod
mypod1   1/1     Running   0          2m33s   env=dev,run=mypod1


================

How to set environment variable

apiVersion: v1
kind: Pod
metadata:
   name: demopod
   labels:
      newlbl: test1
spec:
  containers:
        - name: democpntiner
           image: nginx
           env:
              - name: env_type
                value: dev
             - name: env_loc
               value:  apac
     


Create pod and then check env variable.
#docker container exec -it  container-id env



Run command in POD:

#kubectl  exec  mypod  env
#kubectl  exec mypod -c mycontainer  env  --> if we have multiple container inside pod



Create Multi Container POD:

apiVersion: v1
kind: Pod
metadata:
    name: mypod1
    labels:
       env: dev
spec:
   containers:
           - name: con1
             image: nginx
           - name: con2
             image: ubuntu
             args: [ "sleep", "3600" ]


==================
Login to Container if we have multi container pod
#kubectl exec pod-name -c container-name -it bash




==================
Init Container:


In Kubernetes, we can run more than one container in a Pod, but as a practice, we run only one application container. Along with an application container, we can also run one or more init containers.

Kubernetes init containers run in the same Pod as the main application container, though with a separate life cycle. The pattern is often used to initialize a state or configuration for the application running in the main container.

  • An init container is an additional container in a Pod that completes a task before the "regular" container is started
  • The regular container will only be started once the init container has been started
  • An init container in a Pod must run and complete before any other application containers in the Pod start.
  • This is a great way to initialize a Kubernetes Pod. You can pull any files (keystores, policies, and so forth), configurations, and so on with an init container.
  • Just as with any other application container, we can have more than one init container in a given Pod; but unlike an application container, each init container must run to completion before the next init container starts.

[root@controller ~]# cat pod-init-container.yml
apiVersion: v1
kind: Pod
metadata:
  name: init-container-example-1
spec:
  initContainers:
  - name: sleepy
    image: alpine
    command: ['sleep', '60']
  containers:
  - name: web
    image: nginx


Sidecar Container:
  • Typically, there are two different categories of containers: the container that runs the application and another container that provides helper functionality to the primary application.
  • In the Kubernetes space, the container providing helper functionality is called a sidecar container.
  • Among the most commonly used capabilities of a sidecar container are file synchronization, logging, and watcher capabilities.
  • The sidecars are not part of the main traffic or API of the primary application. They usually operate asynchronously and are not involved in the public API.
  • A great example is a central logging agent. Your main container can just log to stdout, but the sidecar container will send all logs to a central logging service where they will be aggregated with the logs from the entire system.



[root@controller ~]# cat example-1.yaml
apiVersion: v1
kind: Pod
metadata:
  name: sidecar-pod-1
spec:
  volumes:
  - name: log
    emptyDir: {}

  containers:
  - image: busybox
    name: application
    args:
     - /bin/sh
     - -c
     - >
      while true; do
        echo "$(date) INFO hello" >> /var/log/myapp.log ;
        sleep 1;
      done
    volumeMounts:
    - name: log
      mountPath: /var/log

  - name: sidecar
    image: busybox
    args:
     - /bin/sh
     - -c
     - tail -fn+1 /var/log/myapp.log
    volumeMounts:
    - name: log
      mountPath: /var/log
======================






===============


$ kubectl --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create        Create a resource from a file or from stdin.
  expose        Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
  run           Run a particular image on the cluster
  set           Set specific features on objects

Basic Commands (Intermediate):
  explain       Documentation of resources
  get           Display one or many resources
  edit          Edit a resource on the server
  delete        Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout       Manage the rollout of a resource
  scale         Set a new size for a Deployment, ReplicaSet or Replication Controller
  autoscale     Auto-scale a Deployment, ReplicaSet, or ReplicationController

Cluster Management Commands:
  certificate   Modify certificate resources.
  cluster-info  Display cluster info
  top           Display Resource (CPU/Memory/Storage) usage.
  cordon        Mark node as unschedulable
  uncordon      Mark node as schedulable
  drain         Drain node in preparation for maintenance
  taint         Update the taints on one or more nodes

Troubleshooting and Debugging Commands:
  describe      Show details of a specific resource or group of resources
  logs          Print the logs for a container in a pod
  attach        Attach to a running container
  exec          Execute a command in a container
  port-forward  Forward one or more local ports to a pod
  proxy         Run a proxy to the Kubernetes API server
  cp            Copy files and directories to and from containers.
  auth          Inspect authorization
  debug         Create debugging sessions for troubleshooting workloads and nodes

Advanced Commands:
  diff          Diff live version against would-be applied version
  apply         Apply a configuration to a resource by filename or stdin
  patch         Update field(s) of a resource
  replace       Replace a resource by filename or stdin
  wait          Experimental: Wait for a specific condition on one or many resources.
  kustomize     Build a kustomization target from a directory or a remote url.

Settings Commands:
  label         Update the labels on a resource
  annotate      Update the annotations on a resource
  completion    Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  api-resources Print the supported API resources on the server
  api-versions  Print the supported API versions on the server, in the form of "group/version"
  config        Modify kubeconfig files
  plugin        Provides utilities for interacting with plugins.
  version       Print the client and server version information


Important Blogs:

Kubernetes Create Pod using Kubectl and YAML Tutorial (progressivecoder.com)


Create Kubernestes POD using YAML file:

Create A Pod In Kubernetes Cluster | by Bharathiraja | CodeX | Medium


Secret:

Pull an Image from a Private Registry | Kubernetes


No comments:

Post a Comment

Sample Game App Deployment on EKS cluster

 https://padmakshi.medium.com/setting-up-an-eks-cluster-and-deploying-a-game-application-a-step-by-step-guide-08790e0be117