在现代微服务架构中,应用发布风险 是一个核心问题。直接全量替换部署可能导致生产环境大面积故障。
金丝雀发布(Canary Release) 是一种安全、渐进的发布策略,它允许我们在一小部分用户中测试新版本的应用,确认稳定后再逐步扩展到全部用户。
本文将通过一个 经典 Nginx Web 服务的金丝雀发布案例,结合 K8s Deployment + Service + Istio VirtualService,完整演示如何实现。

一、实验环境准备
二、案例架构说明
三、源代码与步骤
1. 部署 Nginx v1 版本
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-v1
labels:
app: nginx
version: v1
spec:
replicas: 3
selector:
matchLabels:
app: nginx
version: v1
template:
metadata:
labels:
app: nginx
version: v1
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
configMap:
name: nginx-v1-html
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-v1-html
data:
index.html: |
<h1>Welcome v1</h1>
2. 部署 Nginx v2 版本
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-v2
labels:
app: nginx
version: v2
spec:
replicas: 2
selector:
matchLabels:
app: nginx
version: v2
template:
metadata:
labels:
app: nginx
version: v2
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
configMap:
name: nginx-v2-html
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-v2-html
data:
index.html: |
<h1>Welcome v2</h1>
3. 定义统一 Service(v1 + v2)
apiVersion: v1
kind: Service
metadata:
name: nginx-svc
spec:
selector:
app: nginx
ports:
- port: 80
targetPort: 80
4. 配置 Istio VirtualService(流量按比例分配)
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: nginx-destination
spec:
host: nginx-svc
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: nginx-canary
spec:
hosts:
- "*"
gateways:
- istio-system/ingressgateway
http:
- route:
- destination:
host: nginx-svc
subset: v1
weight: 90
- destination:
host: nginx-svc
subset: v2
weight: 10
四、测试与验证
kubectl apply -f nginx-v1.yaml
kubectl apply -f nginx-v2.yaml
kubectl apply -f nginx-svc.yaml
kubectl apply -f nginx-canary.yaml
kubectl get svc -n istio-system
curl http://<GATEWAY_IP>
<h1>Welcome v1</h1>
<h1>Welcome v2</h1>
五、金丝雀扩展与替换
如果测试验证 v2 稳定,可逐步调整 VirtualService 的权重:
直到 v1 可以安全下线。
六、总结
这个案例可以直接在你的 K8s + Istio 环境落地运行。