Kubernetes logoKubernetesv1.37INTERMEDIATE

Kubernetes Essentials

Deploy, configure, secure, scale, and troubleshoot container workloads with Kubernetes.

18 min read
kuberneteskubectlcontainersdevopsorchestration
Loading your progress

Setup

Install kubectl and connect it to an existing Kubernetes cluster.

Install kubectl on Linux, macOS, or Windows and verify the client.

bash
# macOS
brew install kubectl

# Windows
winget install -e --id Kubernetes.kubectl
📌 Keep kubectl within one minor version of the cluster
💡 Homebrew and winget provide simple managed installs
🔍 Linux ARM64 uses the linux/arm64 download path
⚠️ Verify downloaded binaries in sensitive environments
kubectlinstallversion

Install minikube and start a local learning cluster.

bash
# macOS
brew install minikube

# Windows
winget install Kubernetes.minikube
📌 minikube is for learning and local development
💡 Docker or another supported driver is required
🔍 minikube configures the kubectl context automatically
⚠️ Use a managed or administered cluster for production
minikubelocal-clustersetup

Select a kubeconfig context and verify connectivity.

bash
kubectl config get-contexts
kubectl cluster-info
📌 Kubernetes commands require access to a cluster
⚠️ Confirm the active context before making changes
💡 KUBECONFIG can point to one or more config files
🔍 A context combines a cluster, user, and namespace
kubeconfigcontextcluster-access

Architecture and Objects

Understand cluster components and Kubernetes API objects.

Identify the control plane and worker-node responsibilities.

bash
kubectl cluster-info
kubectl get nodes
📌 The API server is the cluster entry point
🔍 etcd stores desired and observed state
💡 Controllers reconcile actual state continuously
⚠️ componentstatuses is deprecated on some clusters
architectureclusterapi

Object Manifest

Declare desired state with apiVersion, kind, metadata, and spec.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
    - name: web
      image: nginx:1.29
📌 apiVersion and kind select the resource schema
📌 metadata.name identifies the object
🔍 spec describes desired state
🎯 Store production manifests in version control
manifestyamlobjects

kubectl and Contexts

Connect to clusters and inspect resources safely.

Select the cluster, user, and default namespace.

bash
kubectl config current-context
kubectl config get-contexts
📌 A context combines cluster, user, and namespace
⚠️ Confirm context before mutations
💡 Set a default namespace per context
🔍 kubectl reads $HOME/.kube/config by default
kubectlcontextnamespace

Get resources in useful output formats.

bash
kubectl get pods
kubectl describe pod web
⚡ Use short names such as po, deploy, and svc
💡 explain reads the server resource schema
🔍 describe combines state and recent events
🎯 Prefer machine-readable output in scripts
kubectlinspectexplain

Declarative Management

Preview and apply version-controlled manifests.

Manage desired state from files.

bash
kubectl diff -f app.yaml
kubectl apply -f app.yaml
📌 Prefer apply for reproducible workloads
⚡ diff previews changes before apply
💡 Server dry runs perform API validation
⚠️ Delete removes every object in the file
applydiffdelete

Labels and Metadata

Organize and select related resources.

Attach queryable labels and descriptive annotations.

bash
kubectl label pod web env=prod
kubectl get pods -l env=prod
📌 Selectors connect controllers and Services to Pods
💡 Use annotations for non-identifying metadata
🔍 Set-based selectors support in and notin
⚠️ Changing selector labels can disconnect resources
labelsselectorsannotations

Pods

Run one or more tightly coupled containers.

Inspect, enter, and forward ports to Pods.

bash
kubectl get pods
kubectl logs web
📌 Pods are replaceable, not durable servers
💡 Specify the container in multi-container Pods
🔍 port-forward is intended for local access
⚠️ exec and port-forward require RBAC permission
podslogsexec

Deployments and Rollouts

Run and update interchangeable application replicas.

Manage stateless replicated workloads.

bash
kubectl create deployment web --image=nginx:1.29
kubectl scale deployment web --replicas=3
📌 Deployments manage ReplicaSets and Pods
💡 Use declarative manifests for production
🔍 Scaling changes desired replica count
⚠️ HPA needs a metrics provider
deploymentscalereplicas

Rollout Control

Inspect, pause, resume, restart, or undo updates.

bash
kubectl rollout status deployment/web
kubectl rollout history deployment/web
📌 Wait for rollout status in deployment pipelines
💡 Record meaningful image tags
🔍 Undo creates a new rollout from an old revision
⚠️ Rollback does not revert external dependencies
rolloutrollbackdeployment

Other Workloads

Choose controllers for stateful, node-level, and finite work.

Run stable identities or one Pod per selected node.

bash
kubectl get statefulsets
kubectl get daemonsets
📌 StatefulSets preserve network and storage identity
📌 DaemonSets target all or selected nodes
🔍 Both support rollout inspection
🎯 Use Deployments when identity is unnecessary
statefulsetdaemonsetworkloads

Run tasks to completion once or on a schedule.

bash
kubectl create job report --image=busybox:1.37 -- echo ready
📌 Jobs retry Pods until completion policy is met
📌 CronJob schedules use the controller timezone
💡 Set history limits and deadlines in manifests
⚠️ Jobs must be safe to retry
jobcronjobbatch

Services and Networking

Expose stable endpoints and route application traffic.

Provide stable discovery for selected Pods.

bash
kubectl expose deployment web --port=80 --target-port=8080
📌 Services select Pods by labels
🔍 ClusterIP is the default Service type
💡 EndpointSlices show selected backends
⚠️ A Service with no endpoints usually has a selector mismatch
servicednsnetworking

Ingress

Route external HTTP traffic through an Ingress controller.

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
spec:
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80
📌 Ingress requires an installed controller
🔍 Ingress routes HTTP and HTTPS traffic
💡 TLS Secrets attach certificates
🎯 Consider Gateway API for newer routing needs
ingresshttprouting

Configuration

Inject non-secret and sensitive configuration.

Create configuration and expose it to Pods.

bash
kubectl create configmap app-config --from-literal=LOG_LEVEL=info
kubectl create secret generic db --from-literal=password='change-me'
📌 Base64 encoding is not encryption
⚠️ Avoid secrets in shell history and Git
💡 Mount config as files for live updates
🔍 Environment variables need a Pod restart to refresh
configmapsecretconfiguration

Health and Resources

Declare health checks and resource expectations.

Probes

Separate startup, readiness, and liveness checks.

yaml
readinessProbe:
  httpGet:
    path: /ready
    port: 8080
📌 Readiness controls Service traffic
📌 Liveness can restart a stuck container
💡 Startup probes protect slow applications
⚠️ Aggressive probes can create outages
probeshealthcontainers

Reserve scheduler capacity and cap container use.

yaml
resources:
  requests: {cpu: 100m, memory: 128Mi}
  limits: {cpu: 500m, memory: 256Mi}
📌 The scheduler uses requests for placement
🔍 Memory limit breaches can cause OOMKilled
⚠️ CPU limits throttle rather than terminate
🎯 Measure workloads before tuning values
resourcesrequestslimits

Storage

Attach ephemeral and persistent data to workloads.

Request persistent storage through a StorageClass.

yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 10Gi
📌 PVCs request storage and PVs provide it
🔍 StorageClass controls dynamic provisioning
⚠️ Access modes depend on the storage driver
🎯 Check reclaim policy before deleting claims
storagepvcpersistent-volume

Scheduling

Influence where Pods run.

Constrain or repel Pods during scheduling.

yaml
nodeSelector:
  disktype: ssd
📌 nodeSelector is a simple hard constraint
💡 Affinity supports richer placement rules
🔍 Taints repel Pods without matching tolerations
⚠️ Toleration permits placement but does not require it
schedulingtaintsaffinity

Security

Limit workload identity and container privileges.

Grant the minimum API permissions required.

bash
kubectl create serviceaccount reporter
kubectl auth can-i list pods --as=system:serviceaccount:default:reporter
📌 Pods receive a ServiceAccount identity
🎯 Grant least privilege in a namespace
🔍 Roles need bindings before they grant access
⚠️ Avoid broad cluster-admin bindings
securityrbacserviceaccount

Run containers with reduced privileges.

yaml
securityContext:
  runAsNonRoot: true
  allowPrivilegeEscalation: false
📌 Container settings override overlapping Pod settings
🎯 Drop Linux capabilities by default
💡 Use RuntimeDefault seccomp
⚠️ Test images with non-root execution
security-contextnon-rootseccomp

Troubleshooting

Find failures using status, events, logs, and ephemeral debugging.

Follow a repeatable inspection sequence.

bash
kubectl get pods
kubectl describe pod web
kubectl logs web
📌 Start with status, describe, events, then logs
💡 --previous reads the last crashed container
🔍 debug can add an ephemeral container
⚠️ Debug images still operate inside the cluster
debugeventslogs