Skip to main content

Command Palette

Search for a command to run...

Essential Resources of Kubernetes for Managing Applications Efficiently

Updated
14 min read
Essential Resources of Kubernetes for Managing Applications Efficiently
J
IT Professional with 4+ years of combined experience across Software Engineering, DevOps, Cloud, Technical Writing, and AI-assisted Development. Passionate about building things, simplifying complex technology, and continuously learning while sharing knowledge through hands-on experimentation and technical writing.

Kubernetes has revolutionized the way we manage containerized applications, offering a robust platform for automating deployment, scaling, and operations. In this article, we delve into the core components of Kubernetes, including Pods, Deployments, and essential resources like Secrets, Services, and ConfigMaps. By understanding these elements, you'll gain insights into how Kubernetes orchestrates complex applications, ensuring reliability, scalability, and security.

Pods

🧱 What’s a Pod?

  • Think of a Pod like a cozy room for one or more containers to live together.

  • They share resources like storage and network so they can talk and work smoothly.

📦 Types of Pods

  • One-container Pods: Most common — simple and clean.

  • Multi-container Pods: For containers that need to team up closely.

🚀 How Pods Work

  • You usually don’t make them directly. Instead, use tools like Deployments or Jobs to create and manage Pods.

  • They’re temporary — if one stops working, Kubernetes replaces it automatically.

🧾 Pod Templates

  • Templates are blueprints used to create Pods.

  • Changing a template means Kubernetes makes new Pods instead of editing old ones.

🛠️ What You Can Change

  • Only a few things like container images can be changed once a Pod is running.

  • Most parts are locked in after creation.

🔗 Sharing Inside Pods

  • Network: Containers share the same IP and can talk through the Pod's IP address.

  • Storage: Shared volumes let them read/write the same data.

🔐 Security & OS

  • You can control access and behavior using securityContext.

  • Pods can run on Linux or Windows, and you choose which using settings in the Pod file.


📘Source: Kubernetes Pods documentation


Deployments

🚀 What’s a Deployment?

  • Think of it as a manager for your Pods.

  • It makes sure the right number of containers are running and updates them safely when needed.

📦 What Deployments Do

  • Create Pods using ReplicaSets.

  • Update Pods smoothly (e.g., changing the app version).

  • Roll back if something goes wrong.

  • Scale up/down to handle traffic changes.

  • Pause updates, fix things, and resume.

🔄 How It Works

  • You write a config describing what you want.

  • Kubernetes slowly shifts reality to match that config.

  • It handles all the tricky bits like keeping some Pods alive during updates.

📁 Example: nginx Deployment

  • Creates 3 nginx Pods from a template.

      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:1.14.2
              ports:
              - containerPort: 80
    

    🔍 Breakdown:

    • replicas: 3: Spin up 3 Nginx Pods.

    • selector: Tells Kubernetes which Pods this Deployment should manage.

    • template: Blueprint for each Pod.

    • image: Uses the official nginx:1.14.2 image.

    • containerPort: 80: Exposes port 80 on the container.

  • Uses kubectl apply to deploy.

  • Let’s you monitor and update using rollout commands.

📊 Checking Status

  • See how many Pods are ready, updated, available, and how long they’ve been running.

🧬 Updating the App

  • Change the container image (like from nginx:1.14.2 to 1.16.1).

  • Kubernetes handles the update with minimal downtime.

⏮ Rolling Back

  • If an update fails, you can roll back to a previous version easily.

📘Source: Kubernetes Deployment documentation


ReplicaSet

🔄 What’s a ReplicaSet?

  • Ensures a specific number of identical Pods are running at all times.

  • Automatically creates or deletes Pods to maintain that desired count.

  • Mostly used under the hood by Deployments.

📦 Key Fields in a ReplicaSet

  • replicas: Target number of Pods to maintain.

  • selector: How it identifies which Pods belong to it.

  • template: Blueprint for creating new Pods.

🧠 How It Works

  1. Uses the Pod template to generate identical Pods.

  2. Tracks Pods using ownerReferences.

  3. Matches Pods using the selector labels — and can adopt unowned Pods with matching labels.

📝 Example YAML

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        image: nginx:latest
  • This will ensure 3 Pods running nginx are always alive with label app=web.

🧹 Managing ReplicaSets

  • Scale by changing spec.replicas.

  • Use kubectl delete rs <name> to remove it.

  • If you delete Pods, the ReplicaSet replaces them automatically.

⚠️ Things to Watch

  • Avoid label overlap — or it may adopt unintended Pods.

  • Pods must match both the selector and template.metadata.labels.

  • No rolling updates — use Deployment for smarter updates.

🤖 When Not to Use It Directly

  • Prefer Deployment for everyday app management — it wraps ReplicaSets and adds versioning + rolling updates.

  • Use ReplicaSet directly only if you need custom control without automatic updates.


📘Source: Kubernetes RepilicaSet documentation


Secrets

🧩 What Is a Secret?

  • A Secret holds confidential info like passwords, tokens, or SSH keys.

  • Instead of putting this data directly into your app or Pod file, Secrets store it safely in Kubernetes.

🤝 Why Use Secrets?

  • Keeps sensitive data out of your code and containers.

  • Secrets are created separately from Pods, which helps reduce exposure.

  • Kubernetes avoids writing Secrets to disk when possible.

⚠️ Be Cautious

  • Secrets are not encrypted by default — anyone with access to the API server or etcd can read them.

  • To improve safety:

    • Turn on Encryption at Rest.

    • Use RBAC to limit who can access Secrets.

    • Restrict Secrets to specific containers.

    • Consider using external Secret stores like HashiCorp Vault.

🛠️ Common Uses

  • Set environment variables for containers.

  • Provide private registry credentials (for pulling images).

  • Supply SSH keys, tokens, or TLS certificates.

📁 Example Secrets

Create a .secret-file and mount it as a volume in your Pod:

apiVersion: v1
kind: Secret
metadata:
  name: dotfile-secret
data:
  .secret-file: dmFsdWUtMg0KDQo=  # base64 for "value-2"

Mount it in a Pod:

apiVersion: v1
kind: Pod
metadata:
  name: secret-dotfiles-pod
spec:
  volumes:
  - name: secret-volume
    secret:
      secretName: dotfile-secret
  containers:
  - name: dotfile-test-container
    image: busybox
    command: ["ls", "-l", "/etc/secret-volume"]
    volumeMounts:
    - name: secret-volume
      readOnly: true
      mountPath: "/etc/secret-volume"

🔒 Limiting Access

  • Mount Secrets into only one container in a multi-container Pod to improve security.

  • Separate responsibilities (e.g., frontend vs. signer container) can protect Secrets from exploit.

📦 Secret Types

TypePurpose
OpaqueCustom data
kubernetes.io/service-account-tokenServiceAccount tokens
kubernetes.io/dockerconfigjsonDocker registry credentials
kubernetes.io/tlsTLS certificate
kubernetes.io/basic-authUsername + password

📘Source: Kubernetes Secrets documentation


Service

🚪 What’s a Service?

  • It’s a doorway that lets other apps (inside or outside the cluster) talk to your Pods.

  • Even if Pods come and go, the Service stays stable with a single access point.

🔧 Why Use It?

  • Your Pods get random IPs and can disappear anytime.

  • Services give your app a fixed endpoint so others can reach it without worrying about Pod changes.

🧭 How Services Work

  • Services find Pods using labels (like app: myapp).

  • They keep track of which Pods are available and direct traffic to them.

📡 Types of Service

TypeDescription
ClusterIPDefault, reachable only inside cluster
NodePortExposes via a port on each cluster node
LoadBalancerUses cloud provider’s LB to expose
ExternalNameMaps to a DNS name instead of Pods

🔁 EndpointSlices

  • Used to track real IPs of Pods behind a Service.

  • Updates automatically when Pods change.

  • Replaces older Endpoints (now deprecated).

📁 Example Service

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376
  • This creates a Service pointing to Pods labeled app: MyApp, forwarding external port 80 to Pod port 9376.

🛠 Services Without Selectors

  • You can manually define backends using EndpointSlice if Pods aren’t managed directly (e.g., external databases or hybrid deployments).

📘Source: Kubernetes Service documentation


ConfigMap

🧩 What’s a ConfigMap?

  • It’s like a storage box for settings: holds non-sensitive config as key-value pairs.

  • Helps keep your app config separate from your container image.

  • Ideal for things like file paths, usernames, or toggles — not for secrets (use Secrets for those).

📦 Why Use It?

  • Makes apps portable across environments (e.g. switch DATABASE_HOST from localhost to a cloud service).

  • You can reuse the same app image in dev and production — just swap the config!

🔐 Note on Security

  • Not encrypted by default.

  • If using for sensitive data, enable encryption at rest, tighten RBAC, or use a dedicated Secret manager.

🔧 How to Use ConfigMaps

You can feed ConfigMap data into Pods in 4 ways:

  1. As environment variables

  2. As command-line args

  3. As mounted files in a volume

  4. Programmatically via the Kubernetes API (to enable dynamic updates)

📁 Example ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: game-demo
data:
  player_initial_lives: "3"
  ui_properties_file_name: "user-interface.properties"
  game.properties: |
    enemy.types=aliens,monsters
    player.maximum-lives=5

🛠 Pod Using ConfigMap

apiVersion: v1
kind: Pod
metadata:
  name: configmap-demo-pod
spec:
  containers:
  - name: demo
    image: alpine
    command: ["sleep", "3600"]
    env:
    - name: PLAYER_INITIAL_LIVES
      valueFrom:
        configMapKeyRef:
          name: game-demo
          key: player_initial_lives

📚 Good to Know

  • Updates to mounted volumes sync automatically (after a short delay).

  • Environment variable values from a ConfigMap don’t auto-update — restarting the Pod is required.

  • You can make a ConfigMap immutable to prevent accidental changes.


Source: Kubernetes ConfigMap documentation


Persistent Volume (PV)

📦 What’s a Persistent Volume?

  • A PVs is like a hard drive for your cluster.

  • It’s pre-created by an admin or dynamically made using a StorageClass.

  • Unlike regular volumes, PVs live beyond Pod lifetimes — ideal for long-term data.

📝 What’s a Persistent Volume Claim (PVC)?

  • A PVC is a request for storage made by a user/app.

  • Think of it like asking for a locker with a specific size and access rules (e.g. read-only, read/write).

🔁 Lifecycle: How PVs & PVCs Work

  1. Provisioning: PVs can be made ahead of time or on-the-fly using StorageClasses.

  2. Binding: Kubernetes links your PVC to a matching PV.

  3. Using: Pods mount PVCs as volumes to store data.

  4. Reclaiming: When done, PVC is deleted, and the PV’s reclaim policy kicks in.

🔧 Reclaim Policies

PolicyWhat It Does
RetainKeeps the volume for manual cleanup
DeleteRemoves both the Kubernetes object and real data
RecycleClears data and makes it available again (deprecated)

📁 Example PV and PVC

📁 persistent-volume.yml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mongo-pv
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /data/mongo
  • Creates a 1Gi volume using local host storage.

  • Retain keeps data even after the claim is deleted.

📁 persistent-volume-claim.yml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mongo-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  • Requests 1Gi of storage.

  • Access mode must match the PV (ReadWriteOnce).


🛡️ Protection Mechanism

  • Kubernetes blocks deletion of PVs/PVCs still in use — prevents accidental data loss.

  • You’ll see a “Terminating” status with special finalizers (kubernetes.io/pv-protection, etc.).

⚡ Dynamic Provisioning

  • Triggered by a PVC asking for a specific StorageClass.

  • The cluster auto-creates the right volume — no admin intervention needed.

    Example:

    📁 storage-class.yml

      apiVersion: storage.k8s.io/v1
      kind: StorageClass
      metadata:
        name: fast-storage
      provisioner: kubernetes.io/aws-ebs  # Change based on your cloud or local setup
      parameters:
        type: gp2
    

    📁 pvc-dynamic.yml

      apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: dynamic-pvc
      spec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 5Gi
        storageClassName: fast-storage
    

    What Happens:

    • PVC requests 5Gi storage using fast-storage StorageClass.

    • Kubernetes dynamically provisions an appropriate volume (e.g., AWS EBS or other backend).

    • No manual creation of PersistentVolume needed.


Source: Kubernetes Persistent Volumes documentation


Ingress

🚪 What’s Ingress?

  • It’s like a traffic gatekeeper for your cluster.

  • Controls external HTTP/HTTPS access to your internal services.

  • Think: URLs → Ingress → Service → Pod.

🛠️ What It Can Do

  • Provides clean, consistent web URLs for your services.

  • Handles SSL termination for HTTPS.

  • Supports routing rules based on hostnames and paths.

  • Offers name-based virtual hosting (same IP, multiple domain names).

📦 Example YAML

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /app
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
  • Routes traffic from example.com/app to my-service.

🚧 Important Notes

  • You need an Ingress controller (like NGINX) — creating an Ingress object alone won’t expose your app.

  • Rules match host + path to decide where traffic goes.

  • Different controllers support different annotations, like rewrite-targets.

🧬 Path Matching Types

Path TypeDescription
PrefixMatches path prefix (/app/app/*)
ExactMatches full path (/app only)
ImplementationSpecificDepends on the controller

Source: Kubernetes Ingress documentation


🧊 Frozen Ingress API

  • The Ingress API is now frozen — no new features will be added.

  • Still widely used and supported in production clusters.

  • Great for simple routing, but limited for advanced traffic control.


The Gateway API (New Direction)

The Gateway API is Kubernetes’ modern replacement for Ingress — now supported across many platforms.

🌟 Key Features

  • Role-oriented: separates responsibilities for infra providers, cluster operators, and app devs.

  • Expressive & Flexible: supports header-based routing, traffic weighting, and more.

  • Extensible: allows adding filters, authentication, and custom behaviors via linked resources.

  • Portable: uses CRDs, supported by multiple implementations.

📦 Gateway API Resources

ResourcePurpose
GatewayClassDefines shared config across Gateways
GatewayRepresents traffic handling infra (like a load balancer)
HTTPRouteMaps traffic rules (path, host, filters) to backend Services

🔁 Request Flow (Gateway API)

  1. Client sends request (e.g. https://example.com/login)

  2. Gateway receives the request via a listener (port/protocol)

  3. HTTPRoute matches it (host + path) and forwards to a Service

  4. Optional: add/remove headers, rewrite paths, split traffic

🆚 Ingress vs. Gateway API Comparison

FeatureIngressGateway API
StatusFrozen APIActively evolving
Traffic RoutingBasic path/host matchingHeader-based, weighted, filters
TLS/SSLBasic terminationAdvanced TLS management
Resource TypesSingle (Ingress)Modular (Gateway, HTTPRoute, etc.)
Role SeparationNot definedClear roles: infra, ops, devs
ExtensibilityVia annotationsBuilt-in via CRDs (Custom Resource Definitions) & filters
Controller CompatibilityLimited to annotationsBroad implementations supported
Best ForSimple setupsComplex, scalable environments

📘Source: Kubernetes Gateway API documentation


Namespaces

🧩 What Are Namespaces?

  • Namespaces divide a Kubernetes cluster into smaller sections.

  • They help organize and isolate resources by teams, environments, or projects.

  • Think of them as folders inside your cluster.

📦 Why Use Namespaces?

  • Resources inside each namespace stay isolated from others.

  • You can use resource quotas to limit usage per namespace.

  • Perfect for setups with multiple users or environments (like dev, staging, prod).

🌱 Initial Namespaces in Kubernetes

NamespacePurpose
defaultWhere resources go if no namespace is specified.
kube-systemFor system-level components like DNS and controllers.
kube-publicReadable by everyone — mostly unused but available for public data.
kube-node-leaseHelps track node heartbeats to detect failures.

📁 Example namespace.yml

apiVersion: v1
kind: Namespace
metadata:
  name: dev-team
  • This creates a namespace called dev-team.

  • You can then deploy resources (Pods, Deployments, Services, etc.) into this namespace by adding:

    yaml

      metadata:
        namespace: dev-team
    

📟 Commands You Can Use

  • Create the namespace:

      kubectl apply -f namespace.yml
    
  • List all namespaces:

      kubectl get namespaces
    
  • Use this namespace by default:

      kubectl config set-context --current --namespace=dev-team
    

🌐 DNS & Networking Notes

  • Services in a namespace get a DNS name like:

      myservice.mynamespace.svc.cluster.local
    
  • To access Services across namespaces, use the full DNS name.

  • All namespace names must be valid RFC 1123 DNS labels.

⚠️ Cautions

  • Avoid using the default namespace in production — create your own.

  • Don’t create namespaces with names of public top-level domains (like .com) to prevent DNS conflicts.

  • Not all resources are namespaced (e.g., Nodes, PVs, StorageClasses exist cluster-wide).


📘Source: Kubernetes Namespaces documentation


Conclusion

In conclusion, understanding the core parts of Kubernetes, like Pods, Deployments, and key resources such as Secrets, Services, and ConfigMaps, is vital for managing containerized applications effectively. These elements ensure applications are reliable, scalable, and secure, offering a strong platform for automating deployment and operations. By mastering these components, you can fully utilize Kubernetes to efficiently manage complex applications.

More from this blog

D

Demystifying Tech with Jasai

104 posts

Demystifying Tech with Jasai is a blog dedicated to breaking down complex tech concepts into clear, beginner-friendly explanations. Covering DevOps, Docker, Git, AWS, CI/CD, Networking, and core programming fundamentals, it emphasizes strong foundations before advanced topics. Through step-by-step walkthroughs and real-world analogies, it simplifies the why behind the how — making technology approachable, structured, and built for long-term growth.