Deploying Containers with Kubernetes

3.13K 0 0 0 0

✅ Chapter 4: ConfigMaps, Secrets, and Volume Management

🔍 Introduction

In Kubernetes, managing application configuration, sensitive data, and persistent storage is crucial for running real-world production systems.

In this chapter, you will learn:

  • How to externalize application configurations using ConfigMaps
  • How to securely handle passwords, keys, and tokens using Secrets
  • How to manage persistent data using Volumes, PersistentVolumeClaims (PVCs), and StorageClasses

Mastering these concepts ensures your applications remain stateless, secure, and scalable.


📋 Part 1: Kubernetes ConfigMaps

🔹 What is a ConfigMap?

A ConfigMap is a Kubernetes object that allows you to store non-sensitive configuration data (like environment variables, command-line arguments, or entire config files) separately from application code.

This enables separation of concerns, making your applications more portable and easier to manage.


📄 Creating a ConfigMap

Option 1: From literal values

bash

 

kubectl create configmap my-config --from-literal=APP_MODE=production


Option 2: From a file

Create a config file, e.g., app.properties:

text

 

APP_MODE=production

LOG_LEVEL=info

Create ConfigMap:

bash

 

kubectl create configmap my-config --from-file=app.properties


🛠️ Using ConfigMap in Pods

Inject as Environment Variables:

yaml

 

apiVersion: v1

kind: Pod

metadata:

  name: myapp-pod

spec:

  containers:

  - name: myapp

    image: nginx

    envFrom:

    - configMapRef:

        name: my-config


Mount as a Volume:

yaml

 

volumeMounts:

- name: config-volume

  mountPath: /etc/config

 

volumes:

- name: config-volume

  configMap:

    name: my-config

  • Each key in the ConfigMap becomes a file in the mounted directory.

📋 Listing and Managing ConfigMaps

Command

Purpose

kubectl get configmaps

List all ConfigMaps

kubectl describe configmap my-config

View details

kubectl delete configmap my-config

Delete a ConfigMap


🔒 Part 2: Kubernetes Secrets

🔹 What is a Secret?

Secrets are objects used to store sensitive data such as:

  • Passwords
  • API tokens
  • SSH keys
  • TLS certificates

They are base64-encoded for transportation (not encrypted by default unless special encryption-at-rest is configured).


📄 Creating a Secret

Option 1: From literals

bash

 

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


Option 2: From files

bash

 

kubectl create secret generic tls-secret --from-file=cert.pem --from-file=key.pem


🛠️ Using Secrets in Pods

Inject as Environment Variables:

yaml

 

env:

- name: DB_USER

  valueFrom:

    secretKeyRef:

      name: my-secret

      key: username

- name: DB_PASS

  valueFrom:

    secretKeyRef:

      name: my-secret

      key: password


Mount as a Volume:

yaml

 

volumeMounts:

- name: secret-volume

  mountPath: /etc/secret

 

volumes:

- name: secret-volume

  secret:

    secretName: my-secret

  • Each secret key becomes a file.

📋 Managing Secrets

Command

Purpose

kubectl get secrets

List all secrets

kubectl describe secret my-secret

View metadata (base64 encoded values)

kubectl delete secret my-secret

Delete a secret


📦 Part 3: Kubernetes Volume Management

🔹 Why Persistent Storage?

  • Kubernetes Pods are ephemeral — when a Pod dies, data inside it is lost.
  • Volumes provide persistent storage across Pod lifecycles.

📁 Volume Types

Volume Type

Use Case

emptyDir

Temporary scratch space

hostPath

Mounts a file/directory from the host node

PersistentVolume (PV)

Abstracted storage resource

PersistentVolumeClaim (PVC)

Request for storage by a user

ConfigMap/Secret

Configuration storage

NFS/GlusterFS/AWS EBS

Network and cloud storage


🧱 emptyDir Volume Example

yaml

 

volumes:

- name: cache-volume

  emptyDir: {}

  • Created when the Pod starts, deleted when the Pod stops.

🧱 hostPath Volume Example

yaml

 

volumes:

- name: host-volume

  hostPath:

    path: /data/host

  • Mounts /data/host from the Node to the Pod.

️ Warning: Not recommended for cloud or multi-node clusters.


🔗 PersistentVolumes (PV) and PersistentVolumeClaims (PVC)

🔹 What is a PersistentVolume?

  • Provisioned by admins or dynamically via StorageClasses.
  • Represents real storage resources (disk, cloud storage).

🔹 What is a PersistentVolumeClaim?

  • Users create PVCs to request storage without worrying about how it is provisioned.

🧪 Simple PVC Example

PersistentVolume (PV):

yaml

 

apiVersion: v1

kind: PersistentVolume

metadata:

  name: pv-demo

spec:

  capacity:

    storage: 1Gi

  accessModes:

    - ReadWriteOnce

  hostPath:

    path: /mnt/data


PersistentVolumeClaim (PVC):

yaml

 

apiVersion: v1

kind: PersistentVolumeClaim

metadata:

  name: pvc-demo

spec:

  accessModes:

    - ReadWriteOnce

  resources:

    requests:

      storage: 500Mi


🛠️ Mounting a PVC in a Pod

yaml

 

volumes:

- name: storage

  persistentVolumeClaim:

    claimName: pvc-demo


🔧 StorageClasses for Dynamic Provisioning

With StorageClasses, Kubernetes automatically provisions PVs as needed.

yaml

 

apiVersion: storage.k8s.io/v1

kind: StorageClass

metadata:

  name: standard

provisioner: kubernetes.io/aws-ebs

parameters:

  type: gp2

Use in PVC:

yaml

 

storageClassName: standard


📊 ConfigMap vs Secret vs PVC: Quick Comparison

Feature

ConfigMap

Secret

PVC

Purpose

App config

Sensitive data

Persistent data

Encryption

No

Base64 (encryption optional)

Not applicable

Mounted as

Env or file

Env or file

Volume


🛡️ Best Practices

  • Use ConfigMaps for non-sensitive config data only.
  • Use Secrets for anything involving credentials or tokens.
  • Always encrypt Secrets at rest if available.
  • Use PVCs with StorageClasses for dynamic storage provisioning.
  • Avoid hostPath in production environments.

🚀 Summary: What You Learned in Chapter 4


  • ConfigMaps help externalize environment-specific configuration
  • Secrets manage sensitive data like passwords and tokens
  • Volumes and PVCs handle persistent storage needs
  • StorageClasses enable dynamic storage provisioning
  • Separating configuration, secrets, and storage ensures cleaner, scalable, and secure Kubernetes applications

Back

FAQs


✅ 1. What is Kubernetes, and how does it differ from Docker?

Answer: Docker is used to build and run containers, while Kubernetes is a container orchestration platform that manages the deployment, scaling, and operation of multiple containers across a cluster of machines.

✅ 2. Do I need to learn Docker before learning Kubernetes?

Answer: Yes, a basic understanding of Docker is essential since Kubernetes is designed to manage and orchestrate Docker (or OCI-compatible) containers. You'll need to know how to build and run container images before deploying them with Kubernetes.

✅ 3. What is a Pod in Kubernetes?

Answer: A Pod is the smallest deployable unit in Kubernetes. It encapsulates one or more containers that share the same network, storage, and lifecycle. Pods are used to run containerized applications.

✅ 4. How do I expose my application to the internet using Kubernetes?

Answer: You can expose your application using a Service of type LoadBalancer or NodePort. For more advanced routing (e.g., domain-based routing), you can use an Ingress Controller.

✅ 5. What is a Deployment in Kubernetes?

Answer: A Deployment is a Kubernetes object that ensures a specified number of replicas (Pods) are running at all times. It handles rolling updates, rollback, and maintaining the desired state of the application.

✅ 6. Can Kubernetes run locally for learning and development?

Answer: Yes. Tools like Minikube, Kind, and Docker Desktop (with Kubernetes enabled) allow you to run a local Kubernetes cluster on your machine for development and testing.

✅ 7. What’s the difference between ConfigMap and Secret in Kubernetes?

Answer: Both are used to inject configuration data into Pods. ConfigMaps store non-sensitive data like environment variables, while Secrets are designed to store sensitive data like passwords, API tokens, or keys—encrypted at rest.

✅ 8. How does Kubernetes handle application failure or crashes?

Answer: Kubernetes automatically restarts failed containers, replaces them, reschedules Pods to healthy nodes, and ensures the desired state (like the number of replicas) is always maintained.

✅ 9. How do I monitor applications running in Kubernetes?

Answer: Kubernetes integrates well with monitoring tools like Prometheus, Grafana, Kube-state-metrics, and ELK stack (Elasticsearch, Logstash, Kibana). These tools help you track performance, health, and logs.

✅ 10. Is Kubernetes suitable for small projects or just large enterprises?

Answer: While Kubernetes shines in large, scalable environments, it can also be used for small projects—especially with tools like Minikube or cloud-managed clusters. However, simpler alternatives like Docker Compose may be better suited for truly small-scale applications.