404 Not Found

404 Not Found


nginx

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


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:

YAML
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

100%
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

YAML
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:

TEXT
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

BASH
# 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:

TEXT
# Command executed successfully

5. Service and Ingress

(1) ▶ Example: Service Definition

YAML
# 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:

TEXT
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

YAML
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:

TEXT
Deployment.apps/my-app created
Service/my-app-service exposed
Ingress/my-app-ingress created

6. ConfigMap and Secret

(1) ▶ Example: ConfigMap and Secret

YAML
# 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:

TEXT
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
🔒 Security: Secrets are only Base64-encoded; they are not encrypted. In production environments, you should enable etcd encryption or use an external key management solution such as Vault.


7. Liveness and Readiness Probes

(1) ▶ Example: Probe Configuration

YAML
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:

TEXT
The configuration has taken effect.
YAML
# 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

YAML
# 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

Q What is the difference between a Deployment and a StatefulSet?
A A Deployment manages stateless applications (which can be replaced at any time), while a StatefulSet manages stateful applications (with fixed network identities and persistent storage). OrderFlow is a stateless service, so use a Deployment. MySQL is a stateful service, so use a StatefulSet or Operator.
Q How can I achieve zero-downtime deployment?
A 1) Configure a readinessProbe so that Pods are added to the Service only after they are ready; 2) Set the rolling update strategy's 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).
Q Will a Pod automatically retrieve the new configuration after a ConfigMap is updated?
A Configuration via environment variables will not update automatically (the Pod must be restarted). Configuration via volume mounting will update automatically (with a delay of approximately 60 seconds). Spring Cloud Kubernetes supports hot configuration refresh.
Q How do I set the "requests" and "limits" for CPU and memory?
A "Requests" determine scheduling and the minimum guarantee, while "limits" determine the maximum available capacity. We recommend setting "limits" to 2 x "requests." Setting these values too low can result in OOM kills or CPU throttling, while setting them too high wastes resources. Monitor actual usage first, then fine-tune the settings.
Q What are the advantages of Helm Charts?
A Helm is a package manager for K8s that turns all YAML into templates, supporting variable substitution, version control, and one-click deployment, upgrades, and rollbacks. It is well-suited for managing complex deployments involving multiple resources.
Q How do I troubleshoot a Pod startup failure?
A 1) 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


📝 Exercises

  1. 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.

  2. 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.

  3. 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 implement helm upgrade rolling updates and helm rollback rollbacks.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏