Envoy代理核心概念
约 1355 字大约 5 分钟
envoyproxy
2025-06-21
Envoy 是由 Lyft 开发的高性能 L7 代理和通信总线,是 Istio 服务网格的数据平面组件。它支持动态配置、丰富的可观测性和先进的负载均衡算法。本文将深入讲解 Envoy 的核心架构和配置。
整体架构
Listener(监听器)
Listener 定义 Envoy 监听的网络地址和端口:
static_resources:
listeners:
- name: http_listener
address:
socket_address:
address: 0.0.0.0
port_value: 8080
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
codec_type: AUTO
route_config:
name: local_route
virtual_hosts:
- name: backend
domains: ["*"]
routes:
- match:
prefix: "/"
route:
cluster: backend_cluster
http_filters:
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.RouterFilter Chain(过滤器链)
Envoy 的过滤器分为三层:
HTTP 过滤器链配置示例:
http_filters:
# JWT 认证
- name: envoy.filters.http.jwt_authn
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
providers:
auth0:
issuer: https://example.auth0.com/
audiences: ["api.example.com"]
remote_jwks:
http_uri:
uri: https://example.auth0.com/.well-known/jwks.json
cluster: auth0_jwks
timeout: 5s
cache_duration: 600s
rules:
- match:
prefix: /api
requires:
provider_name: auth0
# 速率限制
- name: envoy.filters.http.local_ratelimit
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
stat_prefix: http_local_rate_limiter
token_bucket:
max_tokens: 1000
tokens_per_fill: 100
fill_interval: 1s
# 路由(必须最后一个)
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.RouterCluster 与 Endpoint
Cluster 配置
clusters:
- name: backend_cluster
type: STRICT_DNS # 服务发现类型
connect_timeout: 5s
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: backend_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: backend.default.svc.cluster.local
port_value: 8080
# 健康检查
health_checks:
- timeout: 3s
interval: 10s
unhealthy_threshold: 3
healthy_threshold: 2
http_health_check:
path: /healthz
# TLS 上游
transport_socket:
name: envoy.transport_sockets.tls
typed_config:
"@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
sni: backend.example.com服务发现类型
| 类型 | 描述 |
|---|---|
| STATIC | 静态端点列表 |
| STRICT_DNS | DNS 解析,严格使用返回的所有 IP |
| LOGICAL_DNS | DNS 解析,使用第一个返回的 IP |
| EDS | 通过 xDS API 动态发现 |
| ORIGINAL_DST | 使用连接的原始目标地址 |
Route Configuration(路由配置)
route_config:
name: local_route
virtual_hosts:
- name: api_service
domains: ["api.example.com"]
routes:
# 精确路径匹配
- match:
path: "/api/v1/health"
direct_response:
status: 200
body:
inline_string: '{"status":"ok"}'
# 前缀匹配 + 流量分割
- match:
prefix: "/api/v2"
headers:
- name: x-canary
exact_match: "true"
route:
cluster: backend_v2_cluster
# 正则匹配
- match:
safe_regex:
regex: "/api/v[0-9]+/users/[0-9]+"
route:
cluster: user_service
timeout: 30s
retry_policy:
retry_on: "5xx,connect-failure,retriable-4xx"
num_retries: 3
per_try_timeout: 10s
retry_back_off:
base_interval: 0.1s
max_interval: 1s
# 加权路由(灰度发布)
- match:
prefix: "/api"
route:
weighted_clusters:
clusters:
- name: backend_v1
weight: 90
- name: backend_v2
weight: 10xDS API(动态配置)
xDS 是 Envoy 的动态配置发现协议族:
xDS 通信模式:
- State of the World (SotW):每次下发完整配置
- Incremental (Delta):仅下发变更部分
# 动态配置(从控制平面获取)
dynamic_resources:
lds_config:
resource_api_version: V3
ads: {}
cds_config:
resource_api_version: V3
ads: {}
ads_config:
api_type: GRPC
transport_api_version: V3
grpc_services:
- envoy_grpc:
cluster_name: xds_cluster
clusters:
- name: xds_cluster
type: STATIC
connect_timeout: 5s
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
explicit_http_config:
http2_protocol_options: {}
load_assignment:
cluster_name: xds_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: istiod.istio-system.svc
port_value: 15010负载均衡算法
clusters:
- name: backend
lb_policy: LEAST_REQUEST # 负载均衡策略
lb_subset_config: # 子集负载均衡
fallback_policy: DEFAULT_SUBSET
default_subset:
version: v1
subset_selectors:
- keys: ["version"]
- keys: ["version", "region"]| 算法 | 描述 | 适用场景 |
|---|---|---|
| ROUND_ROBIN | 轮询 | 通用场景 |
| LEAST_REQUEST | 最少活跃请求 | 请求耗时差异大 |
| RING_HASH | 一致性哈希 | 需要会话亲和性 |
| RANDOM | 随机 | 简单场景 |
| MAGLEV | Maglev 一致性哈希 | 大规模缓存场景 |
Circuit Breaking(熔断)
clusters:
- name: backend
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 1024 # 最大连接数
max_pending_requests: 1024 # 最大等待请求
max_requests: 1024 # 最大并发请求
max_retries: 3 # 最大并发重试
track_remaining: true
- priority: HIGH
max_connections: 2048Outlier Detection(异常点检测)
自动识别并驱逐不健康的上游主机:
clusters:
- name: backend
outlier_detection:
consecutive_5xx: 5 # 连续 5 次 5xx 则驱逐
interval: 10s # 检测间隔
base_ejection_time: 30s # 基础驱逐时间
max_ejection_percent: 50 # 最多驱逐 50% 的主机
consecutive_gateway_failure: 3 # 连续网关错误
enforcing_consecutive_5xx: 100 # 执行概率 100%
success_rate_minimum_hosts: 5 # 成功率检测最少主机数
success_rate_stdev_factor: 1900 # 成功率标准差因子可观测性
Stats(统计指标)
stats_sinks:
- name: envoy.stat_sinks.statsd
typed_config:
"@type": type.googleapis.com/envoy.config.metrics.v3.StatsdSink
tcp_cluster_name: statsd_cluster
prefix: envoy
admin:
address:
socket_address:
address: 0.0.0.0
port_value: 9901# 查看统计数据
curl http://localhost:9901/stats
# cluster.backend.upstream_rq_total: 12345
# cluster.backend.upstream_rq_2xx: 12300
# cluster.backend.upstream_rq_5xx: 45
# cluster.backend.upstream_cx_active: 50Tracing(分布式追踪)
tracing:
http:
name: envoy.tracers.opentelemetry
typed_config:
"@type": type.googleapis.com/envoy.config.trace.v3.OpenTelemetryConfig
grpc_service:
envoy_grpc:
cluster_name: otel_collector
service_name: my-serviceAccess Logging(访问日志)
access_log:
- name: envoy.access_loggers.stdout
typed_config:
"@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog
log_format:
json_format:
timestamp: "%START_TIME%"
method: "%REQ(:METHOD)%"
path: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%"
status: "%RESPONSE_CODE%"
duration: "%DURATION%"
upstream: "%UPSTREAM_HOST%"
request_id: "%REQ(X-REQUEST-ID)%"总结
Envoy 是现代服务网格和 API 网关的基石:
- Filter Chain 是核心扩展点,通过组合过滤器实现复杂流量管理
- xDS API 实现配置热更新,无需重启 Envoy
- 异常点检测 + 熔断 提供自动化故障隔离
- 丰富的可观测性(统计/追踪/日志)支撑生产运维
- 在 Istio 中 Envoy 作为 Sidecar 自动注入,开发者无需直接配置
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于