How to Deploy Kubernetes Without Regretting It
DEV Community

How to Deploy Kubernetes Without Regretting It

The first time I ran kubectl get pods against a real cluster, it took 90 seconds to return an empty list. I thought something was broken. Nothing was broken. That's just how Kubernetes teaches you patience.

Then I deployed my first app, watched it CrashLoopBackOff for an hour, and learned that "deploying to Kubernetes" is mostly a sequence of small humiliations until you understand what the control plane is actually doing.

This is the article I needed then. We're going to deploy a real application - a web API with a database, an ingress, autoscaling, and TLS - from zero to a working cluster. Along the way I'll point out the things I've seen go wrong in production, because that's where most of the value is.

What Kubernetes Actually Is

Kubernetes is a declarative, eventually-consistent control plane for running containers across one or more hosts. You describe what you want (three replicas of an API, a Service that routes to them, an Ingress that terminates TLS), submit that description to the API server, and Kubernetes continuously works to make reality match the description.

If a node dies, Kubernetes reschedules your pods. If you change a Deployment's image tag, Kubernetes rolls the pods. If a pod crashes, Kubernetes restarts it.

The mental model isn't "I'm running containers." It's "I'm submitting desired-state documents to an API, and a bunch of controllers are reconciling reality toward that state." Internalize that and 80% of Kubernetes clicks into place.

Distribution Type Cost Sweet spot kind Local Free CI, fast tests k3d Local Free Local dev that feels like prod minikube Local Free Tutorials, older workflows Docker Desktop Local Free/paid Already using Docker Desktop EKS Managed $0.10/hr + nodes AWS shops GKE Managed Free control plane (Standard) + nodes GCP shops, best managed experience AKS Managed Free control plane + nodes Azure shops k3s Self-managed Free Edge, IoT, Raspberry Pi RKE2 Self-managed Free Self-managed, hardened For learning, use k3d. For real work, use a managed service unless you have a strong reason not to.

Architecture at a Glance

+-------------------------+
| Control Plane           |
| - API server            |
| - etcd (state)          |
| - scheduler             |
| - controller manager    |
| - cloud controllers     |
+-----------+-------------+
            |
+----------------+----------------+
|                |                |
+-----v----+ +------v-----+ +------v-----+
| Node 1   | | Node 2     | | Node 3     |
| - kubelet| | - kubelet  | | - kubelet  |
| - kube-  | | - kube-    | | - kube-    |
| proxy    | | proxy      | | proxy      |
| - pods   | | - pods     | | - pods     |
+----------+ +------------+ +------------+

Your code runs in pods on the nodes. The control plane decides which pod goes on which node, watches for failures, and exposes the API you talk to via kubectl.

Prerequisites and Tooling

You need:

  • docker (or another container runtime, but Docker is fine).
  • kubectl (the CLI). Install from your distro's package manager or download from dl.k8s.io.
  • A cluster. For local: brew install k3d then k3d cluster create dev. For cloud: pick your provider's managed service.
  • helm (the package manager). Optional but I'd recommend it.
  • k9s (the TUI). Not optional, in my opinion. It makes debugging 10x faster.

Verify:

kubectl version --client
kubectl cluster-info
kubectl get nodes

If kubectl get nodes shows a node in Ready state, you have a cluster. Congratulations, you're already past where a lot of tutorials stop.

Project Layout

For anything non-trivial, you'll end up with something like this:

infra/
  k8s/
    base/
      namespace.yaml
      deployment.yaml
      service.yaml
      configmap.yaml
      secret.yaml # template, real secrets via Sealed Secrets or External Secrets
      hpa.yaml
      pdb.yaml
      ingress.yaml
      kustomization.yaml
    overlays/
      staging/
        kustomization.yaml
        patches/
      prod/
        kustomization.yaml
        patches/
  helm/
    values.yaml
    Chart.yaml # if you package your app as a chart

I prefer Kustomize for apps I control (no templating, plain YAML) and Helm for third-party things (cert-manager, ingress-nginx, Prometheus). Mixing is fine and common.

Your First Real Deployment

Enough theory. Here's a complete, working set of manifests for a stateless web API. I'm going to include everything: Namespace, Deployment, Service, ConfigMap, Secret, HPA, PDB, and Ingress.

# namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: myapp
  labels:
    name: myapp
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: myapp
  labels:
    app: api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: api
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        fsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: myregistry.io/myapp-api:v1.2.3 # pinned, never :latest
          ports:
            - containerPort: 3000
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: api-secret
                  key: database-url
            - name: LOG_LEVEL
              valueFrom:
                configMapKeyRef:
                  name: api-config
                  key: log-level
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 3000
            initialDelaySeconds: 5
            periodSeconds: 5
            failureThreshold: 3
          livenessProbe:
            httpGet:
              path: /health/live
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 10
            failureThreshold: 3
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: [ALL]
            runAsNonRoot: true
            runAsUser: 10001
          volumeMounts:
            - name: tmp
              mountPath: /tmp
            - name: cache
              mountPath: /app/cache
      volumes:
        - name: tmp
          emptyDir: {}
        - name: cache
          emptyDir: {}
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchLabels:
                    app: api
                topologyKey: kubernetes.io/hostname
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: api
  namespace: myapp
spec:
  type: ClusterIP
  selector:
    app: api
  ports:
    - name: http
      port: 80
      targetPort: 3000
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config
  namespace: myapp
data:
  log-level: info
  feature-flags.yaml: |
    features:
      new_dashboard: true
      beta_api: false
# secret.yaml (TEMPLATE - do not commit real secrets)
apiVersion: v1
kind: Secret
metadata:
  name: api-secret
  namespace: myapp
type: Opaque
stringData:
  database-url: postgres://app: CH*******@db.myapp.svc :5432/app
# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
  namespace: myapp
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 50
          periodSeconds: 60
# pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api
  namespace: myapp
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: api
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api
  namespace: myapp
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
  ingressClassName: nginx
  tls:
    - hosts: [api.example.com]
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api
                port:
                  number: 80

Apply them in order:

kubectl apply -f namespace.yaml
kubectl apply -f configmap.yaml,secret.yaml,deployment.yaml,service.yaml,hpa.yaml,pdb.yaml,ingress.yaml
kubectl -n myapp rollout status deployment/api

That's a real deployment. Let me walk through what's happening.

Walking Through the Deployment

Namespace. Don't put things in default. Namespaces give you RBAC boundaries, network policy boundaries, and resource quota boundaries. Use them.

Deployment vs Pod. You almost never create a Pod directly. You create a Deployment, which manages a ReplicaSet, which manages Pods. The Deployment handles rolling updates and rollbacks.

strategy: RollingUpdate with maxUnavailable: 0. This means Kubernetes will spin up the new pod before killing the old one. Zero-downtime deploys require this (plus a working readiness probe).

runAsNonRoot and runAsUser: 10001. Don't run as root. Pick a UID above 10000 to avoid collisions with host users. Set it both at the pod level and the container level - the pod-level setting is the default; the container-level setting is the override.

readOnlyRootFilesystem: true. Forces the container's filesystem to be read-only. Mount emptyDir volumes at paths that need writes (/tmp, cache directories). This stops attackers who get RCE from persisting on the filesystem.

capabilities: { drop: [ALL] }. Drop all Linux capabilities. Add back only what you actually need (usually none).

Resources: requests and limits. Requests are what the scheduler uses to place pods and what the kubelet uses for cgroup shares. Limits are the hard cap. Set both. Without requests, the scheduler has no information and will pack pods badly. Without limits, one pod can starve the node.

Readiness probe vs liveness probe. Readiness = "is this pod ready to receive traffic?" If it fails, the pod is removed from the Service's endpoints but not restarted. Liveness = "is this pod healthy?" If it fails, the pod is restarted. They check different things and should hit different endpoints. /health/live should be cheap and never depend on downstream services. /health/ready should check downstream connectivity.

Pod anti-affinity. The preferredDuringSchedulingIgnoredDuringExecution block tells the scheduler to prefer placing replicas on different nodes. Without this, all three replicas can end up on one node, and a node failure takes down your entire app.

HPA behavior. The scaleDown.stabilizationWindowSeconds: 300 keeps the HPA from flapping - after a scale-up, it waits 5 minutes before scaling down. Without this, you'll scale up on a traffic spike and immediately scale down, then scale up again.

PDB. minAvailable: 2 means voluntary disruptions (node drains, upgrades) can't take below 2 replicas. This is what keeps your app alive during cluster upgrades.

Stateful Workloads: StatefulSet, PV, PVC

For databases and other stateful services, use a StatefulSet with persistent volumes. Here's the pattern for a Redis cache that needs persistence:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: myapp
spec:
  serviceName: redis
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redis:7-alpine
          ports:
            - containerPort: 6379
          volumeMounts:
            - name: data
              mountPath: /data
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits: { cpu: 500m, memory: 512Mi }
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        storageClassName: gp3
        resources:
          requests:
            storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: myapp
spec:
  clusterIP: None # headless; DNS returns pod IPs
  selector:
    app: redis
  ports:
    - port: 6379

The volumeClaimTemplates block creates a PVC per replica automatically. The headless Service (clusterIP: None) gives each pod a stable DNS name: redis-0.redis.myapp.svc.cluster.local. That's the trick that makes StatefulSets useful for clustered databases.

For real databases, prefer the operator pattern. There are excellent Postgres operators (CloudNativePG, Zalando Postgres), MySQL operators (Percona, Oracle), and Redis operators (Spotahome). Running your own database on Kubernetes without an operator is asking for a 3am page when failover doesn't work the way you assumed.

Helm and Kustomize: Pick One per Job

Helm Kustomize Model Templated YAML Patched YAML Best for Third-party charts, distribution Your own apps, env-specific overlays Learning curve Moderate (template language) Low (just YAML) Validation Hard (templates render at runtime) Easy (it's always valid YAML) I use Helm for installing things like ingress-nginx, cert-manager, and Prometheus. I use Kustomize for my own app manifests, with overlays for staging/prod. This is a common pattern and it works well.

A Kustomize overlay for staging:

# overlays/staging/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: myapp-staging
resources:
  - ../../base
images:
  - name: myregistry.io/myapp-api
    newTag: v1.2.3-rc.1
patches:
  - target:
      kind: Deployment
      name: api
    patch: |
      - op: replace
        path: /spec/replicas
        value: 1

Deploy with:

kubectl apply -k overlays/staging

Resource Requests, Limits, and QoS

Every pod gets a QoS class based on its resource settings. There are three:

  • Guaranteed: requests == limits for CPU and memory, for every container. Highest priority, last to be killed by the kubelet under node pressure.
  • Burstable: requests set but != limits. Medium priority.
  • BestEffort: no requests or limits. First to be killed.

For production services, aim for Guaranteed. It means the kubelet won't kill your pod unless the node is truly out of memory, and your pod gets the CPU and memory you asked for.

The math: if you set requests: { cpu: 100m, memory: 128Mi } and limits: { cpu: 500m, memory: 512Mi }, the scheduler reserves 100m CPU and 128Mi memory for the pod. Under load, the pod can burst up to 500m CPU (throttled via CFS quota) and 512Mi memory (OOM-killed if it exceeds). If the node runs out of memory, Burstable pods are killed before Guaranteed pods.

CPU throttling is invisible and deadly. If your limit is 500m and you need 600m, you don't crash - you just get slow. Latency p99 jumps from 50ms to 500ms with no error. Monitor CPU throttling (container_cpu_cfs_throttled_seconds_total in Prometheus) and either raise the lim

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.