- name
- kubernetes-basics
- description
- Kubernetes container orchestration fundamentals. Use when deploying applications to Kubernetes, managing clusters, or learning container orchestration concepts.
## Purpose
Orchestrate containerized applications across clusters of machines with automated deployment, scaling, and management.
## When to Use
- Deploying containerized applications
- Managing microservices
- Scaling applications
- Implementing CI/CD pipelines
- Managing multi-container applications
## Core Concepts
### Pod
Smallest deployable unit. Contains one or more containers sharing storage/network.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: nginx:1.25
ports:
- containerPort: 80
```
### Deployment
Manages Pod replicas and updates.
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deployment
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: my-container
image: nginx:1.25
ports:
- containerPort: 80
```
### Service
Exposes Pods as network service.
```yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 80
type: LoadBalancer
```
### ConfigMap
Stores configuration data.
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data:
database.url: "postgres://localhost:5432/mydb"
cache.ttl: "3600"
```
### Secret
Stores sensitive data (base64 encoded).
```yaml
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
password: cGFzc3dvcmQ= # base64 encoded "password"
```
## Installation
### Minikube (Local Development)
```bash
# Install
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
# Start
minikube start
# Stop
minikube stop
```
### Kind (Local Development)
```bash
# Install
go install sigs.k8s.io/kind@latest
# Create cluster
kind create cluster
# Delete cluster
kind delete cluster
```
### k3s (Lightweight)
```bash
# Install
curl -sfL https://get.k3s.io | sh -
# Check status
sudo k3s kubectl get nodes
```
### Cloud Providers
- **GKE**: Google Kubernetes Engine
- **EKS**: Amazon Elastic Kubernetes Service
- **AKS**: Azure Kubernetes Service
## kubectl Commands
### Cluster Info
```bash
# Get cluster info
kubectl cluster-info
# Get nodes
kubectl get nodes
# Get namespaces
kubectl get namespaces
```
### Pods
```bash
# List pods
kubectl get pods
# Describe pod
kubectl describe pod <pod-name>
# Get pod logs
kubectl logs <pod-name>
# Exec into pod
kubectl exec -it <pod-name> -- sh
# Delete pod
kubectl delete pod <pod-name>
```
### Deployments
```bash
# Create deployment
kubectl create deployment myapp --image=nginx
# Scale deployment
kubectl scale deployment myapp --replicas=3
# Update image
kubectl set image deployment/myapp nginx=nginx:1.26
# Rollback
kubectl rollout undo deployment/myapp
# Check rollout status
kubectl rollout status deployment/myapp
```
### Services
```bash
# List services
kubectl get services
# Expose deployment
kubectl expose deployment myapp --port=80 --type=LoadBalancer
# Delete service
kubectl delete service myapp
```
### Apply/Delete
```bash
# Apply from file
kubectl apply -f deployment.yaml
# Apply from directory
kubectl apply -f k8s/
# Delete from file
kubectl delete -f deployment.yaml
```
## Common Configurations
### Node.js Application
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nodejs-app
spec:
replicas: 3
selector:
matchLabels:
app: nodejs
template:
metadata:
labels:
app: nodejs
spec:
containers:
- name: nodejs
image: node:20-alpine
command: ["node", "index.js"]
ports:
- containerPort: 3000
env:
- name: PORT
value: "3000"
- name: NODE_ENV
value: "production"
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "200m"
---
apiVersion: v1
kind: Service
metadata:
name: nodejs-service
spec:
selector:
app: nodejs
ports:
- port: 80
targetPort: 3000
type: LoadBalancer
```
### PostgreSQL Database
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:15-alpine
ports:
- containerPort: 5432
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: postgres-storage
mountPath: /var/lib/postgresql/data
volumes:
- name: postgres-storage
persistentVolumeClaim:
claimName: postgres-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
name: postgres-service
spec:
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
type: ClusterIP
```
### Redis Cache
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:7-alpine
ports:
- containerPort: 6379
resources:
requests:
memory: "64Mi"
cpu: "50m"
limits:
memory: "128Mi"
cpu: "100m"
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
spec:
selector:
app: redis
ports:
- port: 6379
targetPort: 6379
type: ClusterIP
```
## Latest Kubernetes Features (2024-2026)
### v1.32 (Penelope) - December 2024
- Dynamic resource allocation for pods (beta)
- AppArmor support (stable)
- CEL for admission control (beta)
- Improved pod disruption budgets
### v1.33 - 2025
- Job resource modification in suspended jobs (beta)
- Enhanced network policies
- Improved CSI volume support
- Better resource metrics
### v1.34 - 2025
- Gateway API (beta)
- Improved pod scheduling
- Enhanced security contexts
- Better observability features
### v1.35 - 2025
- Container resource modification in suspended jobs (alpha → beta)
- Queue controller improvements
- Network policy enhancements
- Storage improvements
### v1.36 - 2025/2026
- Gateway API improvements
- Enhanced job management
- Better multi-cluster support
- Improved security features
## Deployment Strategies
### Rolling Update (Default)
Gradually replaces old pods with new ones.
```yaml
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
```
### Recreate
Shuts down all pods before starting new ones.
```yaml
spec:
strategy:
type: Recreate
```
### Blue/Green
Maintains two versions, switches traffic instantly.
```yaml
# Create two deployments
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-blue
spec:
# ... blue configuration
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-green
spec:
# ... green configuration
```
### Canary
Deploys new version to subset of users.
```yaml
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
name: myapp
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
service:
port: 80
analysis:
interval: 1m
threshold: 5
maxWeight: 50
```
## Ingress
### NGINX Ingress Controller
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
```
## Horizontal Pod Autoscaler
```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: myapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80
```
## Namespaces
### Create Namespace
```yaml
apiVersion: v1
kind: Namespace
metadata:
name: development
```
### Set Default Namespace
```bash
kubectl config set-context --current --namespace=development
```
## Resource Limits
### Pod Resources
```yaml
spec:
containers:
- name: my-container
image: nginx
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
```
## Health Checks
### Liveness Probe
```yaml
spec:
containers:
- name: my-container
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
```
### Readiness Probe
```yaml
spec:
containers:
- name: my-container
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
```
## Best Practices
### Image Management
- Use specific image tags (not `latest`)
- Scan images for vulnerabilities
- Use multi-stage builds
- Keep images small
### Resource Management
- Set resource requests and limits
- Use Horizontal Pod Autoscaler
- Monitor resource usage
- Right-size your pods
### Security
- Use non-root containers
- Scan images for vulnerabilities
- Use secrets for sensitive data
- Enable network policies
- Use RBAC for access control
### Configuration
- Use ConfigMaps for config
- Use Secrets for sensitive data
- Externalize configuration
- Use environment variables
### High Availability
- Use multiple replicas
- Use anti-affinity rules
- Distribute across nodes
- Use persistent storage for stateful apps
## Common Issues
### Pod Not Starting
```bash
# Check pod status
kubectl describe pod <pod-name>
# Check logs
kubectl logs <pod-name>
# Check events
kubectl get events
```
### Image Pull Errors
```bash
# Check image pull secrets
kubectl get secrets
# Create image pull secret
kubectl create secret docker-registry regcred \
--docker-server=<registry> \
--docker-username=<user> \
--docker-password=<pass>
```
### Resource Exhaustion
```bash
# Check node resources
kubectl top nodes
# Check pod resources
kubectl top pods
# Describe node
kubectl describe node <node-name>
```
## Tools
### kubectl
Main CLI tool for Kubernetes.
### k9s
Terminal UI for Kubernetes.
```bash
brew install k9s
```
### Lens
GUI for Kubernetes management.
### Helm
Package manager for Kubernetes.
```bash
# Install
brew install helm
# Add repo
helm repo add stable https://charts.helm.sh/stable
# Install chart
helm install my-release stable/nginx
```
### ArgoCD
GitOps continuous delivery for Kubernetes.
## Monitoring
### Prometheus + Grafana
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: prometheus-config
data:
prometheus.yml: |
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
```
## Troubleshooting
### Debug Pods
```bash
# Check pod status
kubectl get pods
# Describe pod
kubectl describe pod <pod-name>
# View logs
kubectl logs <pod-name>
# Exec into pod
kubectl exec -it <pod-name> -- sh
```
### Debug Services
```bash
# Check service endpoints
kubectl get endpoints <service-name>
# Test service from pod
kubectl run -it --rm debug --image=nicolaka/netshoot --restart=Never -- sh
```
### Debug Network
```bash
# Check network policies
kubectl get networkpolicies
# Check DNS
kubectl run -it --rm debug --image=busybox --restart=Never -- nslookup kubernetes.default
```
## Scripts
### deploy.sh
```bash
#!/bin/bash
kubectl apply -f k8s/
kubectl rollout status deployment/myapp
```
### scale.sh
```bash
#!/bin/bash
kubectl scale deployment myapp --replicas=$1
```
### logs.sh
```bash
GitHubで見る