Kubernetes Fundamentals — Pods, Deployments and Services

Run and operate container workloads with Kubernetes pods, deployments, services, configuration, secrets, probes, kubectl, and scaling.

Est. 45 min Updated Suggest a fix
// Part 01 — The orchestration problem

Kubernetes Keeps the Desired Workload Running

A container can run well on one laptop and still fail when a host restarts or demand changes. Kubernetes is a system for managing containerized workloads across a cluster. You describe a desired state in API objects; controllers continually compare that desired state with what is running and try to reconcile the difference. Kubernetes does not make an application stateless, secure, or observable by default—you still design those properties.

A cluster is made of a control plane and worker nodes. The control plane stores and coordinates cluster objects. Nodes run pods, usually through a container runtime. In managed Kubernetes, the provider operates part of the control plane, but your team remains responsible for application configuration, identity, network policy, cluster upgrade planning, and workload health.

ObjectPurposeThink of it as
PodSmallest schedulable unit; one or more tightly coupled containersA workload instance with shared networking
DeploymentDeclares and updates a replicated set of podsA controller for stateless application replicas
ServiceProvides a stable network endpoint for selected podsA name and traffic-distribution boundary
ConfigMapStores non-secret configuration dataRuntime settings separated from an image
SecretStores sensitive configuration in the Kubernetes APIA sensitive value with access controls—not automatic encryption everywhere
💡 Note
A Pod is replaceable. Do not rely on its IP address or local filesystem as permanent storage. Use a Service for stable access and an appropriate persistent storage system for data that must survive replacement.
// Part 02 — Workload manifest

Declare a Deployment, Not a Hand-Managed Pod

A Deployment describes a desired replica count and a pod template. The controller creates and replaces pods as needed. The selector must match the template labels; labels connect this Deployment to the pods it manages. The sample below assumes an application image listens on port 8080 and exposes a /health endpoint. Use an image that your team owns and has tested—this lesson does not publish a real application image.

deployment.yaml
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  labels:
    app: orders-api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: orders-api
  template:
    metadata:
      labels:
        app: orders-api
    spec:
      containers:
        - name: api
          image: ghcr.io/example-org/orders-api:replace-with-commit-sha
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 15
            periodSeconds: 20

Resource requests help the scheduler find a node with enough capacity. Limits constrain resource consumption but can also affect latency and availability when set poorly. The values above are teaching placeholders, not sizing guidance; load-test the actual application and tune them from observed use. Use an immutable image reference from the release pipeline instead of leaving the illustrative tag in a real deployment.

⚠️ Important
A liveness probe that fails too aggressively can repeatedly restart a slow but recoverable app. Match probe paths and timing to real startup and health behavior, and use a startup probe when an app legitimately needs longer to start.
// Part 03 — Expose the pods

Use a Service for a Stable Endpoint

Pod addresses change as pods are rescheduled. A Service selects pods by labels and provides a stable virtual endpoint for clients. A ClusterIP Service is reachable inside the cluster. External access normally uses a controlled ingress or load balancer configured for the cluster; do not make a service public simply to test an application.

service.yaml
yaml
apiVersion: v1
kind: Service
metadata:
  name: orders-api
spec:
  type: ClusterIP
  selector:
    app: orders-api
  ports:
    - name: http
      port: 80
      targetPort: http

The Service selector uses the same app: orders-api label as the Deployment's pod template. The Service accepts traffic on port 80 and sends it to the named container port. If the labels do not match, the Service has no endpoints. If the app binds only to localhost inside the container, other pods cannot reach it through the Pod network.

Service typeTypical useExposure
ClusterIPInternal API or database endpointInside the cluster
NodePortSpecialized access or simple test environmentsNode address and allocated port; protect carefully
LoadBalancerProvider-managed external entry pointMay provision a public or private load balancer
// Part 04 — Configuration

Keep Settings Outside the Container Image

A ConfigMap carries non-sensitive settings such as a log level or a service name. A Secret holds sensitive values such as a database password, but creating a Secret object does not by itself guarantee encryption at rest or safe access. Configure the cluster's secret encryption and access controls, or use an approved external secrets manager. Never commit real secret values to a manifest or expose them in a public lesson repository.

app-config.yaml
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: orders-api-config
data:
  LOG_LEVEL: "info"
  UPSTREAM_TIMEOUT_SECONDS: "3"
---
apiVersion: v1
kind: Secret
metadata:
  name: orders-api-runtime
type: Opaque
stringData:
  DATABASE_URL: REPLACE_WITH_SECRET_FROM_APPROVED_SECRET_STORE

The Secret value shown is a placeholder, not a credential. In a real system, sync or inject runtime secrets from the organization's approved secret manager and protect access with workload identity and RBAC. Kubernetes stores Secret values as encoded data in its API representation; encoding is not encryption. If applying a manifest from a file, keep real values in a protected source that is never committed or uploaded as a lesson artifact.

Reference configuration using environment variables or mounted files in the pod template. The container image stays the same across environments; the environment supplies the settings. Avoid printing secret environment variables in application logs or diagnostic output.

deployment-config-fragment.yaml
yaml
spec:
  containers:
    - name: api
      image: ghcr.io/example-org/orders-api:replace-with-commit-sha
      envFrom:
        - configMapRef:
            name: orders-api-config
        - secretRef:
            name: orders-api-runtime
// Part 05 — Apply and inspect

Use kubectl to Observe Before You Change

kubectl is the command-line client for the Kubernetes API. Confirm the current context and namespace before applying manifests; a familiar command can still target the wrong cluster. In a local training cluster, the following commands apply the workload, inspect its rollout, and show pod state. In a shared or production cluster, use the team's authorized context and reviewed change process.

inspect-workload.sh
bash
# Check the selected cluster context before making changes.
kubectl config current-context
kubectl config view --minify

# Apply only the reviewed manifests in the current namespace.
kubectl apply -f app-config.yaml
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

# Observe readiness and recent events.
kubectl rollout status deployment/orders-api
kubectl get deployments,pods,services -l app=orders-api
kubectl describe deployment/orders-api
kubectl logs -l app=orders-api --all-containers=true --tail=100

When a pod is not ready, inspect the Deployment and pod events, then read the container logs. Check for image pull failures, wrong ports, missing configuration, insufficient resources, and a probe path that does not exist. Avoid repeatedly deleting pods before finding the cause; the controller may simply create the same failing pod again.

🎯 Pro Tip
Treat kubectl config current-context as a pre-flight check. Keep production credentials and contexts separate from local learning clusters, and use namespace-scoped permissions where practical.
// Part 06 — Health and updates

Probes Tell Kubernetes When to Route or Restart

A readiness probe answers whether the container should receive traffic now. A liveness probe answers whether it should be restarted. A startup probe can give slow-starting applications time before liveness checks begin. These signals must match application behavior: readiness can depend on required startup initialization, while liveness should detect a process that cannot recover without a restart. A dependency outage is not always a reason to restart every app pod.

A Deployment performs rolling updates according to its rollout strategy. Watch the rollout and define what happens if the new version is not ready. Keep a stable Service selector, test backward-compatible configuration changes, and remember that rolling back code does not automatically undo a database migration. Use staged migration patterns so old and new app versions can safely overlap.

  1. Set readiness to reflect whether the pod can safely serve requests.
  2. Use liveness only for failures that a process restart can plausibly fix.
  3. Set resource requests based on observed workload behavior and cluster capacity.
  4. Watch rollout status and application metrics during an update.
  5. If the release harms users, use a reviewed rollback or forward-fix procedure and verify the outcome.
// Part 07 — Scale and operate

Scale Replicas Without Hiding Bottlenecks

A Deployment can scale to a desired number of replicas. More replicas may help when requests can be handled in parallel, but they do not fix a saturated database, a shared lock, or a downstream rate limit. Horizontal autoscaling needs resource requests and metrics; set scaling boundaries and understand how added replicas affect dependencies. Stateful systems need storage and scheduling design beyond simply increasing a replica count.

scale-and-update.sh
bash
# Set a replica count for a controlled training deployment.
kubectl scale deployment/orders-api --replicas=3
kubectl rollout status deployment/orders-api

# Inspect the Service and its selected endpoints.
kubectl get service orders-api
kubectl get endpoints orders-api

# Revert the Deployment to its previous revision if the rollout is unhealthy.
kubectl rollout undo deployment/orders-api
kubectl rollout status deployment/orders-api

An imperative scale command changes live desired state. If manifests are the source of truth, update the declared replica count too, or the next apply can revert your manual change. In production, make the change through the reviewed deployment process so it is recorded and reproducible.

📌 Real World Example
A delivery app may need more API replicas during a promotion, but first check whether the database connection pool and order queue can handle the extra concurrency. Scale the whole request path, not just the front-end pods.
// Part 08 — Pitfalls

Common Mistakes

Creating a bare Pod as the production workload

Why: A deleted or failed pod has no higher-level controller to recreate the desired replicas.

Fix: Use a Deployment for stateless services and let it manage pods and rollouts.

Putting real credentials in a ConfigMap or committed Secret manifest

Why: ConfigMaps are not secret stores, and encoded Secret data is not encryption.

Fix: Use an approved secret manager, cluster encryption and RBAC, and keep real values out of Git.

Using liveness to check every downstream dependency

Why: A dependency outage can trigger a restart storm that makes recovery worse.

Fix: Separate process health from readiness and dependency health; alert on the dependency itself.

Scaling pods without checking downstream capacity

Why: More callers can overload a database or API that is already the bottleneck.

Fix: Observe end-to-end capacity and rate limits, then scale with tested bounds.

// Part 09 — Practice

Deploy and Troubleshoot an Order API

Practice

Run a small workload in a local or sandbox cluster

  1. Write a Deployment manifest with two replicas, matching labels, a tested image, and resource requests.
  2. Create a ClusterIP Service and explain how its selector finds the Deployment pods.
  3. Add a ConfigMap for a non-sensitive setting and describe the safe source for a real runtime secret.
  4. Apply the manifests in a local cluster; inspect rollout status, events, and logs with kubectl.
  5. Change the replica count, verify the result, and explain why the declarative manifest must also be updated.

Hint: Use a local learning cluster or review the manifests without applying them. Always verify kubectl context before changing a shared cluster.

🎯 Key Takeaways

  • ✓Kubernetes controllers reconcile declared desired state; use Deployments for replaceable stateless application pods.
  • ✓Pods are ephemeral; Services provide stable in-cluster access by selecting matching pod labels.
  • ✓ConfigMaps hold non-secret settings; Secrets require encryption, access controls, and safe sourcing beyond simple encoding.
  • ✓Readiness, liveness, and startup probes have different jobs; configure them around actual application health behavior.
  • ✓Use kubectl context checks, rollout status, events, and logs to troubleshoot methodically.
  • ✓Scale with awareness of databases, queues, and other dependencies; keep declarative configuration aligned with live changes.

Next

What comes next

Package Kubernetes apps with Helm charts and deploy them declaratively from Git with Argo CD, including rollbacks and environment promotion.

Lesson 12 · Helm and GitOps with Argo CD →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...