Pods are the smallest deployable units of computing that can be created and managed in Kubernetes.
Overview
At the end of this module, you will :
Learn the format of a YAML file
Learn how to manage a Pods
Learn how to manage containers
Prerequisites
Create the directory data/pods in your home folder to manage the YAML file needed in this module.
mkdir~/data/pods
Run
The run command creates a Pod based on the parameters specified, such as the image or the environment variables. This deployment is issued to the Kubernetes master which launches the Pods and containers required. Kubectl run is similar to docker run but at a cluster level.
In imperative object configuration, the kubectl command specifies the operation (create, replace, etc.), optional flags and at least one file name. The file specified must contain a full definition of the object in YAML or JSON format.
The create command create a resources based on the imperative declaration (command line or YAML file).
Exercise n°1
Create a pod that contain a single nginx container with a simple YAML file.
The file created in this exercise will be reused, do not delete it.
When using declarative object configuration, a user operates on object configuration files stored locally, however the user does not define the operations to be taken on the files. Create, update, and delete operations are automatically detected per-object by kubectl. This enables working on directories, where different operations might be needed for different objects.
The apply command manage the status of resources in the Kubernetes cluster. It can create, update and delete resources based on one or more YAML files.
Exercise n°1
Update the image version of the previous nginx pods.
The get command list the object asked. It could be a single object or a list of multiple objects comma separated. This command is useful to get the status of each object. The output can be formatted to only display some information based on some json search or external tools like tr, sort, uniq.
The default output display some useful information about each services :
Name : the name of the newly created resource
Ready : the amount of container ready in the Pods
Status : the deployment status
Restarts : the count that the Pods has restarted from his creation
Once an application is running, it is inevitably a need to debug problems or check the configuration deployed.
The logs command display the stdout and stderr logs of each container in a pod. The containers within a Pod must be started to get information otherwise nothing will be displayed.
This command is really useful to debug a container deployed in a Pod.
Exercise n°1
Create a new Pods that send a message in stdout.
~/data/pods/04_pods.yaml
apiVersion:v1kind:Podmetadata:name:busybox-logsspec:containers: - name:busyboximage:busyboxcommand: ["/bin/sh"]args: ["-c","echo \"$(date) - INFO - My first logs output on $(hostname)\""]restartPolicy:Never
Create the resource based on the previous yaml file definition.
kubectlcreate-f~/data/pods/04_pods.yaml
Get the logs of the busybox-logs Pod created previously.
Once an application is running, it is inevitably a need to debug problems or check the configuration deployed.
The describe command display a lot of configuration information about the container(s) and Pod (labels, resource requirements, etc.) or any other Kubernetes objects, as well as status information about the container(s) and Pod (state, readiness, restart count, events, etc.).
This command is really useful to introspect and debug a container deployed in a Pod.
Exercise n°1
Get the information of the pod busybox deployed on the default namespace.
kubectldescribepobusybox
Name:busyboxNamespace:defaultPriority:0PriorityClassName:<none>Node:minikube/10.0.2.15StartTime:Wed,13Feb201912:45:52-0500Labels:run=busyboxAnnotations:<none>Status:SucceededIP:172.17.0.7Containers:busybox:ContainerID:docker://5a3892c9be87e3f15e752f99d127d6d84525d1a29f3a5bb1b11713a3ae373eb1Image:busyboxImageID:docker-pullable://busybox@sha256:7964ad52e396a6e045c39b5a44438424ac52e12e4d5a25d94895f2058cb863a0Port:<none>HostPort:<none>State:TerminatedReason:CompletedExitCode:0Started:Wed,13Feb201912:45:55-0500Finished:Wed,13Feb201912:45:55-0500Ready:FalseRestartCount:0Environment:<none>Mounts:/var/run/secrets/kubernetes.io/serviceaccountfromdefault-token-wpxhp (ro)Conditions:TypeStatusInitializedTrueReadyFalseContainersReadyFalsePodScheduledTrueVolumes:default-token-wpxhp:Type:Secret (a volumepopulatedbyaSecret)SecretName:default-token-wpxhpOptional:falseQoSClass:BestEffortNode-Selectors:<none>Tolerations:node.kubernetes.io/not-ready:NoExecutefor300snode.kubernetes.io/unreachable:NoExecutefor300sEvents:TypeReasonAgeFromMessage-------------------------NormalScheduled18mdefault-schedulerSuccessfullyassigneddefault/busyboxtominikubeNormalPulling18mkubelet,minikubepullingimage"busybox"NormalPulled18mkubelet,minikubeSuccessfullypulledimage"busybox"NormalCreated18mkubelet,minikubeCreatedcontainerNormalStarted18mkubelet,minikubeStartedcontainer
Exec
Execute a command in a container is sometimes needed for debug or development purpose.
The exec command manage the SSH connection to a container deployed in a Pod.
Usually, the format is : kubectl exec -it POD_NAME -c CONTAINER_NAME
Exercise n°1
Connect to the pod my-single-app in the namespace default.
kubectlexec-itmy-single-appbash
Exit the container with this command.
exit
Exercise n°2
Connect to the postgres container in the my-multi-app pod in the namespace default.
Sometimes it’s necessary to make narrow, non-disruptive updates to resources created. It is suggested to maintain a set of configuration files in source control, so that they can be maintained and versioned along with the code for the resources they configure. But sometimes for debug and development purpose, it could be useful to directly manage a Kubernetes object deployed in a cluster in real time.
The edit command allows to directly edit any API resource retrieve via the command line tools. It will open the editor defined by your KUBE _EDITOR, or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. Multiple objects can edit, although changes are applied one at a time.
Exercise n°1
Edit the my-single-app pods to update the image.
KUBE_EDITOR="nano"kubectleditpodsmy-single-app
Explain
Kubernetes come with a lot of documentation about his objects and the available options in each one. Those information can be find easily in command line or in the official Kubernetes documentation.
The explain command allows to directly ask the API resource via the command line tools to display information about each Kubernetes objects and their architecture.
Exercise n°1
Get the documentation of a specific field of a resource.
kubectlexplainpods.spec
KIND:PodVERSION:v1RESOURCE:spec<Object>DESCRIPTION:Specificationofthedesiredbehaviorofthepod.Moreinfo:https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-statusPodSpecisadescriptionofapod.FIELDS:activeDeadlineSeconds<integer>OptionaldurationinsecondsthepodmaybeactiveonthenoderelativetoStartTimebeforethesystemwillactivelytrytomarkitfailedandkillassociatedcontainers.Valuemustbeapositiveinteger.affinity<Object>Ifspecified,thepod's scheduling constraints automountServiceAccountToken <boolean> AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. containers <[]Object> -required- List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. dnsConfig <Object> Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy. dnsPolicy <string> Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'. enableServiceLinks <boolean> EnableServiceLinks indicates whether information about services should be injected into pod'senvironmentvariables,matchingthesyntaxofDockerlinks.hostAliases<[]Object>HostAliasesisanoptionallistofhostsandIPsthatwillbeinjectedintothepod's hosts file if specified. This is only valid for non-hostNetwork pods. hostIPC <boolean> Use the host'sipcnamespace.Optional:Defaulttofalse.hostNetwork<boolean>Hostnetworkingrequestedforthispod.Usethehost's network namespace. If this option is set, the ports that will be used must be specified. Default to false. hostPID <boolean> Use the host'spidnamespace.Optional:Defaulttofalse.hostname<string>SpecifiesthehostnameofthePodIfnotspecified,thepod's hostname will be set to a system-defined value. imagePullSecrets <[]Object> ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod initContainers <[]Object> List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, or Liveness probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ nodeName <string> NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements. nodeSelector <map[string]string> NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node'slabelsforthepodtobescheduledonthatnode.Moreinfo:https://kubernetes.io/docs/concepts/configuration/assign-pod-node/priority<integer>Thepriorityvalue.Varioussystemcomponentsusethisfieldtofindthepriorityofthepod.WhenPriorityAdmissionControllerisenabled,itpreventsusersfromsettingthisfield.TheadmissioncontrollerpopulatesthisfieldfromPriorityClassName.Thehigherthevalue,thehigherthepriority.priorityClassName<string>Ifspecified,indicatesthepod's priority. "system-node-critical" and "system-cluster-critical" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default. readinessGates <[]Object> If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to "True" More info: https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%!B(MISSING)%!B(MISSING).md restartPolicy <string> Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy runtimeClassName <string> RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md This is an alpha feature and may change in the future. schedulerName <string> If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler. securityContext <Object> SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field. serviceAccount <string> DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead. serviceAccountName <string> ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ shareProcessNamespace <boolean> Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false. This field is beta-level and may be disabled with the PodShareProcessNamespace feature. subdomain <string> If specified, the fully qualified Pod hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not specified, the pod will not have a domainname at all. terminationGracePeriodSeconds <integer> Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds. tolerations <[]Object> If specified, the pod'stolerations.volumes<[]Object>Listofvolumesthatcanbemountedbycontainersbelongingtothepod.Moreinfo:https://kubernetes.io/docs/concepts/storage/volumes
Add the --recursive flag to display all of the fields at once without descriptions.
Delete
The delete command delete resources by filenames, stdin, resources and names, or by resources and label selector.
Some resources, such as pods, support graceful deletion. These resources define a default period before they are forcibly terminated (the grace period) but you may override that value with the --grace-period flag, or pass --now to set a grace-period of 1.
Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right when you submit a delete, their update will be lost along with the rest of the resource.
Exercise n°1
Delete the busybox pod deployed previously in the default namespace.
kubectldeletepodsbusybox-ndefault
Exercise n°2
Delete the nginx pod deployed previously in the default namespace with declarative method.
kubectldelete-f~/data/pods
Module exercise
The purpose of this section is to manage each steps of the lifecycle of an application to better understand each concepts of the Kubernetes course.
The main objective in this module is to deploy the Voting App Pods in his dedicated namespace.
For more information about the application used all along the course, please refer to the Exercise App > Voting App link in the left panel.
Based on the principles explain in this module, try by your own to handle this steps. The development of a yaml file is recommended.
The file developed has to be stored in this directory : ~/data/votingapp/01_pods
Deploy each containers of the Voting App in a single Pod called voting-app in his dedicated namespace created in the previous module.
Ensure the Pods are up and running
Check the logs of each Pods
Yaml file definition to deploy the Voting App containers.
Kubectl command to deploy the Pods based on the previous definition file.
kubectlcreate-f~/data/votingapp/01_pods/pods.yaml
Ensure the Pods are created.
kubectlgetpods-nvoting-app
Check the logs of each Pods to ensure the main process is running.
# Get the database logskubectllogsdb-nvoting-app# Get the queue logskubectllogsredis-nvoting-app# Get the result logskubectllogsresult-nvoting-app# Get the vote logskubectllogsvote-nvoting-app# Get the worker logskubectllogsworker-nvoting-app
External documentation
Those documentations can help you to go further in this topic :