微服务架构 #

一、微服务概述 #

微服务架构将应用拆分为多个独立服务,每个服务独立部署和扩展。

1.1 微服务特点 #

text
微服务特点
    │
    ├── 服务独立
    │   ├── 独立部署
    │   └── 独立扩展
    │
    ├── 服务通信
    │   ├── REST API
    │   └── gRPC
    │
    ├── 服务发现
    │   └── Kubernetes Service
    │
    └── 配置管理
        └── ConfigMap/Secret

1.2 架构设计 #

text
微服务架构
    │
    ├── API网关
    │   └── 统一入口
    │
    ├── 业务服务
    │   ├── 用户服务
    │   ├── 订单服务
    │   └── 商品服务
    │
    ├── 基础服务
    │   ├── 配置中心
    │   └── 消息队列
    │
    └── 数据存储
        ├── MySQL
        └── Redis

二、服务部署 #

2.1 用户服务 #

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-service
  template:
    metadata:
      labels:
        app: user-service
    spec:
      containers:
      - name: user-service
        image: user-service:v1.0.0
        ports:
        - containerPort: 8080
        env:
        - name: DB_HOST
          value: mysql
        - name: REDIS_HOST
          value: redis
        - name: SERVICE_NAME
          value: user-service
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 200m
            memory: 256Mi
---
apiVersion: v1
kind: Service
metadata:
  name: user-service
spec:
  selector:
    app: user-service
  ports:
  - port: 8080

2.2 订单服务 #

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
spec:
  replicas: 3
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
    spec:
      containers:
      - name: order-service
        image: order-service:v1.0.0
        ports:
        - containerPort: 8080
        env:
        - name: DB_HOST
          value: mysql
        - name: USER_SERVICE_URL
          value: http://user-service:8080
        - name: PRODUCT_SERVICE_URL
          value: http://product-service:8080
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: order-service
spec:
  selector:
    app: order-service
  ports:
  - port: 8080

2.3 商品服务 #

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: product-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: product-service
  template:
    metadata:
      labels:
        app: product-service
    spec:
      containers:
      - name: product-service
        image: product-service:v1.0.0
        ports:
        - containerPort: 8080
        env:
        - name: DB_HOST
          value: mysql
        - name: REDIS_HOST
          value: redis
---
apiVersion: v1
kind: Service
metadata:
  name: product-service
spec:
  selector:
    app: product-service
  ports:
  - port: 8080

三、API网关 #

3.1 部署Nginx网关 #

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: gateway-config
data:
  nginx.conf: |
    events {
      worker_connections 1024;
    }
    http {
      upstream user_service {
        server user-service:8080;
      }
      upstream order_service {
        server order-service:8080;
      }
      upstream product_service {
        server product-service:8080;
      }
      
      server {
        listen 80;
        
        location /api/users {
          proxy_pass http://user_service;
          proxy_set_header Host $host;
        }
        
        location /api/orders {
          proxy_pass http://order_service;
          proxy_set_header Host $host;
        }
        
        location /api/products {
          proxy_pass http://product_service;
          proxy_set_header Host $host;
        }
      }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-gateway
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api-gateway
  template:
    metadata:
      labels:
        app: api-gateway
    spec:
      containers:
      - name: nginx
        image: nginx:1.25
        ports:
        - containerPort: 80
        volumeMounts:
        - name: config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
      - name: config
        configMap:
          name: gateway-config
---
apiVersion: v1
kind: Service
metadata:
  name: api-gateway
spec:
  selector:
    app: api-gateway
  ports:
  - port: 80
  type: LoadBalancer

四、服务发现 #

4.1 Kubernetes Service #

text
服务发现机制
    │
    ├── ClusterIP
    │   └── 集群内部访问
    │
    ├── DNS解析
    │   └── <service-name>.<namespace>.svc.cluster.local
    │
    └── 环境变量
        └── 自动注入服务信息

4.2 跨命名空间访问 #

yaml
# 在production命名空间访问development命名空间服务
env:
- name: USER_SERVICE_URL
  value: http://user-service.development.svc.cluster.local:8080

五、配置中心 #

5.1 集中配置管理 #

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  # 数据库配置
  DB_HOST: mysql
  DB_PORT: "3306"
  DB_NAME: appdb
  
  # Redis配置
  REDIS_HOST: redis
  REDIS_PORT: "6379"
  
  # 日志配置
  LOG_LEVEL: info
  LOG_FORMAT: json

5.2 按环境配置 #

yaml
# 开发环境
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: development
data:
  LOG_LEVEL: debug
---
# 生产环境
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: production
data:
  LOG_LEVEL: info

六、服务网格(Istio) #

6.1 安装Istio #

bash
# 下载Istio
curl -L https://istio.io/downloadIstio | sh -

# 安装Istio
istioctl install --set profile=demo

# 启用自动注入
kubectl label namespace default istio-injection=enabled

6.2 配置VirtualService #

yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: user-service
spec:
  hosts:
  - user-service
  http:
  - route:
    - destination:
        host: user-service
        subset: v1
      weight: 90
    - destination:
        host: user-service
        subset: v2
      weight: 10
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: user-service
spec:
  host: user-service
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2

6.3 配置流量管理 #

yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api-gateway
spec:
  hosts:
  - "api.example.com"
  gateways:
  - api-gateway
  http:
  - match:
    - uri:
        prefix: /api/users
    route:
    - destination:
        host: user-service
  - match:
    - uri:
        prefix: /api/orders
    route:
    - destination:
        host: order-service

七、监控与日志 #

7.1 Prometheus监控 #

yaml
# 服务监控配置
annotations:
  prometheus.io/scrape: "true"
  prometheus.io/port: "8080"
  prometheus.io/path: "/metrics"

7.2 分布式追踪 #

yaml
# Jaeger配置
env:
- name: JAEGER_AGENT_HOST
  value: jaeger-agent.observability.svc.cluster.local
- name: JAEGER_AGENT_PORT
  value: "6831"

八、完整部署 #

8.1 部署脚本 #

bash
#!/bin/bash
# deploy-microservices.sh

echo "Creating namespaces..."
kubectl apply -f namespaces.yaml

echo "Deploying infrastructure..."
kubectl apply -f mysql.yaml
kubectl apply -f redis.yaml

echo "Waiting for infrastructure..."
kubectl wait --for=condition=ready pod -l app=mysql --timeout=300s
kubectl wait --for=condition=ready pod -l app=redis --timeout=300s

echo "Deploying services..."
kubectl apply -f user-service.yaml
kubectl apply -f order-service.yaml
kubectl apply -f product-service.yaml

echo "Deploying API Gateway..."
kubectl apply -f api-gateway.yaml

echo "Deployment completed!"
kubectl get pods

九、最佳实践 #

9.1 服务设计原则 #

text
服务设计原则
    │
    ├── 单一职责
    │   └── 一个服务一个功能
    │
    ├── 独立部署
    │   └── 服务独立部署更新
    │
    ├── 故障隔离
    │   └── 服务故障不影响其他服务
    │
    └── 弹性设计
        └── 重试、熔断、限流

9.2 配置建议 #

配置项 建议
资源限制 设置合理的requests和limits
健康检查 配置liveness和readiness探针
日志格式 使用JSON格式便于收集
监控指标 暴露Prometheus指标

十、总结 #

10.1 核心要点 #

组件 说明
服务拆分 按业务功能拆分
API网关 统一入口
服务发现 Kubernetes Service
配置管理 ConfigMap/Secret
服务网格 Istio流量管理

10.2 学习总结 #

恭喜你完成了Kubernetes完全指南的学习!你已经掌握了从基础到进阶的Kubernetes知识,可以开始在实际项目中应用了。

最后更新:2026-03-28