Tuesday, 4 August 2020

Kubernetes: kubectl explain: Get documentation about resources

‘kubectl explain {resource}’ command is used to get documentation about the resource.

 

Example

kubectl explain Pod

kubectl explain Deployment

$kubectl explain Deployment
KIND:     Deployment
VERSION:  apps/v1

DESCRIPTION:
     Deployment enables declarative updates for Pods and ReplicaSets.

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 metadata.

   spec	<Object>
     Specification of the desired behavior of the Deployment.

   status	<Object>
     Most recently observed status of the Deployment.

If you want to know about the spec property, use '.' operator like below.

 

kubectl explain Deployment.spec

$kubectl explain Deployment.spec
KIND:     Deployment
VERSION:  apps/v1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of the Deployment.

     DeploymentSpec is the specification of the desired behavior of the
     Deployment.

FIELDS:
   minReadySeconds	<integer>
     Minimum number of seconds for which a newly created pod should be ready
     without any of its container crashing, for it to be considered available.
     Defaults to 0 (pod will be considered available as soon as it is ready)

   paused	<boolean>
     Indicates that the deployment is paused.

   progressDeadlineSeconds	<integer>
     The maximum time in seconds for a deployment to make progress before it is
     considered to be failed. The deployment controller will continue to process
     failed deployments and a condition with a ProgressDeadlineExceeded reason
     will be surfaced in the deployment status. Note that progress will not be
     estimated during the time a deployment is paused. Defaults to 600s.

   replicas	<integer>
     Number of desired pods. This is a pointer to distinguish between explicit
     zero and not specified. Defaults to 1.

   revisionHistoryLimit	<integer>
     The number of old ReplicaSets to retain to allow rollback. This is a
     pointer to distinguish between explicit zero and not specified. Defaults to
     10.

   selector	<Object> -required-
     Label selector for pods. Existing ReplicaSets whose pods are selected by
     this will be the ones affected by this deployment. It must match the pod
     template's labels.

   strategy	<Object>
     The deployment strategy to use to replace existing pods with new ones.

   template	<Object> -required-
     Template describes the pods that will be created.

If you want to know about the ‘selector’ property of ‘spec’ use below command.

kubectl explain Deployment.spec.selector




Previous                                                    Next                                                    Home

Kubernetes: Print the supported API versions on the server

‘kubectl api-versions’ command print all the supported API versions on the server.

$kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1




Previous                                                    Next                                                    Home

Kubernetes: Print the supported API resources on the server

‘kubectl api-resources’ command print all the supported API resources on the server.

$kubectl api-resources
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
ingressclasses                                 networking.k8s.io              false        IngressClass
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment





Previous                                                    Next                                                    Home

Kubernetes: Secrets

Secrets are a special type of volume used to store Application Sensitive Information like password, Authentication tokens etc.,.

 

Are the secrets encrypted?

No, Secrets are not encrypted. They are encoded using the Base64 Encoding scheme.

 

Secrets types

a. docker-registry: Used to connect to a Docker Registry.

 

b. TLS: Create a TLS Secret.

 

c. generic: Create a secret from local file, directory or literal value.

 

How to create secrets?

Creation of secret almost similar to the creation of configmaps.

 

You can create a secret from file or using literal values.

 

Let’s create a file 'token' with the below information.

 

token

AAAAASSSSSSSAsw1111112222343fsafklsjfkdjkhsjhajhvaua!!!QWER

 

Let’s create a secret of type ‘generic’ and name ‘user-service-secret’ by executing the below command.

 

kubectl create secret generic user-service-secret --from-file=authToken=./token --from-literal=password=pasd5432s123

$kubectl create secret generic user-service-secret --from-file=authToken=./token --from-literal=password=pasd5432s123
secret/user-service-secret created

Let’s query secrets by executing the below command.

$kubectl get secrets
NAME                  TYPE                                  DATA   AGE
default-token-w7rp7   kubernetes.io/service-account-token   3      33d
user-service-secret   Opaque                                2      101s

As you see the output, secret with the name ‘user-service-secret’ is created.

 

Using ‘-o yaml’ option, you can see the content of secret (but in base64 encoded form).

$kubectl get secret user-service-secret -o yaml
apiVersion: v1
data:
  authToken: QUFBQUFTU1NTU1NTQXN3MTExMTExMjIyMjM0M2ZzYWZrbHNqZmtkamtoc2poYWpodmF1YSEhIVFXRVIK
  password: cGFzZDU0MzJzMTIz
kind: Secret
metadata:
  creationTimestamp: "2020-06-08T15:17:59Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:authToken: {}
        f:password: {}
      f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-06-08T15:17:59Z"
  name: user-service-secret
  namespace: default
  resourceVersion: "337591"
  selfLink: /api/v1/namespaces/default/secrets/user-service-secret
  uid: 23110053-dd1c-4798-a7e8-987f226b5b0c
type: Opaque

You can decode the encoded string using the base64 command.

$echo cGFzZDU0MzJzMTIz | base64 -D
pasd5432s123

How to read secrets?

You can read secrets in two ways.

a.   Using Environment Variables.

b.   Mounted as Volumes

 

secretsDemo.yml

apiVersion: v1
kind: Pod
metadata:
  name: secrets-demo-pod1
  labels:
    app: user-service
    author: krishna
    serviceType: desktop
spec:
  containers:
    - name: user-service
      image: jboss/wildfly
      volumeMounts:
      - mountPath: /etc/secrets
        name: service-secrets

  volumes:
  - name: service-secrets
    secret:
      secretName: user-service-secret

$kubectl create -f secretsDemo.yml 
pod/secrets-demo-pod1 created

Let’s login to the container and check whether secrets mounted or not.

 

kubectl exec -it secrets-demo-pod1 -c user-service -- /bin/bash

$kubectl exec -it secrets-demo-pod1 -c user-service -- /bin/bash
[jboss@secrets-demo-pod1 ~]$ 
[jboss@secrets-demo-pod1 ~]$ ls /etc/secrets/
authToken  password

As you see the output, each secret is mounted as a file. File content has the actual value.

[jboss@secrets-demo-pod1 ~]$ cat /etc/secrets/authToken 
AAAAASSSSSSSAsw1111112222343fsafklsjfkdjkhsjhajhvaua!!!QWER
[jboss@secrets-demo-pod1 ~]$ 
[jboss@secrets-demo-pod1 ~]$ cat /etc/secrets/password  
pasd5432s123

Reading secrets as environment Variables

You can even read secrets as environment variables.

 

secretsDemo2.yml

apiVersion: v1
kind: Pod
metadata:
  name: secrets-demo-pod2
  labels:
    app: user-service
    author: krishna
    serviceType: desktop
spec:
  containers:
    - name: user-service
      image: busybox
      command: ["/bin/sh", "-c", "env"]
      envFrom:
        - secretRef:
            name: user-service-secret

Create Pod using the above definition file.

$kubectl create -f secretsDemo2.yml 
pod/secrets-demo-pod2 created

Check the logs to confirm that secrets available in environment variables.

$kubectl logs secrets-demo-pod2
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT=tcp://10.96.0.1:443
authToken=AAAAASSSSSSSAsw1111112222343fsafklsjfkdjkhsjhajhvaua!!!QWER

HOSTNAME=secrets-demo-pod2
SHLVL=1
HOME=/root
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
password=pasd5432s123
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/
$

Note

a.   If you want to create a secret using YAML definition file, you must encode the secret before putting it. Kubernetes do not encode the secret if you create via yaml definition file.




Previous                                                    Next                                                    Home

Kubernetes: ConfigMaps

ConfigMap is a special type of volume used to store the Application Configurations. ConfigMaps must be created before a Pod using them.

 

Using ConfigMap,

a.   We can make the variables available within a Pod.

b.   ConfigMap can be mount to a location, where the application can read. When you mount ConfigMap as a volume, at the mount point, files will be created with the name of key, and file content has the value.

c.    It can be used to provide command-line arguments.

 

ConfigMaps can be created from multiple sources.

a.   Directories

b.   Files

c.    Literal Values

 

Demo 1: Create ConfigMap from a file

Step 1: Create a file ‘appConfigurations’ with the below content.

 

appConfigurations

appName=Chat-Server
version=1.23.4

Step 2: Let's create a ConfigMap using the contents of the file ‘appConfigurations’.

kubectl create cm chat-server-config-map --from-file=appConfigurations

 

Above statement creates a configmap with the name ‘chat-server-config-map’.

$kubectl create cm chat-server-config-map --from-file=appConfigurations
configmap/chat-server-config-map created

You can query config maps to confirm that ‘chat-server-config-map’ is created.

$kubectl get cm
NAME                     DATA   AGE
chat-server-config-map   1      36s

You can see the content of configMap using ‘kubectl describe’ command.

$kubectl describe cm chat-server-config-map
Name:         chat-server-config-map
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
appConfigurations:
----
appName=Chat-Server
version=1.23.4

Events:  <none>

Step 3: Let’s create a Pod that uses this configMap ‘chat-server-config-map’.

$kubectl create -f configMapDemo1.yml 
pod/configmap-demo-pod1 created

Query Pods.

$kubectl get pods
NAME                  READY   STATUS      RESTARTS   AGE
configmap-demo-pod1   0/1     Completed   0          9s

Let’s see what is printed by the Pod ‘configmap-demo-pod1’.

$kubectl logs configmap-demo-pod1
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT=443
appConfigurations=appName=Chat-Server
version=1.23.4

HOSTNAME=configmap-demo-pod1
SHLVL=1
HOME=/root
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/

You can see that the keys ‘appName’ and ‘version’ are printed to console.

 

Demo 2: Creating ConfigMap using literal values

Below statement create a config map using literal values.

kubectl create cm chat-bot-configs --from-literal=version=1.234 --from-literal=appName=ChatBot

$kubectl create cm chat-bot-configs --from-literal=version=1.234 --from-literal=appName=ChatBot
configmap/chat-bot-configs created

Let’s query config maps to confirm ‘chat-bot-configs’ is created.

$kubectl get cm
NAME                     DATA   AGE
chat-bot-configs         2      4s
chat-server-config-map   1      14m

You can get the content of configmap using ‘kubectl describe’ command.

$kubectl describe cm chat-bot-configs
Name:         chat-bot-configs
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
appName:
----
ChatBot
version:
----
1.234
Events:  <none>

You can even view the content of configmap in YAML format like below.

$kubectl get cm chat-bot-configs -o yaml
apiVersion: v1
data:
  appName: ChatBot
  version: "1.234"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-06-08T10:58:28Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:appName: {}
        f:version: {}
    manager: kubectl
    operation: Update
    time: "2020-06-08T10:58:28Z"
  name: chat-bot-configs
  namespace: default
  resourceVersion: "325135"
  selfLink: /api/v1/namespaces/default/configmaps/chat-bot-configs
  uid: e5365462-178b-411c-bb47-21fab1e1b122

Demo 3: Populate a volume with the data stored in configmap.

 

Let’s create a configuration file.

document-storage-configs.conf

version=1.23
downSync=30
upSync=1
fullSync=120

Create a ConfigMap from the above configuration file.

kubectl create cm document-storage-configmap --from-file=document-storage-configs.conf

$kubectl create cm document-storage-configmap --from-file=document-storage-configs.conf
configmap/document-storage-configmap created

Query ConfigMaps to confirm.

$kubectl get cm
NAME                         DATA   AGE
chat-bot-configs             2      52m
chat-server-config-map       1      66m
document-storage-configmap   1      3s

Let’s create a Pod that mounts this configMap as a file.

 

configMapDemo2.yml

apiVersion: v1
kind: Pod
metadata:
  name: configmap-demo-pod2
  labels:
    app: document-storage
    author: krishna
    serviceType: desktop
spec:
  containers:
    - name: document-storage
      image: jboss/wildfly
      volumeMounts:
      - name: conf
        mountPath: /app/configs 
  volumes:
  - name: conf
    configMap:
      name: document-storage-configmap
      items:
      - key: document-storage-configs.conf
        path: document-storage-configs

Create Pod using the above definition file.

$kubectl create -f configMapDemo2.yml
pod/configmap-demo-pod2 created

Now, login to the container by executing the below command.

kubectl exec -it configmap-demo-pod2 -c document-storage -- /bin/bash

 

You can see that configuration file is located at location /app/configs

cat /app/configs/document-storage-configs

$kubectl exec -it configmap-demo-pod2 -c document-storage -- /bin/bash
[jboss@configmap-demo-pod2 ~]$ 
[jboss@configmap-demo-pod2 ~]$ cat /app/configs/document-storage-configs 
version=1.23
downSync=30
upSync=1
fullSync=120





Previous                                                    Next                                                    Home

Kubernetes: Configure PV Storage

Persistent Volume (PV) object is used to connect to external storage.

 

Step 1: Create a Persistent Volume.

 

persistedVolume.yml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: my-pv
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/pv1-data"

Create a Persisted volume using the above definition file.

$kubectl create -f persistedVolume.yml 
persistentvolume/my-pv created

Query all the persisted volumes.

$kubectl get pv
NAME    CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
my-pv   5Gi        RWO            Retain           Available                                   9s

From the above output, it is confirmed that the Persisted Volume ‘my-pv’ is created.

 

Step 2: Configuring PVC (Persistent Volume Claim).

 

Using Persistent Volume Claim, we can request access to Persistent Volume.

 

persistentVolumeClaim.yml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 2Gi

Let’s create a Persistent Volume Claim using the above definition file by executing the below command.

 

kubectl create -f persistentVolumeClaim.yml

$kubectl create -f persistentVolumeClaim.yml 
persistentvolumeclaim/my-pvc created

Query Persistent Volumes.

$kubectl get pvc
NAME     STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
my-pvc   Bound    pvc-0f55016a-c661-40b4-88f7-1ceade1bdb97   2Gi        RWO            standard       59s

Step 3: Let’s create a Pod with two containers that use this PV.

 

podPvDemo.yml

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: hello-world
    author: krishna
    serviceType: user-service
spec:
  volumes:
    - name: pv-storage
      persistentVolumeClaim:
        claimName: my-pvc
  containers:
    - name: container1
      image: busybox
      command:
        - sleep 
        - "300"
      volumeMounts:
        - mountPath: /container1-mount
          name: pv-storage

‘spec.containers.volumeMounts.name’ refers to the ‘claimName’ of matched ‘spec.volumes.name’.

 

Let’s create a pod using the above definition file.

$kubectl create -f podPvDemo.yml 
pod/my-pod created

Let’s create a file in the mounted path.

kubectl exec -it my-pod -c container1 -- touch /container1-mount/hello.txt

 

Let’s list the files in the mounted path.

$kubectl exec -it my-pod -c container1 -- ls -l /container1-mount
total 0
-rw-r--r--    1 root     root             0 Jun  8 10:19 hello.txt

Let’s delete the pod.

$kubectl delete pod my-pod
pod "my-pod" deleted

Query the pods to confirm the Pod is deleted.

$kubectl get pods
No resources found in default namespace.

Let’s recreate the pod again.

$kubectl create -f podPvDemo.yml 
pod/my-pod created

Let’s list the files at path ‘/container1-mount’ to make sure that the file ‘hello.txt’ is persisted.

$kubectl exec -it my-pod -c container1 -- ls -l /container1-mount
total 0
-rw-r--r--    1 root     root             0 Jun  8 10:19 hello.txt

Previous                                                    Next                                                    Home

Kubernetes: Storage Options

If you store any data in a container/Pod the data is available until the container/Pod live. Once Container/Pod deleted, crashed, restarted you will lose the data.

 

If a Pod encapsulates multiple containers, there may be a need to share data across containers.

 

To solve this problem, Kubernetes come up with different storage options.

a.   Pod Volumes: Used to allocate storage outside of the container

b.   Persistent Volume (PV): Using this, Pods can connect to external storage. Persistent Volume claims (PVC) are used to request access to a specified storage.

c.    ConfigMaps: Using this Pods can connect to Configuration files and variables.

 

How to define a Volume that is available to Pod?

Define the volume in spec.volumes.

 

How to mount a volume to the container?

Containers can mount the volume using spec.containers.volumeMounts property.

 

Volume Types

At the time of writing this post, Kubernetes support the following volume types.

 

a.   awsElasticBlockStore

b.   azureDisk

c.    azureFile

d.   cephfs

e.   cinder

f.     configMap

g.   csi

h.   downwardAPI

i.     emptyDir

j.     fc (fibre channel)

k.    flexVolume

l.     flocker

m. gcePersistentDisk

n.   gitRepo (deprecated)

o.   glusterfs

p.   hostPath

q.   iscsi

r.     local

s.    nfs

t.     persistentVolumeClaim

u.   projected

v.    portworxVolume

w.  quobyte

x.    rbd

y.    scaleIO

z.    secret, storageos and vsphereVolume.

 

In this post, I am going to show the demo using ‘emptyDir’ volume type.

 

An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node. Containers in the Pod can read and write the same files in the emptyDir volume, though that volume can be mounted at the same or different paths in each Container.

 

What will happen when a Pod deleted from the node?

Data in emptyDir will be deleted forever.

 

Let’s create a Pod with two containers and mount a volume that is shared across the containers.

 

Step 1: Create a Pod.

 

podVolumesDemo.yml

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: hello-world
    author: krishna
    serviceType: user-service
spec:
  containers:
    - name: container1
      image: busybox
      command:
        - sleep 
        - "300"
      volumeMounts:
        - mountPath: /container1-mount
          name: my-volume
    - name: container2
      image: busybox
      command:
        - sleep
        - "300"
      volumeMounts:
        - mountPath: /container2-mount
          name: my-volume
  volumes:
  - name: my-volume
    emptyDir: {}

Create Pod by executing the below command.

$kubectl create -f podVolumesDemo.yml 
pod/my-pod created

Query all the pods.

$kubectl get pods
NAME     READY   STATUS    RESTARTS   AGE
my-pod   2/2     Running   0          77s

Step 2: Create some files in the mounted volume of container1 and make sure that these are available to container2.

 

Let’s create two files (hello.txt, demo.ppt) in the mounted directory.

 

kubectl exec -it my-pod -c container1 -- touch /container1-mount/hello.txt

kubectl exec -it my-pod -c container1 -- touch /container1-mount/demo.ppt

 

Let's confirm that the two files are available to container2

kubectl exec -it my-pod -c container2 -- ls -l /container2-mount

$kubectl exec -it my-pod -c container1 -- touch /container1-mount/hello.txt
$
$kubectl exec -it my-pod -c container1 -- touch /container1-mount/demo.ppt
$
$kubectl exec -it my-pod -c container2 -- ls -l /container2-mount
total 0
-rw-r--r--    1 root     root             0 Jun  8 09:15 demo.ppt
-rw-r--r--    1 root     root             0 Jun  8 09:15 hello.txt

You can delete the pod by executing the below command.

kubectl delete pod my-pod

$kubectl delete pod my-pod
pod "my-pod" deleted


Previous                                                    Next                                                    Home