Kubernetes Deployment
Kubernetes is an operating system for container orchestration—with automatic scaling, rolling updates, and self-healing capabilities—ensuring that applications are always online.
1. What You'll Learn
- K8s Deployment and ReplicaSet: Rolling Updates and Rollback Strategies
- Service types (ClusterIP / NodePort / LoadBalancer) and Ingress routing
- ConfigMap / Secret: Managing Application Configuration and Sensitive Information
- Liveness/Readiness Probes and Health Checks
- Bob uses Helm Charts to manage the K8s deployment configuration for OrderFlow
2. A True Story of Cloud-Native Operations
(1) Pain Point: Manual Operations Are Overwhelmed
The OrderFlow production environment runs on three servers, and Bob manually manages the Docker containers on each server. When a server went down, Bob manually started a new container on another server at 3 a.m. During major sales events, scaling is required. Bob manually starts additional containers and then configures load balancing; each scaling operation takes 30 minutes. Charlie requests auto-scaling, but Bob says, "I can't do that."
(2) The Kubernetes Solution
K8s Declarative Configuration, Automated Management:
apiVersion: apps/v1
kind: Deployment
metadata:
name: orderflow
spec:
replicas: 3
template:
spec:
containers:
- name: orderflow
image: orderflow-service:latest
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 8080 }
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 8080 }
Node down? K8s automatically restarts the Pod on another node. Traffic spike? HPA automatically scales out.
(3) Revenue
After Bob deployed OrderFlow using K8s: node failures are automatically recovered (MTTR dropped from 2 hours to 30 seconds), and HPA automatically scales (scaling up time dropped from 30 minutes to 2 minutes). Bob no longer has to fix servers in the middle of the night.
3. Core K8s Resources
(1) Resource Dependencies
graph TD
A[Ingress<br/>External Access] --> B[Service<br/>Internal LB]
B --> C[Deployment<br/>Pod Template]
C --> D[ReplicaSet<br/>Pod Replicas]
D --> E[Pod<br/>Container Group]
E --> F[Container<br/>OrderFlow App]
G[ConfigMap] --> F
H[Secret] --> F
| Resources | Responsibilities | Analogies |
|---|---|---|
| Pod | The smallest deployment unit, containing containers | A process group |
| Deployment | Managing the Number of Pod Replicas and Update Policies | Process Manager |
| Service | Provides a stable access point for Pods | Load Balancer |
| Ingress | HTTP Routing Rules | Nginx Reverse Proxy |
| ConfigMap | Non-sensitive configuration | Configuration file |
| Secret | Sensitive Configuration | Encrypted Configuration File |
4. Deployment and Rolling Updates
(1) ▶ Example: OrderFlow Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: orderflow
labels:
app: orderflow
spec:
replicas: 3
selector:
matchLabels:
app: orderflow
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
template:
metadata:
labels:
app: orderflow
spec:
containers:
- name: orderflow
image: registry.example.com/orderflow-service:1.0.0
ports:
- containerPort: 8080
- containerPort: 8081
env:
- name: SPRING_PROFILES_ACTIVE
value: "prod"
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: orderflow-config
key: database.host
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: orderflow-secrets
key: database.password
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
Output:
Deployment.apps/my-app created
Service/my-app-service exposed
Ingress/my-app-ingress created
| Parameter (Rolling Update) | Meaning | Recommended Value |
|---|---|---|
maxUnavailable |
Maximum number of unavailable Pods | 1 (or 25%) |
maxSurge |
Maximum number of instances exceeding the target | 1 (or 25%) |
(2) ▶ Example: Rolling Updates and Rollbacks
# Update image version (triggers rolling update)
kubectl set image deployment/orderflow orderflow=registry.example.com/orderflow-service:2.0.0
# Check rollout status
kubectl rollout status deployment/orderflow
# Rollback to previous version
kubectl rollout undo deployment/orderflow
# View rollout history
kubectl rollout history deployment/orderflow
Output:
# Command executed successfully
5. Service and Ingress
(1) ▶ Example: Service Definition
# ClusterIP Service (internal access)
apiVersion: v1
kind: Service
metadata:
name: orderflow
spec:
selector:
app: orderflow
ports:
- name: http
port: 80
targetPort: 8080
- name: management
port: 8081
targetPort: 8081
type: ClusterIP
Output:
Configuration applied successfully
| Service Type | Access Scope | Applicable Scenarios |
|---|---|---|
| ClusterIP | Within the cluster | Inter-microservice calls |
| NodePort | External to the cluster (node IP:port) | Simple external access |
| LoadBalancer | Cloud Provider Load Balancer | Production Environment (Cloud) |
| ExternalName | DNS CNAME | Reference to External Service |
(2) ▶ Example: Ingress Routing
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: orderflow-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: api.orderflow.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: orderflow
port:
number: 80
tls:
- hosts:
- api.orderflow.example.com
secretName: orderflow-tls
Output:
Deployment.apps/my-app created
Service/my-app-service exposed
Ingress/my-app-ingress created
6. ConfigMap and Secret
(1) ▶ Example: ConfigMap and Secret
# ConfigMap: non-sensitive configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: orderflow-config
data:
database.host: "mysql-service"
database.name: "orderflow"
redis.host: "redis-service"
spring.profiles.active: "prod"
management.server.port: "8081"
---
# Secret: sensitive configuration (base64 encoded)
apiVersion: v1
kind: Secret
metadata:
name: orderflow-secrets
type: Opaque
data:
database.password: b3JkZXJmbG93MTIz # base64 of "orderflow123"
redis.password: cmVkaXNwYXNz # base64 of "redispass"
jwt.private-key: LS0tLS1CRUdJTi... # base64 of private key
Output:
Configuration applied successfully
| Dimension | ConfigMap | Secret |
|---|---|---|
| Data Type | Plaintext | Base64-encoded |
| Applicable Content | Non-sensitive Configuration | Passwords, Keys, Certificates |
| Storage Method | etcd (plaintext) | etcd (encrypted) |
| Size Limit | 1MB | 1MB |
7. Liveness and Readiness Probes
(1) ▶ Example: Probe Configuration
spec:
containers:
- name: orderflow
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60
periodSeconds: 30
timeoutSeconds: 3
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
startupProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 30
Output:
The configuration has taken effect.
# application-prod.yml: Enable liveness/readiness groups
management:
endpoint:
health:
show-details: always
group:
liveness:
include: livenessState
readiness:
include: readinessState, db, redis
| Probe Type | Purpose | Consequences of Failure |
|---|---|---|
livenessProbe |
Check if the process is running | Restart the container |
readinessProbe |
Check if ready to receive traffic | Remove from Service |
startupProbe |
Check if the application has finished launching | Disable other probes during launch |
8. Comprehensive Example: Complete Deployment of OrderFlow on K8s
# k8s/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: orderflow
---
# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: orderflow-config
namespace: orderflow
data:
SPRING_PROFILES_ACTIVE: "prod"
DB_HOST: "mysql-service"
DB_NAME: "orderflow"
REDIS_HOST: "redis-service"
MANAGEMENT_SERVER_PORT: "8081"
---
# k8s/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: orderflow-secrets
namespace: orderflow
type: Opaque
data:
DB_PASSWORD: b3JkZXJmbG93MTIz
---
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: orderflow
namespace: orderflow
spec:
replicas: 3
selector:
matchLabels: { app: orderflow }
strategy:
rollingUpdate: { maxUnavailable: 1, maxSurge: 1 }
template:
metadata:
labels: { app: orderflow }
spec:
containers:
- name: orderflow
image: registry.example.com/orderflow-service:1.0.0
ports:
- { containerPort: 8080 }
- { containerPort: 8081 }
envFrom:
- configMapRef: { name: orderflow-config }
- secretRef: { name: orderflow-secrets }
resources:
requests: { memory: "512Mi", cpu: "250m" }
limits: { memory: "1Gi", cpu: "500m" }
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 8080 }
initialDelaySeconds: 60; periodSeconds: 30; failureThreshold: 3
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 8080 }
initialDelaySeconds: 30; periodSeconds: 10; failureThreshold: 3
---
# k8s/service.yaml
apiVersion: v1
kind: Service
metadata:
name: orderflow
namespace: orderflow
spec:
selector: { app: orderflow }
ports:
- { name: http, port: 80, targetPort: 8080 }
type: ClusterIP
---
# k8s/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: orderflow-ingress
namespace: orderflow
spec:
ingressClassName: nginx
rules:
- host: api.orderflow.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service: { name: orderflow, port: { number: 80 } }
❓ FAQ
maxUnavailable to 0; 3) Use the preStop hook for graceful shutdown (sleep 10—wait for traffic to drain); 4) Implement graceful shutdown in the application (server.shutdown=graceful).kubectl describe pod <name> Check Events; 2) kubectl logs <name> Check container logs; 3) kubectl get events --sort-by=.metadata.creationTimestamp Check cluster events.📖 Summary
- Deployment manages Pod replicas and rolling updates; maxUnavailable and maxSurge control the update pace
- Service: Provides a stable access point to Pods—internal via ClusterIP, external via LoadBalancer
- Ingress configures HTTP routing and TLS, which is equivalent to a reverse proxy in K8s
- ConfigMaps are used to manage non-sensitive configuration, while Secrets are used to manage sensitive information (Base64-encoded)
- The Liveness, Readiness, and Startup probes monitor the liveness, readiness, and startup states, respectively.
- Declarative configuration + rolling updates = zero-downtime deployment
📝 Exercises
-
Basic Exercise (Difficulty: ⭐): Write the Deployment and Service YAML files for OrderFlow, deploy them to a local K8s cluster (minikube or kind), and verify that the application is accessible.
-
Advanced Exercise (Difficulty: ⭐⭐): Add ConfigMap, Secret, and Ingress configurations to enable access via an external domain. Configure Liveness and Readiness probes to simulate Pod failures and verify automatic recovery.
-
Challenge (Difficulty: ⭐⭐⭐): Use a Helm Chart to manage the K8s deployment of OrderFlow, supporting variable substitution via
values.yaml(image version, number of replicas, resource configuration), and implementhelm upgraderolling updates andhelm rollbackrollbacks.



