Kubernetes Basics for Developers
Docker Compose works fine on one server. Then the app needs a second server, a container dies at 3 a.m. and nobody restarts it, and a deploy means SSHing into each box and hoping the old and new versions don't fight over the port. At that point you're writing your own orchestration in bash scripts, and that's usually when someone says "should we just use Kubernetes?"
This post covers what a developer needs to get productive with Kubernetes (K8s): how a cluster is laid out, pods, Deployments, Services, config and secrets, probes and scaling, and the kubectl commands you'll actually type every day. Everything here runs on a local Minikube cluster.
Kubernetes started at Google and borrowed ideas from Borg, Google's internal cluster manager. Google open-sourced it in 2014 and later donated it to the Cloud Native Computing Foundation (CNCF), which still maintains it. That history explains a lot of its design: it was built for running many services across many machines, not for one app on one VPS.
What Kubernetes Actually Does for You
The short version: you tell Kubernetes what you want ("3 replicas of my API, always"), and it figures out how to get there and keep it that way across your servers. If a node dies, it notices the count dropped and starts replacements somewhere else. You don't write that logic.
Without an orchestrator, these are the problems that show up once you have more than a handful of containers:
- Manual scaling: Starting extra containers by hand when traffic spikes is slow and easy to get wrong.
- No self-healing: When a container crashes, someone has to notice and restart it.
- Service discovery: Container IPs change on every restart. How do other services find them?
- Rolling deployments: Updating an app across many servers without downtime is fiddly.
- Resource waste: Packing workloads onto servers efficiently is hard to do by hand.
Here's what Kubernetes gives you in return:
- Self-healing: Automatically restarts failed containers and reschedules on healthy nodes.
- Horizontal scaling: Scale workloads up or down with a single command or automatically based on CPU/memory.
- Service discovery & load balancing: Stable DNS names and IPs for your services regardless of which pods are running.
- Automated rollouts and rollbacks: Deploy new versions progressively; roll back if health checks fail.
- Secret and config management: Inject environment-specific config and secrets without rebuilding images.
- Storage orchestration: Auto-mount cloud storage (EBS, GCE PD) or local storage as needed.
Kubernetes Cluster Architecture: Control Plane manages Worker Nodes that run Pods containing your containers
Core Concepts: Clusters, Nodes, and Pods
Before writing any YAML, it helps to know how the pieces nest. A cluster contains nodes, nodes run pods, and pods run your containers.
Cluster
The cluster is the whole environment. It has a Control Plane (the part that makes decisions) and one or more Worker Nodes (the machines that run your app). Every kubectl command you run talks to the control plane's API server, never to the nodes directly.
Node
A node is a worker machine, either a VM or a physical server. Each one runs three Kubernetes components:
- kubelet: An agent that talks to the control plane and makes sure the right containers are running.
- kube-proxy: Maintains the network rules that route traffic to and from pods.
- Container runtime: The thing that actually runs containers, usually containerd or CRI-O.
Pod
You don't manage containers directly in Kubernetes. You manage pods. A pod wraps one or more tightly coupled containers that share a network namespace (same IP address) and storage volumes. Most pods run a single container, and that's the default you should reach for.
apiVersion: v1
kind: Pod
metadata:
name: my-api-pod
labels:
app: my-api
spec:
containers:
- name: my-api
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "100m"
limits:
memory: "128Mi"
cpu: "250m"
You can create a Pod directly, but you almost never should in production. A bare pod isn't rescheduled if its node dies. Use a Deployment (or a StatefulSet for stateful workloads), which gives you self-healing and rolling updates.
Setting Up Your Local Environment
You need two things: kubectl (the CLI that talks to your cluster) and a local cluster to practice on. I'd start with Minikube, since it's the least fuss for a single-node cluster on a laptop.
Install kubectl
The Kubernetes CLI. You'll use it to deploy apps, inspect resources, and manage the cluster.
# Linux (amd64)
curl -LO "https://dl.k8s.io/release/$(curl -sL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl && sudo mv kubectl /usr/local/bin/
# macOS (Homebrew)
brew install kubectl
# Windows (Chocolatey)
choco install kubernetes-cli
# Verify installation
kubectl version --client
Install Minikube
A single-node Kubernetes cluster that runs on your own machine. Good enough for development and learning.
# Linux
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
# macOS
brew install minikube
# Start a local Kubernetes cluster
minikube start
# Verify everything is working
kubectl cluster-info
kubectl get nodes
Explore the Kubernetes Dashboard
Minikube ships with the Kubernetes dashboard, a web UI that shows cluster state. Handy while you're still learning which kubectl command shows what.
# Opens the dashboard in your default browser
minikube dashboard
# Check what's running in the cluster
kubectl get all --all-namespaces
Deployments: Declaring Your Desired State
For a stateless app, you'll almost always use a Deployment. You declare the desired state (which image, how many replicas, resource limits) and a controller keeps comparing that to what's actually running and fixing the difference. That reconciliation loop is the core idea behind all of Kubernetes.
Creating a Deployment also creates a ReplicaSet, which manages the actual pods. You'll rarely touch ReplicaSets yourself; the Deployment handles them.
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-api
labels:
app: my-api
spec:
replicas: 3
selector:
matchLabels:
app: my-api
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: my-api
spec:
containers:
- name: my-api
image: my-api:1.0.0
ports:
- containerPort: 3000
resources:
requests:
memory: "128Mi"
cpu: "250m"
limits:
memory: "256Mi"
cpu: "500m"
env:
- name: NODE_ENV
value: "production"
- name: PORT
value: "3000"
# Apply the deployment manifest
kubectl apply -f deployment.yaml
# Watch pods come up in real time
kubectl get pods -w
# Describe a specific pod (shows events, errors)
kubectl describe pod my-api-7d6f8b9c5-xk2p9
# Check deployment rollout status
kubectl rollout status deployment/my-api
# View deployment details
kubectl describe deployment my-api
# Stream logs from a pod
kubectl logs -f my-api-7d6f8b9c5-xk2p9
# Execute a command inside a running pod
kubectl exec -it my-api-7d6f8b9c5-xk2p9 -- /bin/sh
If kubectl get pods shows ErrImagePull or ImagePullBackOff, the node can't find your image. A common cause on Minikube: you built my-api:1.0.0 with your host's Docker, but the cluster has its own image store. Run minikube image load my-api:1.0.0 (or build after eval $(minikube docker-env)), and set imagePullPolicy: IfNotPresent so it doesn't try a registry. kubectl describe pod shows the exact pull error under Events.
Rolling Updates and Rollbacks
With the RollingUpdate strategy, Kubernetes starts new pods before it terminates old ones, so the app stays up during a deploy. With maxUnavailable: 0 as above, it won't take an old pod down until a new one is ready. That last part depends on readiness probes, which we'll get to below.
# Deploy a new version by updating the image
kubectl set image deployment/my-api my-api=my-api:1.1.0
# Monitor the rollout
kubectl rollout status deployment/my-api
# View rollout history
kubectl rollout history deployment/my-api
# Rollback to previous version if something goes wrong
kubectl rollout undo deployment/my-api
# Rollback to a specific revision
kubectl rollout undo deployment/my-api --to-revision=2
Services: Stable Network Endpoints
Pods come and go. Each time one restarts or moves to another node, it gets a new IP. A Service gives you a stable virtual IP (ClusterIP) and DNS name that routes to whichever healthy pods match its selector, whatever their IPs happen to be right now.
A Kubernetes Service acts as a stable load-balanced endpoint in front of ephemeral Pods
There are four Service types:
| Service Type | Accessibility | Typical Use Case |
|---|---|---|
| ClusterIP (default) | Internal to cluster only | Microservice-to-microservice communication |
| NodePort | External via node IP + static port (30000-32767) | Local development, quick testing |
| LoadBalancer | External via cloud provider load balancer | Production external traffic (AWS ELB, GCP LB) |
| ExternalName | Maps service to external DNS name | Accessing external databases or third-party APIs |
apiVersion: v1
kind: Service
metadata:
name: my-api-service
spec:
# Selects pods with this label; must match the Deployment's pod labels
selector:
app: my-api
type: LoadBalancer
ports:
- name: http
protocol: TCP
port: 80 # Port the service listens on
targetPort: 3000 # Port your container listens on
---
# For internal services between microservices, use ClusterIP:
apiVersion: v1
kind: Service
metadata:
name: database-service
spec:
selector:
app: postgres
type: ClusterIP
ports:
- port: 5432
targetPort: 5432
# Apply the service
kubectl apply -f service.yaml
# Check service status
kubectl get services
# On Minikube, get the service URL
minikube service my-api-service --url
# Forward a port for quick local testing (no service needed)
kubectl port-forward pod/my-api-7d6f8b9c5-xk2p9 8080:3000
If requests to a Service hang or get refused, run kubectl get endpoints my-api-service. An empty list means the selector doesn't match any ready pod: usually a label typo, or pods failing their readiness probe. Also note that on Minikube a LoadBalancer Service's EXTERNAL-IP stays <pending> forever unless you run minikube tunnel, because there's no cloud provider to hand out an IP.
ConfigMaps and Secrets
If you bake config into the image, you need a new build for every environment, and your database password ends up in the registry. Kubernetes splits this out: ConfigMaps hold non-sensitive configuration and Secrets hold the sensitive stuff.
Kubernetes Secrets are base64-encoded, not encrypted. Anyone with access to etcd, or with RBAC permission to read Secrets, can read them. In production, turn on encryption at rest for etcd and look at a dedicated secrets manager such as HashiCorp Vault, AWS Secrets Manager, or Sealed Secrets.
Store non-sensitive environment-specific configuration:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
# Key-value pairs become environment variables
NODE_ENV: "production"
LOG_LEVEL: "info"
MAX_CONNECTIONS: "100"
# Or mount entire config files
app.json: |
{
"port": 3000,
"timeout": 30,
"retries": 3
}
Create from the command line:
# From literal values
kubectl create configmap app-config \
--from-literal=NODE_ENV=production \
--from-literal=LOG_LEVEL=info
# From a file
kubectl create configmap app-config --from-file=app.json
# From a directory
kubectl create configmap app-config --from-file=./config/
Store sensitive data (base64-encoded in the manifest):
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
data:
# Values MUST be base64-encoded
# echo -n "mypassword" | base64
DB_PASSWORD: bXlwYXNzd29yZA==
API_KEY: c2VjcmV0YXBpa2V5MTIz
JWT_SECRET: bXlzdXBlcnNlY3JldGp3dA==
Create secrets without checking values into git:
# Create directly from literal (kubectl handles base64)
kubectl create secret generic app-secrets \
--from-literal=DB_PASSWORD=mypassword \
--from-literal=API_KEY=secretapikey123
# From a .env file (keep outside of git)
kubectl create secret generic app-secrets \
--from-env-file=.env.production
# View secret (base64-encoded)
kubectl get secret app-secrets -o yaml
# Decode a secret value
kubectl get secret app-secrets \
-o jsonpath='{.data.DB_PASSWORD}' | base64 --decode
Inject config and secrets into your pod spec:
spec:
containers:
- name: my-api
image: my-api:1.0.0
# Load all keys from ConfigMap as env vars
envFrom:
- configMapRef:
name: app-config
- secretRef:
name: app-secrets
# Or load specific keys
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: app-secrets
key: DB_PASSWORD
# Mount ConfigMap as a volume (for config files)
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: app-config
Scaling and Health Checks
You can scale by hand with one command, or let Kubernetes scale on CPU or memory usage. Either way, new pods only get traffic once they pass their health checks, so the two topics go together.
Manual and Automatic Scaling
# Scale to 5 replicas
kubectl scale deployment my-api --replicas=5
# Scale back down
kubectl scale deployment my-api --replicas=2
# Watch pods scale in real time
kubectl get pods -w
For automatic scaling, use a HorizontalPodAutoscaler (HPA). It watches CPU or memory utilization and adjusts the replica count to keep it near your target. Utilization is measured against the container's requests, so if you don't set requests, the HPA has nothing to compare against. It also needs metrics-server; on Minikube that's minikube addons enable metrics-server. Without it, kubectl get hpa shows <unknown>/70% as the target.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-api-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-api
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
Liveness and Readiness Probes
Two kinds of health check answer two different questions: should this pod get traffic, and should it be restarted?
- Readiness Probe: Is the pod ready for traffic? If it fails, the pod is taken out of the Service's endpoints. It isn't restarted; it just stops getting requests.
- Liveness Probe: Is the process still working? If it fails, the container is restarted. This is for recovering from deadlocks or a stuck state.
spec:
containers:
- name: my-api
image: my-api:1.0.0
ports:
- containerPort: 3000
livenessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 30 # Wait 30s after start before checking
periodSeconds: 10 # Check every 10 seconds
failureThreshold: 3 # Restart after 3 consecutive failures
timeoutSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 10 # Start checking sooner than liveness
periodSeconds: 5
failureThreshold: 3
successThreshold: 1
Keep /healthz (liveness) dumb: it should only confirm the process responds. Don't check the database there, or a short DB outage will make Kubernetes restart every pod at once, which makes things worse. /ready (readiness) is where dependency checks belong: if the database connection pool is exhausted, return 503 and Kubernetes stops sending traffic until it recovers. And if your app is slow to boot, an initialDelaySeconds that's too short on the liveness probe gets you a CrashLoopBackOff where the container is killed before it ever finishes starting.
kubectl Commands You'll Use Daily
You don't need to memorize these. kubectl --help and kubectl explain <resource> are there for exactly that.
| Command | What It Does |
|---|---|
kubectl get pods |
List all pods in current namespace |
kubectl get pods -A |
List pods across all namespaces |
kubectl describe pod <name> |
Detailed pod info including events and errors |
kubectl logs <pod> -f |
Stream logs from a pod in real time |
kubectl exec -it <pod> -- sh |
Open an interactive shell inside a pod |
kubectl apply -f <file.yaml> |
Create or update resources from a YAML file |
kubectl delete -f <file.yaml> |
Delete resources defined in a YAML file |
kubectl get events --sort-by=.lastTimestamp |
View cluster events (great for debugging) |
kubectl top nodes |
Show CPU and memory usage per node |
kubectl top pods |
Show CPU and memory usage per pod |
kubectl explain deployment.spec |
Documentation for any resource field in-CLI |
kubectl config get-contexts |
List all configured clusters/contexts |
kubectl config use-context <name> |
Switch between clusters (dev, staging, prod) |
Namespaces: Logical Isolation Within a Cluster
Namespaces split one cluster into separate virtual clusters, so teams, environments (dev/staging), or apps don't need their own cluster. Be clear about what "isolated" means here: namespaces separate names, RBAC permissions, and resource quotas, but pods in different namespaces can still talk to each other over the network unless you add NetworkPolicies.
# Create a namespace
kubectl create namespace my-team
# Deploy to a specific namespace
kubectl apply -f deployment.yaml -n my-team
# Set a default namespace for your session
kubectl config set-context --current --namespace=my-team
# Kubernetes ships with 4 built-in namespaces:
# default : where resources go if you don't specify
# kube-system : Kubernetes system components (don't touch)
# kube-public : readable by all, used for cluster info
# kube-node-lease : node heartbeat objects
Putting It All Together
Here's one file that combines a ConfigMap, Deployment, Service, and HPA. It's a reasonable starting point for a stateless web service. Note that it targets a production namespace, so create that first (kubectl create namespace production) or the apply fails with namespaces "production" not found.
---
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: production
data:
NODE_ENV: "production"
LOG_LEVEL: "warn"
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-api
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: my-api
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: my-api
spec:
containers:
- name: my-api
image: my-api:1.0.0
ports:
- containerPort: 3000
envFrom:
- configMapRef:
name: app-config
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "500m"
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: my-api-service
namespace: production
spec:
selector:
app: my-api
type: LoadBalancer
ports:
- port: 80
targetPort: 3000
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-api-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-api
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
When I'd Use Kubernetes (and When I Wouldn't)
Before You Commit to It
- It's worth it when you run several services that deploy independently, need zero-downtime rollouts, have traffic that actually varies, or already have someone on the team who can own the cluster.
- I'd skip it for a single Laravel or Node app on one or two servers. Docker Compose, a PaaS, or a managed container service (Cloud Run, ECS Fargate, Fly.io) gets you most of the benefit with far less to operate.
- Don't self-host the control plane for your first production cluster. Use EKS, GKE, or AKS, and expect to pay for the control plane and the load balancers each
LoadBalancerService creates. - Stateful stuff is harder. Running Postgres or Redis in the cluster means StatefulSets, persistent volumes, and backups you now own. A managed database is usually the better call early on.
- The YAML is the easy part. Logging, metrics, RBAC, cluster upgrades every few months, and image registry access are where the real ongoing work is.
If you want to get comfortable with it, do this once end to end on Minikube: deploy one app with a Deployment and a Service, add both probes, scale it, push a broken image on purpose, and roll it back. Once desired state and labels/selectors make sense, most of the other resources follow the same pattern.