A Complete Guide to Kubernetes Components and YAML Configuration Explained

Ms. BMs. B
9 min read

Kubernetes (often abbreviated as K8s) is an open-source container orchestration platform designed to automate the deployment, scaling, and management of containerized applications. Kubernetes has become the industry standard for container orchestration.

Core Concepts of Kubernetes

1. Architecture

Kubernetes operates as a cluster consisting of:

  • Control Plane (Master Node): This is the brain of the cluster that manages workload and communications.

    • API Server: Entry point for all REST commands

    • Scheduler: Assigns work to nodes

    • Controller Manager: Maintains the desired state

    • etcd: Key-value store for cluster data

  • Worker Nodes: These are machines that run containerized applications.

    • Kubelet: The agent ensuring containers are running in a Pod

    • Container Runtime: The software responsible for running containers (Docker, containerd, CRI-O)

    • Kube-proxy: Network proxy maintaining network rules

2. Basic Resources

  • Pod: This is the smallest deployable unit containing one or more containers

  • Service: It is an abstraction defining a logical set of Pods and a policy to access them

  • Volume: Is a storage abstraction that allows containers to consume storage resources

  • Namespace: Virtual cluster that provides scope for names

  • ConfigMap/Secret: Resources for configuration management

3. Controllers

  • Deployment: Manages ReplicaSets and provides declarative updates to Pods

  • StatefulSet: Manages stateful applications

  • DaemonSet: Ensures all nodes run a copy of a Pod

  • Job/CronJob: Manages batch processing workloads

Common kubectl Commands

Cluster Management

# Get cluster information
kubectl cluster-info


# View nodes in the cluster
kubectl get nodes


# View detailed information about a specific node
kubectl describe node <node-name>


# Get available API resources
kubectl api-resources

Pod Operations

# Create resources from a file
kubectl apply -f <filename.yaml>


# List all pods in the current namespace
kubectl get pods


# List pods across all namespaces
kubectl get pods --all-namespaces


# Get detailed information about a pod
kubectl describe pod <pod-name>


# Execute a command in a container
kubectl exec -it <pod-name> -- <command>


# View pod logs
kubectl logs <pod-name>


# Delete a pod
kubectl delete pod <pod-name>

Deployment Operations

# Create a deployment
kubectl create deployment <name> --image=<image>


# Scale a deployment
kubectl scale deployment <name> --replicas=<count>


# Update a deployment's image
kubectl set image deployment/<name> <container>=<new-image>


# Roll back a deployment
kubectl rollout undo deployment/<name>


# View deployment status
kubectl rollout status deployment/<name>


# View deployment history
kubectl rollout history deployment/<name>

Service Operations

# Expose a deployment as a service
kubectl expose deployment <name> --port=<port> --type=<type>


# List all services
kubectl get services


# Delete a service
kubectl delete service <service-name>

Configuration and Context

# View current context
kubectl config current-context


# Switch context
kubectl config use-context <context-name>


# View kubeconfig
kubectl config view

Namespace Operations

# Create a namespace
kubectl create namespace <namespace-name>


# Set a default namespace for a context
kubectl config set-context --current --namespace=<namespace-name>


# List resources in a specific namespace
kubectl get <resource> -n <namespace-name>

YAML Configuration Examples

Pod Definition

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80

Deployment Definition

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

Service Definition

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 80
  type: ClusterIP

Explaining Kubernetes YAML Configuration Definitions

YAML (YAML Ain’t Markup Language) is the standard format used to define Kubernetes resources. Below, I have explained the common elements found in Kubernetes YAML configurations and explained what each part means.

Common Structure of Kubernetes YAML Files

Every Kubernetes YAML definition typically includes four main sections:

  1. apiVersion: Specifies which version of the Kubernetes API to use

  2. kind: Defines what type of resource you're creating

  3. metadata: Contains data that identifies the resource (name, labels, annotations, etc.)

  4. spec: The actual configuration of the resource (varies by resource type)

Pod Definition Explained

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80
  • apiVersion: v1: Using the core/v1 API version, which includes basic resources like Pods

  • kind: Pod: Defining a Pod resource, the smallest deployable unit in Kubernetes

  • metadata:

    • name: nginx-pod: The unique identifier for this Pod

    • labels: Key-value pairs used for identification and selection

      • app: nginx: A label that marks this Pod as part of the "nginx" application
  • spec: The desired state for this Pod

    • containers: List of containers in the Pod

      • name: nginx: Name of the container

      • image: nginx: Container image to use (from Docker Hub in this case)

      • ports: List of ports to expose

        • containerPort: 80: The port the container listens on

Deployment Definition Explained

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
  • apiVersion: apps/v1: Uses the apps API group, which includes resources like Deployments

  • kind: Deployment: Defining a Deployment, which manages ReplicaSets

  • metadata:

    • name: nginx-deployment: Unique name for this Deployment
  • spec: The desired state for this Deployment

    • replicas: 3: Maintain 3 replicas (copies) of the Pod

    • selector: Defines how the Deployment finds Pods to manage

      • matchLabels: Select Pods with matching labels

        • app: nginx: Match Pods with the label app=nginx
    • template: The Pod template used when creating new Pods

      • metadata: Metadata for the created Pods

        • labels: Labels applied to created Pods

          • app: nginx: Label that matches the selector above
      • spec: The Pod specification (same as in a Pod definition)

        • containers: List of containers in each Pod

          • name, image, ports: Same as in the Pod example

Service Definition Explained

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 80
  type: ClusterIP
  • apiVersion: v1: Core API version which includes Services

  • kind: Service: Defining a Service resource for network access

  • metadata:

    • name: nginx-service: Unique name for this Service
  • spec: The desired state for this Service

    • selector: Determines which Pods the Service routes traffic to

      • app: nginx: Selects Pods with the label app=nginx
    • ports: List of ports to expose

      • port: 80: The port the Service listens on

      • targetPort: 80: The port on the Pod to route traffic to

    • type: ClusterIP: The Service type (internal cluster IP)

Additional Common YAML Elements

Resource Limits and Requests

spec:
  containers:
  - name: app
    resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"
  • resources: Defines resource requirements

    • requests: Minimum resources needed

      • memory: "64Mi": 64 Mebibytes of memory

      • cpu: "250m": 250 milliCPU (1/4 of a CPU core)

    • limits: Maximum resources allowed

      • memory: "128Mi": 128 Mebibytes of memory

      • cpu: "500m": 500 milliCPU (1/2 of a CPU core)

Volume Mounts

spec:
  containers:
  - name: app
    volumeMounts:
    - name: config-volume
      mountPath: /etc/config
  volumes:
  - name: config-volume
    configMap:
      name: app-config
  • volumeMounts: Where volumes are mounted in containers

    • name: References the volume name

    • mountPath: Path in the container where the volume is mounted

  • volumes: List of volumes to create

    • name: Name of this volume

    • configMap: Volume backed by a ConfigMap

      • name: The ConfigMap name

Environment Variables

spec:
  containers:
  - name: app
    env:
    - name: DATABASE_URL
      value: "postgres://user:password@db:5432/dbname"
    - name: SECRET_KEY
      valueFrom:
        secretKeyRef:
          name: app-secrets
          key: secret-key
  • env: List of environment variables

    • Direct value:

      • name: Environment variable name

      • value: Value to set

    • From Secret:

      • name: Environment variable name

      • valueFrom: Get value from another resource

        • secretKeyRef: Reference a key in a Secret

          • name: Secret name

          • key: Key in the Secret

Health Checks

spec:
  containers:
  - name: app
    livenessProbe:
      httpGet:
        path: /health
        port: 8080
      initialDelaySeconds: 15
      periodSeconds: 10
    readinessProbe:
      httpGet:
        path: /ready
        port: 8080
      initialDelaySeconds: 5
      periodSeconds: 5
  • livenessProbe: Checks if container is running properly

    • httpGet: Probe using HTTP GET request

      • path: URL path to check

      • port: Port to check

    • initialDelaySeconds: Wait before first check

    • periodSeconds: Time between checks

  • readinessProbe: Checks if container is ready to serve traffic

ConfigMap and Secret References

# ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  app.properties: |
    key1=value1
    key2=value2

# Secret
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
type: Opaque
data:
  secret-key: c2VjcmV0LXZhbHVl  # base64 encoded "secret-value"
  • ConfigMap:

    • data: Key-value pairs of configuration data

      • Can store multiple configuration files or values
  • Secret:

    • type: Type of Secret (Opaque is generic)

    • data: Key-value pairs storing sensitive data (base64 encoded)

Understanding these YAML configurations is essential for effectively managing Kubernetes resources and deploying applications in a Kubernetes environment.

Advanced Kubernetes Features

1. Networking

  • Service Types:

    • ClusterIP: Exposes the Service on an internal IP (default)

    • NodePort: Exposes the Service on each Node's IP at a static port

    • LoadBalancer: Exposes the Service externally using a cloud provider's load balancer

    • ExternalName: Maps the Service to a DNS name

  • Network Policies: Specifications of how groups of pods are allowed to communicate with each other

# View network policies
kubectl get networkpolicies

2. Storage

  • Storage Classes: Abstraction layer for underlying storage providers

  • Persistent Volumes (PV): Cluster resources provisioned by an administrator

  • Persistent Volume Claims (PVC): Storage requests made by users

# List storage classes
kubectl get storageclasses


# List persistent volumes
kubectl get pv


# List persistent volume claims
kubectl get pvc

3. Configuration and Secrets

# Create a ConfigMap
kubectl create configmap <name> --from-file=<path/to/file>


# Create a Secret
kubectl create secret generic <name> --from-literal=key=value


# View ConfigMaps
kubectl get configmaps


# View Secrets
kubectl get secrets

4. Kubernetes RBAC

Role-Based Access Control (RBAC) is used to regulate access to resources:

# List roles
kubectl get roles --all-namespaces


# List cluster roles
kubectl get clusterroles


# List role bindings
kubectl get rolebindings --all-namespaces


# List cluster role bindings
kubectl get clusterrolebindings

5. Health Checks

  • Liveness Probe: Determines if a container is running

  • Readiness Probe: Determines if a container is ready to receive traffic

  • Startup Probe: Determines when a container application has started

6. Resource Management

# View resource usage across nodes
kubectl top nodes

# View resource usage across pods
kubectl top pods

Kubernetes Tooling Ecosystem

  1. Helm: Package manager for Kubernetes

  2. Prometheus: Monitoring and alerting

  3. Grafana: Visualization and dashboards

  4. Istio: Service mesh for complex operational requirements

  5. Knative: Platform for building serverless applications

  6. Kustomize: Template-free configuration customization

  7. Flux/ArgoCD: GitOps tools for continuous deployment

Kubernetes Best Practices

  1. Resource Requests and Limits: Specify CPU and memory requirements for containers

  2. Liveness and Readiness Probes: Configure appropriate health checks

  3. Pod Disruption Budgets: Ensure availability during voluntary disruptions

  4. Security Context: Define privilege and access control settings for Pods

  5. Network Policies: Implement proper network segmentation

  6. Use Namespaces: Organize resources and implement access controls

  7. Resource Quotas: Set constraints on resource consumption per namespace

  8. Label Everything: Use consistent labeling for effective resource management

  9. Use ConfigMaps and Secrets: Externalize configuration from container images

  10. Regular Auditing: Monitor and review cluster security posture

Kubernetes is a powerful system and mastering it allows for robust, scalable, and resilient application deployments across any infrastructure.

2
Subscribe to my newsletter

Read articles from Ms. B directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ms. B
Ms. B

Hi, I'm a tech enthusiast who has decided to document her cloud journey as the day goes by. Stay tuned and follow me through this journey which I believe would be a wonderful experience. I'm also a team player who loves collaborating with others to create innovative solutions.