Understand kubectl to manage Kubernetes objects

kubernetesresourcesUse kubectlto interact with Kubernetes resources, such as Pod, Services, Volumes, and more. When you use kubectl commands, you are querying or setting the desired state of the cluster. kubectlis calling into the API and manipulating or getting status from the primitives.

In this post, learn about the important resources that developers use and how you go about getting information about and creating a resource using kubectl.

Understand Kubernetes objects

Kubernetes objects are persistent entities. Kubernetes uses these entities to represent the state of your cluster. Specifically, they can describe:

  • Which containerized applications are running (and on which nodes)
  • The resources available to those applications
  • The policies around how those applications behave, such as restart policies, upgrades, and fault-tolerance

A Kubernetes object is a record of intent. Once you create the object, the Kubernetes system will constantly work to ensure that object exists.

In this article, learn about the important Kubernetes objects for developers and the commands you use to create and object and get its status.

The following diagram from Kenichi Shibata‘s post Discovering the basics of Kubectl shows how kubectl interacts with the Kubernetes resources.

kubectl_resources

Introducing important Kubernetes objects

This section defines the important objects and provides pointers into the Kubernetes documentation on where you can learn more.

Pod

Use Kubernetes to manage Docker container images in Pods. However, images themselves are not one of the resources inside Kubernetes, rather they are contained inside of a Pod.

The Pod is a basic building block of Kubernetes. Single-container Pods are used to reduce coupling as much as possible. Multi-container pods can be deployed for cohesive processes. Multi-container Pods are faster since they share the same user-space. Management in Kubernetes is done on the Pod, not the container. Use Deployment when you want to provide updates to Pods and ReplicaSets.

Usually you don’t need to create Pods directly, even for singleton Pods. Instead, create them using workload resources such as Deployment or Job. If your Pods need to track state, consider the StatefulSet resource. For more information, see Using Pods.

Controllers, Jobs

Controllers are control loops that monitor the state of the cluster. They maintain and bring the cluster to the desired state. All controllers are separate, but and compiled into a single binary. Deployment, ReplicaSet, and NodeController are examples of Controllers.

A Job is a controller that creates one or more Pods and ensures that a specified number of them successfully terminate.

Services

Services provide a layer of abstraction over Pods. The abstraction defines a policy to access the Pods. Services load balance the requests across a set of Pods.

Volumes

Containers are ephemeral so once the container crashes, all data is lost. Volumes provide the storage structure which can be attached to a Pod. Lifecycle of a Volume can be bound to a Pod. Volumes help restore stopped and unavailable containers to a previous state.

ConfigMaps, Secrets

ConfigMaps are for non-confidential data. Secretes are for confidential data. Configure applications externally using ConfigMaps and Secrets.

You pass sensitive information without hardcoding it into the container specification.

Deployment

A Deployment provides declarative updates for Pods and ReplicaSets. Use Deployment to define the transition from the current environment to the desired state. Deploys a replication controller or a ReplicaSet to further deploy the Pods. Use Deployment to roll out updates to the application. Rollbacks are possible.

ReplicaSet

Stable set of Pods running. A ReplicaSet ensures that a specified number of pod replicas are running at any given time. You may never need to manipulate ReplicaSet objects: use a Deployment instead.

StatefulSet

StatefulSet is a ReplicaSet, but for stateful applications. Maintains uniqueness of each pods across deployments and scalin operations. Requires a headless service.

Basic kubectl commands

There are several essential commands that you use over and over with kubectl.

First create a cluster, then sign into your cluster. In Azure use the following command:

az aks get-credentials –resource-group $RESOURCE_GROUP_NAME –name $AKS_NAME
view raw sign-into-aks.sh hosted with ❤ by GitHub

The current cluster attached to the kubectl can be viewed using kubectl config view. The config view is stored in a file on your development computer under in ~/.kube/config.

Get information about kubectl

Get the list of resources using kubectl get-resources. This command lists the resources that are available in Kubernetes.

Get the list of current versions of the resources using kubectl api-versions. The supported API versions to identify because you specify the API version when you use YAML files to create objects.

Get

Use the kubectl get command to return the state of objects. The following Gist shows some examples of you can use various parameters to return information about the resource state.

kubectl get services # List all services in the namespace
kubectl get pods –all-namespaces # List all pods in all namespaces
kubectl get pods -o wide # List all pods in the current namespace, with more details
kubectl get deployment my-dep # List a particular deployment
kubectl get pods # List all pods in the namespace
kubectl get pod my-pod -o yaml # Get a pod's YAML
view raw kubectl-get.sh hosted with ❤ by GitHub

Use the -o wide parameter to retrieve more information about the resource. Or use -o yaml to return the YAML representation of the resource.

For more information, see kubectl commands get.

Use the -n parameter on kubectl get to specify a namespace. Namespaces are used to group sets of resources together. For example, you get the list of system Pods using kubectl get pods -n kube-system. To get the list of Pods that are running and their IP address, use kubectl get pods -n kube-system -o wide. In larger projects use namespaces to provide access rights to sets of objects.

Describe

To get a full description of the object, use kubectl describe. The reply includes related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector.

For example, kubectl describe pod my-nginx returns the information about the Pod named my-nginx.

For more information, see kubectl commands describe.

Apply vs Create

kubectl apply and kubectl create are two different approaches to create resources in Kubernetes cluster environment.

kubectl apply manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster. This is the recommended way of managing Kubernetes applications in production.

apply – makes incremental changes to an existing object by defining the desired state of the object.  create creates a whole new object (previously non-existing or deleted) and will fail if the object already exists.

The following example shows several ways to use apply.

kubectl apply -f ./my-manifest.yaml # create resource(s)
kubectl apply -f ./my1.yaml -f ./my2.yaml # create from multiple files
kubectl apply -f ./dir # create resource(s) in all manifest files in dir
view raw kubectl-apply.sh hosted with ❤ by GitHub

The object descriptions in YAML files can be actual files or provided using STDIN. The following example shows an example how you can create several resources.

# Create multiple YAML objects from stdin
cat <<EOF | kubectl apply -f –
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep
spec:
containers:
– name: busybox
image: busybox
args:
– sleep
– "1000000"
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep-less
spec:
containers:
– name: busybox
image: busybox
args:
– sleep
– "1000"
EOF

Busybox combines tiny versions of many common UNIX utilities into a single small executable.

For more information, see kubectl apply vs create: Which One to Use for Creating Resources in Kubernetes Cluster Environment?

For more information, see kubectl commands create and kubectl commands apply .

Create with a dry run

You can use kubectl create to create the YAML for you for a node. For example, the following code creates a Job object and send the results to the console.

kubectl create job job1 -o yaml –dry-run=client –image=busybox

You can then copy and paste the result into your editor to save the file.

The interesting part of creating the object using this technique, you can then see the rest of the parameters in the object set to their default values. As a developer, you can then make changes to meet your needs.

Run

kubectl run will always create a Pod within a Deployment object. By default it sets replicas equal to 1. If you delete the pod running with that deployment, by default Deployment is going to create a new Pod and will continue. You will need to delete the deployment to delete the Pod running.

Use the the --restart parameter to set the Pod Restart Policy field. Set it using possible values Always, OnFailure, and Never. The default value is Always.

With kubectl run, you supply the name and the image. For more information, see kubectl commands run.

Other commands

  • edit. To edit any existing resource in the cluster. It opens a yaml file of that resource. To make the changes to the file and save it. It will be applied to the resource.
  • drain. It is used to drain the node for maintenance activity as if there is any hardware failure on that node and we don’t want to schedule a pod on that until maintenance has been performed on it.
  • scale. This command is used to scale our deployment, replica set or replica controller for your new requirement. For example, if you have a deployment called ‘test-nginx’ running with 1 replica and want to scale the deployment to run 3 replicas of that pod.

In this walkthrough, you learn how to use kubectl to interact with the resources.

Next steps

Resources