Skip to content

Kubernetes basic usage

Introduction

Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. This guide covers the essential concepts and commands for working with Kubernetes using kubectl, the command-line interface for Kubernetes.

If you want to install Kubernetes, there are many ways to do it. You can install it on a single machine, on a local machine, on a cloud provider, or on a home lab:

Kubectl Basics

Installation and Configuration

Install kubectl using curl (check the architecture of your machine):

curl -LO https://dl.k8s.io/release/$(curl -Ls https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl

Verify the installation:

kubectl version --client

Configure kubectl to use your cluster:

kubectl config use-context your-cluster-name

View current context:

kubectl config current-context

List all contexts:

kubectl config get-contexts

Set namespace for current context:

kubectl config set-context --current --namespace=my-namespace

Understanding kubectl Output Formats

Default output (wide format):

kubectl get pods

Detailed output in YAML format:

kubectl get pod <pod-name> -o yaml

JSON output format:

kubectl get pod <pod-name> -o json

Custom columns output:

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP

Save output to file:

kubectl get pods -o yaml > pods.yaml

Resource Management Commands

Get Resources

List all resources of a specific type:

kubectl get <resource-type>

Common resource type shortcuts:

  • pods (po)
  • deployments (deploy)
  • services (svc)
  • configmaps (cm)
  • secrets
  • nodes (no)
  • namespaces (ns)
  • persistentvolumeclaims (pvc)
  • persistentvolumes (pv)

Get resources with specific labels:

kubectl get pods -l app=nginx

Get resources in a specific namespace:

kubectl get pods -n my-namespace

Watch resources in real-time:

kubectl get pods -w

Get resources with field selectors:

kubectl get pods --field-selector status.phase=Running

Describe Resources

Get detailed information about a resource:

kubectl describe <resource-type> <resource-name>

Example commands:

1
2
3
kubectl describe pod my-pod
kubectl describe deployment my-deployment
kubectl describe service my-service

Get events related to a resource:

kubectl describe pod my-pod | grep -A 10 Events:

Create and Apply Resources

Create from file:

kubectl create -f resource.yaml

Apply changes (create or update):

kubectl apply -f resource.yaml

Create from URL:

kubectl create -f https://raw.githubusercontent.com/kubernetes/website/main/content/en/examples/application/nginx-app.yaml

Create with client-side dry-run:

kubectl create -f resource.yaml --dry-run=client

Create with server-side validation:

kubectl create -f resource.yaml --dry-run=server

Edit and Update Resources

Edit resource in default editor:

kubectl edit <resource-type> <resource-name>

Patch resource:

kubectl patch deployment my-deployment -p '{"spec":{"replicas":3}}'

Replace resource:

kubectl replace -f resource.yaml

Scale resources:

kubectl scale deployment my-deployment --replicas=3

Delete Resources

Delete by name:

kubectl delete <resource-type> <resource-name>

Delete by file:

kubectl delete -f resource.yaml

Delete by label:

kubectl delete pods -l app=nginx

Delete with grace period:

kubectl delete pod my-pod --grace-period=30

Force delete:

kubectl delete pod my-pod --force --grace-period=0

Debugging and Troubleshooting

Logs

Get pod logs:

kubectl logs <pod-name>

Get logs from previous instance:

kubectl logs <pod-name> --previous

Follow logs in real-time:

kubectl logs -f <pod-name>

Get logs from specific container:

kubectl logs <pod-name> -c <container-name>

Get logs with timestamps:

kubectl logs <pod-name> --timestamps

Get logs from last N lines:

kubectl logs <pod-name> --tail=100

Exec and Port Forward

Execute command in container:

kubectl exec <pod-name> -- <command>

Start interactive shell:

kubectl exec -it <pod-name> -- /bin/bash

Port forward to pod:

kubectl port-forward <pod-name> 8080:80

Port forward to service:

kubectl port-forward svc/<service-name> 8080:80

Debugging Tools

Get resource events:

kubectl get events --sort-by='.lastTimestamp'

Get resource metrics:

kubectl top pods
kubectl top nodes

Debug pod issues:

kubectl debug <pod-name>

Copy files to container:

kubectl cp <pod-name>:/path/to/file ./local-file

Copy files from container:

kubectl cp ./local-file <pod-name>:/path/to/file

Advanced kubectl Usage

Resource Queries

Get resources with custom output:

kubectl get pods -o jsonpath='{.items[*].metadata.name}'

Get specific fields:

kubectl get pod <pod-name> -o jsonpath='{.status.podIP}'

Get multiple fields:

kubectl get pod <pod-name> -o jsonpath='{.metadata.name}{"\t"}{.status.podIP}{"\n"}'

Get resources with label selectors:

kubectl get pods -l 'environment in (production,staging)'

Configuration Management

View current config:

kubectl config view

View specific context:

kubectl config view --minify

Set namespace for current context:

kubectl config set-context --current --namespace=my-namespace

Create new context:

kubectl config set-context my-context --cluster=my-cluster --user=my-user --namespace=my-namespace

Standard Kubernetes Objects

Kubernetes provides several built-in objects to manage containerized applications:

Pods

The smallest deployable unit in Kubernetes.

Create a new pod:

kubectl run nginx --image=nginx

Get pod details:

kubectl get pods
kubectl describe pod <pod-name>

Delete a pod:

kubectl delete pod <pod-name>

Deployments

Manages the desired state for Pods and ReplicaSets.

Create a new deployment:

kubectl create deployment nginx --image=nginx

Scale a deployment:

kubectl scale deployment nginx --replicas=3

Update a deployment:

kubectl set image deployment/nginx nginx=nginx:1.19

Services

Exposes applications running on Pods to the network.

Create a new service:

kubectl expose deployment nginx --port=80 --type=LoadBalancer

Get service details:

kubectl get services

ConfigMaps and Secrets

Store configuration data and sensitive information.

Create a new ConfigMap:

kubectl create configmap my-config --from-literal=key1=value1

Create a new Secret:

kubectl create secret generic my-secret --from-literal=username=admin

Namespaces

Provide scope for resources and enable resource isolation.

Create a new namespace:

kubectl create namespace my-namespace

List resources in a namespace:

kubectl get all -n my-namespace

PersistentVolumes and PersistentVolumeClaims

Manage storage resources.

Create a new PVC:

kubectl create -f pvc.yaml

List PVCs:

kubectl get pvc

Custom Resource Definitions (CRDs)

CRDs extend Kubernetes' API to create custom resources.

Creating a CRD

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: myresources.example.com
spec:
  group: example.com
  names:
    kind: MyResource
    plural: myresources
    singular: myresource
    shortNames:
      - mr
  scope: Namespaced
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                field1:
                  type: string

Using Custom Resources

Create a custom resource from file:

kubectl create -f my-resource.yaml

List all custom resources:

kubectl get myresources

Get detailed information about a custom resource:

kubectl describe myresource <name>

Operators and Controllers

Understanding Operators

Operators are a method of packaging, deploying, and managing a Kubernetes application. They extend the Kubernetes API to create, configure, and manage instances of complex applications like databases, message brokers, etc.

Working with Operator CRDs

Finding Operator CRDs

List all CRDs in the cluster:

kubectl get crds

Get details about a specific CRD:

kubectl describe crd <crd-name>

Get the API version and kind:

kubectl api-resources | grep <operator-name>

Understanding CRD Relationships

Find related resources using owner references:

kubectl get <resource-type> -o jsonpath='{.items[*].metadata.ownerReferences}'

Find resources managed by an operator:

kubectl get all -l app.kubernetes.io/managed-by=<operator-name>

Find resources belonging to an instance:

kubectl get all -l app.kubernetes.io/instance=<instance-name>

Check the status of operator-managed resources:

kubectl get <crd-kind> <name> -o jsonpath='{.status.conditions}'

Troubleshooting Operators

Get operator pod status:

kubectl get pods -n <operator-namespace> -l app.kubernetes.io/name=<operator-name>

Check operator logs:

kubectl logs -n <operator-namespace> -l app.kubernetes.io/name=<operator-name>

Check CRD status:

kubectl get crd <crd-name> -o jsonpath='{.status.conditions}'

Verify CRD schema:

kubectl get crd <crd-name> -o yaml

List all resources managed by the operator:

kubectl get all -l app.kubernetes.io/managed-by=<operator-name>

Check for failed resources:

kubectl get <crd-kind> -o jsonpath='{.items[?(@.status.conditions[0].status=="False")].metadata.name}'