Envoy代理与API网关深度实战:从过滤器链到xDS动态配置与WASM扩展的全链路流量治理全解析

举报
江南清风起 发表于 2026/10/18 16:07:19 2026/10/18
【摘要】 Envoy代理与API网关深度实战:从过滤器链到xDS动态配置与WASM扩展的全链路流量治理全解析 引言Envoy是现代云原生基础设施中最核心的网络代理——Istio的数据面、AWS App Mesh、Cloudflare的数据路径、无数API网关的底层引擎。理解Envoy意味着理解了服务网格和API网关的底层机制。Envoy的核心设计理念是"网络对应用透明"——通过过滤器链、xDS动态配...

Envoy代理与API网关深度实战:从过滤器链到xDS动态配置与WASM扩展的全链路流量治理全解析

引言

Envoy是现代云原生基础设施中最核心的网络代理——Istio的数据面、AWS App Mesh、Cloudflare的数据路径、无数API网关的底层引擎。理解Envoy意味着理解了服务网格和API网关的底层机制。Envoy的核心设计理念是"网络对应用透明"——通过过滤器链、xDS动态配置、L7协议感知、可观测性内置,Envoy实现了高性能、可扩展、可编程的网络代理。本文从Envoy架构出发,系统性地讲解过滤器链机制、Listener/Route/Cluster配置、xDS动态配置协议、HTTP过滤器开发、WASM扩展、TLS配置、可观测性、性能调优,通过大量可运行配置和代码示例帮助读者掌握Envoy生产实践。

一、Envoy架构与核心概念

1.1 架构总览

# Envoy核心架构
#
#   Listener(监听器)
#     └─ Filter Chain(过滤器链)
#          ├─ Network Filter(L4):TCP/UDP处理
#          │   └─ HTTP Filter(L7):HTTP/gRPC处理
#          │        ├─ Router Filter:路由匹配
#          │        ├─ Rate Limit Filter:限流
#          │        ├─ CORS Filter:跨域
#          │        └─ JWT Filter:认证
#          └─ Cluster(上游集群):负载均衡/健康检查/熔断
#
# xDS动态配置协议:
#   LDS → Listener配置
#   RDS → Route配置
#   CDS → Cluster配置
#   EDS → Endpoint配置
#   SDS → Secret/TLS配置
#   ADS → 聚合xDS(单连接顺序更新)
#
# 数据流:
#   Client → Listener → Filter Chain → Router → Cluster → Endpoint → Server
#            (L4过滤)   (L7过滤)        (路由)    (负载均衡) (健康端点)

1.2 Envoy静态配置

# envoy.yaml - 基础静态配置
node:
  cluster: my-cluster
  id: envoy-1
  metadata:
    namespace: production

admin:
  address:
    socket_address:
      address: 127.0.0.1
      port_value: 9901

# 静态资源配置
static_resources:
  listeners:
  # HTTP Listener
  - name: listener_http
    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
          # 访问日志
          access_log:
          - name: envoy.access_loggers.file
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog
              path: /dev/stdout
              format: "[%START_TIME%] \"%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%\" %RESPONSE_CODE% %DURATION%ms\n"
          # HTTP路由
          route_config:
            name: local_route
            virtual_hosts:
            - name: backend
              domains: ["*"]
              routes:
              - match:
                  prefix: "/api/v1/users"
                route:
                  cluster: user_service
                  timeout: 5s
              - match:
                  prefix: "/api/v1/orders"
                route:
                  cluster: order_service
                  timeout: 10s
              - match:
                  prefix: "/"
                route:
                  cluster: frontend_service
                  timeout: 30s
          # HTTP过滤器链
          http_filters:
          - name: envoy.filters.http.cors
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
              providers:
                google:
                  issuer: https://accounts.google.com
                  audiences: ["my-app"]
                  remote_jwks:
                    http_uri:
                      uri: https://www.googleapis.com/oauth2/v3/certs
                      cluster: google_jwks
                      timeout: 5s
              rules:
              - match:
                  prefix: "/api"
                requires:
                  provider_name: google
          - name: envoy.filters.http.router
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
  
  # TCP Listener(原始TCP代理)
  - name: listener_tcp
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 5432
    filter_chains:
    - filters:
      - name: envoy.filters.network.tcp_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy
          stat_prefix: postgres_proxy
          cluster: postgres_cluster
  
  # Cluster定义
  clusters:
  # HTTP服务集群
  - name: user_service
    type: STRICT_DNS            # DNS动态解析
    lb_policy: ROUND_ROBIN
    dns_lookup_family: V4_ONLY
    connect_timeout: 0.5s
    # 健康检查
    health_checks:
    - timeout: 1s
      interval: 10s
      unhealthy_threshold: 3
      healthy_threshold: 2
      http_health_check:
        path: /health
    # 熔断
    circuit_breakers:
      thresholds:
      - priority: DEFAULT
        max_connections: 100
        max_pending_requests: 50
        max_requests: 200
        max_retries: 3
        max_connection_pools: 10
    # 异常检测
    outlier_detection:
      consecutive_5xx: 5
      interval: 30s
      base_ejection_time: 30s
      max_ejection_percent: 50
    load_assignment:
      cluster_name: user_service
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: user-service.production.svc.cluster.local
                port_value: 8080
  
  # 外部服务集群(google JWKS)
  - name: google_jwks
    type: STRICT_DNS
    connect_timeout: 5s
    transport_socket:
      name: envoy.transport_sockets.tls
      typed_config:
        "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.TlsConfig
        sni: www.googleapis.com
    load_assignment:
      cluster_name: google_jwks
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: www.googleapis.com
                port_value: 443

二、xDS动态配置

2.1 ADS配置

# 使用ADS(Aggregated Discovery Service)动态配置
# 所有xDS通过单连接顺序更新,避免配置不一致

dynamic_resources:
  # 动态Listener
  lds_config:
    ads: {}
    resource_api_version: V3
  # 动态Route
  rds_config:
    ads: {}
    resource_api_version: V3
  # 动态Cluster
  cds_config:
    ads: {}
    resource_api_version: V3

# ADS配置
ads_config:
  api_type: DELTA_GRPC        # GRPC | DELTA_GRPC
  transport_api_version: V3
  grpc_services:
  - envoy_grpc:
      cluster_name: xds_cluster
  set_node_on_first_message_only: true

# xDS管理集群
static_resources:
  clusters:
  - name: xds_cluster
    connect_timeout: 1s
    type: STRICT_DNS
    http2_protocol_options: {}
    load_assignment:
      cluster_name: xds_cluster
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: xds-server.example.com
                port_value: 18000

2.2 xDS控制面开发

// Go xDS Server实现(简化版)
package main

import (
    "context"
    "log"
    "net"
    "google.golang.org/grpc"
    corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
    clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
    endpointv3 "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
    listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
    routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
    discoverygrpc "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
    "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
    "github.com/envoyproxy/go-control-plane/pkg/server/v3"
)

func main() {
    ctx := context.Background()
    
    // 创建配置缓存
    c := cache.NewLinearCache("node-id")
    
    // 构建Cluster配置
    cluster := &clusterv3.Cluster{
        Name: "backend",
        Type: clusterv3.Cluster_STRICT_DNS,
        ConnectTimeout: &durationpb.Duration{Seconds: 1},
        LoadAssignment: &endpointv3.ClusterLoadAssignment{
            ClusterName: "backend",
            Endpoints: []*endpointv3.LocalityLbEndpoints{
                {
                    LbEndpoints: []*endpointv3.LbEndpoint{
                        {
                            HostIdentifier: &endpointv3.LbEndpoint_Endpoint{
                                Endpoint: &endpointv3.Endpoint{
                                    Address: &corev3.Address{
                                        Address: &corev3.Address_SocketAddress{
                                            SocketAddress: &corev3.SocketAddress{
                                                Address: "backend.production.svc",
                                                PortSpecifier: &corev3.SocketAddress_PortValue{
                                                    PortValue: 8080,
                                                },
                                            },
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    }
    
    // 构建Route配置
    routeConfig := &routev3.RouteConfiguration{
        Name: "my-route",
        VirtualHosts: []*routev3.VirtualHost{
            {
                Name: "backend",
                Domains: []string{"*"},
                Routes: []*routev3.Route{
                    {
                        Match: &routev3.RouteMatch{
                            PathSpecifier: &routev3.RouteMatch_Prefix{
                                Prefix: "/",
                            },
                        },
                        Action: &routev3.Route_Route{
                            Route: &routev3.RouteAction{
                                ClusterSpecifier: &routev3.RouteAction_Cluster{
                                    Cluster: "backend",
                                },
                            },
                        },
                    },
                },
            },
        },
    }
    
    // 构建Listener配置
    listener := &listenerv3.Listener{
        Name: "listener-0",
        Address: &corev3.Address{
            Address: &corev3.Address_SocketAddress{
                SocketAddress: &corev3.SocketAddress{
                    Address: "0.0.0.0",
                    PortSpecifier: &corev3.SocketAddress_PortValue{
                        PortValue: 8080,
                    },
                },
            },
        },
    }
    
    // 更新缓存
    c.SetListener(listener)
    c.SetRoute(routeConfig)
    c.SetCluster(cluster)
    
    // 创建xDS Server
    srv := server.NewServer(ctx, c, nil)
    
    // 启动gRPC服务
    grpcServer := grpc.NewServer()
    discoverygrpc.RegisterAggregatedDiscoveryServiceServer(grpcServer, srv)
    
    lis, _ := net.Listen("tcp", ":18000")
    log.Println("xDS Server listening on :18000")
    grpcServer.Serve(lis)
}

三、高级过滤器配置

3.1 JWT认证

http_filters:
- name: envoy.filters.http.jwt_authn
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
    providers:
      # JWT提供者1:Auth0
      auth0:
        issuer: "https://my-tenant.auth0.com/"
        audiences: ["my-api-client-id"]
        forward: true                    # 转发原始token
        forward_payload_header: x-jwt-payload  # 转发payload到后端
        remote_jwks:
          http_uri:
            uri: "https://my-tenant.auth0.com/.well-known/jwks.json"
            cluster: auth0_jwks
            timeout: 5s
          cache_duration: 300s           # JWKS缓存5分钟
      # JWT提供者2:内部OAuth
      internal:
        issuer: "https://auth.internal.com"
        audiences: ["internal-api"]
        local_jwks:
          inline_string: |
            {"keys": [...]}              # 内联JWKS
    rules:
    # /api/*需要认证
    - match:
        prefix: "/api"
      requires:
        requires_any:
          requirements:
          - provider_name: auth0
          - provider_name: internal
    # /public/*不需要认证
    - match:
        prefix: "/public"
      requires:
        allow_missing_or_failed: {}      # 允许缺失JWT
    # /admin/*需要admin角色
    - match:
        prefix: "/admin"
      requires:
        provider_name: auth0
        # 附加要求:claim检查
        requires_fields:
        - name: "role"
          value: "admin"

3.2 速率限制

http_filters:
- name: envoy.filters.http.ratelimit
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimit
    domain: "api_gateway"
    request_type: both                   # internal | external | both
    stage: 0
    enable_x_ratelimit_headers: DRAFT_VERSION_03  # 返回X-RateLimit-*头
    failure_mode_deny: false              # 限流服务故障时放行
    rate_limit_service:
      transport_api_version: V3
      grpc_service:
        envoy_grpc:
          cluster_name: ratelimit_service
        timeout: 0.25s
# 路由级限流配置
route_config:
  virtual_hosts:
  - name: api
    domains: ["api.example.com"]
    routes:
    - match:
        prefix: "/api/"
      route:
        cluster: backend
      # 路由级限流
      typed_per_filter_config:
        envoy.filters.http.ratelimit:
          "@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimitPerRoute
          rate_limits:
          - actions:
            # 按IP限流
            - remote_address: {}
            # 按API Key限流
            - request_headers:
                header_name: x-api-key
                descriptor_key: api_key
            # 按路径+方法限流
            - request_headers:
                header_name: :path
                descriptor_key: path
            - request_headers:
                header_name: :method
                descriptor_key: method
// 速率限制服务(gRPC实现)
package main

import (
    "context"
    "fmt"
    "sync"
    "time"
    rl "github.com/envoyproxy/go-control-plane/envoy/service/ratelimit/v3"
    "github.com/envoyproxy/go-control-plane/envoy/type/v3"
)

type RateLimiter struct {
    mu     sync.Mutex
    limits map[string]*tokenBucket
}

type tokenBucket struct {
    tokens   int
    maxTokens int
    lastRefill time.Time
    refillRate int // tokens per second
}

func (r *RateLimiter) ShouldRateLimit(ctx context.Context,
    req *rl.RateLimitRequest) (*rl.RateLimitResponse, error) {
    
    r.mu.Lock()
    defer r.mu.Unlock()
    
    // 构建描述符key
    key := ""
    for _, desc := range req.Descriptors {
        for _, entry := range desc.Entries {
            key += fmt.Sprintf("%s=%s,", entry.Key, entry.Value)
        }
    }
    
    bucket, exists := r.limits[key]
    if !exists {
        // 新描述符:创建桶(100 req/min)
        bucket = &tokenBucket{
            tokens:     100,
            maxTokens:  100,
            lastRefill: time.Now(),
            refillRate: 2, // 每秒补充2个(120/min)
        }
        r.limits[key] = bucket
    }
    
    // 补充令牌
    now := time.Now()
    elapsed := now.Sub(bucket.lastRefill).Seconds()
    bucket.tokens += int(elapsed) * bucket.refillRate
    if bucket.tokens > bucket.maxTokens {
        bucket.tokens = bucket.maxTokens
    }
    bucket.lastRefill = now
    
    // 消耗令牌
    requested := int(req.HitsAddend)
    if requested == 0 {
        requested = 1
    }
    
    if bucket.tokens >= requested {
        bucket.tokens -= requested
        return &rl.RateLimitResponse{
            OverallCode: rl.RateLimitResponse_OK,
            Status:     rl.RateLimitResponse_OK,
        }, nil
    }
    
    // 限流
    retryAfter := time.Duration(float64(requested-bucket.tokens) /
        float64(bucket.refillRate) * float64(time.Second))
    
    return &rl.RateLimitResponse{
        OverallCode: rl.RateLimitResponse_OVER_LIMIT,
        Status:     rl.RateLimitResponse_OVER_LIMIT,
        ResponseHeaders: []*core.HeaderValue{
            {Key: "x-ratelimit-limit", Value: fmt.Sprintf("%d", bucket.maxTokens)},
            {Key: "x-ratelimit-remaining", Value: fmt.Sprintf("%d", bucket.tokens)},
            {Key: "retry-after", Value: fmt.Sprintf("%d", int(retryAfter.Seconds())+1)},
        },
    }, nil
}

四、WASM扩展

// WASM过滤器:用Go/Rust编写自定义HTTP过滤器
// 无需重新编译Envoy,运行时加载

// proxy-wasm-go-sdk示例
package main

import (
    "github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm"
    "github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types"
    "github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/properties"
)

func main() {
    proxywasm.SetNewHttpContext(newHttpContext)
}

type httpContext struct {
    proxywasm.DefaultHttpContext
    requestBodySize int
    requestStart    int64
}

func newHttpContext(uint32) proxywasm.HttpContext {
    return &httpContext{}
}

// 请求头处理
func (ctx *httpContext) OnHttpRequestHeaders(numHeaders int, endOfStream bool) types.Action {
    // 检查API Key
    authHeader, err := proxywasm.GetHttpRequestHeader("authorization")
    if err != nil || authHeader == "" {
        proxywasm.LogCritical("Missing authorization header")
        proxywasm.SendHttpResponse(401, nil, []byte("Unauthorized"), 0)
        return types.ActionPause
    }
    
    // 添加自定义请求头
    proxywasm.AddHttpRequestHeader("x-wasm-filter", "true")
    proxywasm.AddHttpRequestHeader("x-request-source", "envoy-wasm")
    
    ctx.requestStart = proxywasm.GetCurrentTime()
    
    // 继续处理
    return types.ActionContinue
}

// 请求体处理
func (ctx *httpContext) OnHttpRequestBody(bodySize int, endOfStream bool) types.Action {
    ctx.requestBodySize += bodySize
    
    // 限制请求体大小(10MB)
    if ctx.requestBodySize > 10*1024*1024 {
        proxywasm.LogCritical("Request body too large")
        proxywasm.SendHttpResponse(413, nil, []byte("Payload Too Large"), 0)
        return types.ActionPause
    }
    
    return types.ActionContinue
}

// 响应头处理
func (ctx *httpContext) OnHttpResponseHeaders(numHeaders int, endOfStream bool) types.Action {
    // 添加安全头
    proxywasm.AddHttpResponseHeader("x-content-type-options", "nosniff")
    proxywasm.AddHttpResponseHeader("x-frame-options", "DENY")
    proxywasm.AddHttpResponseHeader("x-content-security-policy", "default-src 'self'")
    
    return types.ActionContinue
}

// 响应体处理
func (ctx *httpContext) OnHttpResponseBody(bodySize int, endOfStream bool) types.Action {
    if endOfStream {
        duration := proxywasm.GetCurrentTime() - ctx.requestStart
        proxywasm.LogInfof("Request completed in %dms, body size: %d",
            duration, ctx.requestBodySize)
        
        // 上报指标
        proxywasm.SetProperty(
            []string{"http_request_duration_ms"},
            []byte(fmt.Sprintf("%d", duration)),
        )
    }
    return types.ActionContinue
}
# Envoy WASM过滤器配置
http_filters:
- name: envoy.filters.http.wasm
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
    config:
      name: my_wasm_filter
      vm_config:
        runtime: envoy.wasm.runtime.v8
        code:
          local:
            filename: /etc/envoy/filter.wasm
      configuration:
        "@type": type.googleapis.com/envoy.extensions.filters.http.wasm.v3.PluginConfig
        fail_open: true                 # WASM失败时放行(非关键路径)

五、TLS配置

# 下游TLS(客户端→Envoy)
static_resources:
  listeners:
  - name: listener_https
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 8443
    filter_chains:
    # 多证书SNI
    - filter_chain_match:
        server_names: ["api.example.com"]
      transport_socket:
        name: envoy.transport_sockets.tls
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
          common_tls_context:
            tls_certificates:
            - certificate_chain:
                filename: /etc/envoy/tls/api.crt
              private_key:
                filename: /etc/envoy/tls/api.key
            alpn_protocols: ["h2", "http/1.1"]
          require_client_certificate: false
    - filter_chain_match:
        server_names: ["admin.example.com"]
      transport_socket:
        name: envoy.transport_sockets.tls
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
          common_tls_context:
            tls_certificates:
            - certificate_chain:
                filename: /etc/envoy/tls/admin.crt
              private_key:
                filename: /etc/envoy/tls/admin.key
          # mTLS:要求客户端证书
          require_client_certificate: true
          validation_context:
            trusted_ca:
              filename: /etc/envoy/tls/client-ca.crt
            # 证书吊销检查
            crl: 
              filename: /etc/envoy/tls/ca.crl

# 上游TLS(Envoy→后端)
clusters:
- name: backend_https
  transport_socket:
    name: envoy.transport_sockets.tls
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
      sni: backend.internal.com
      common_tls_context:
        tls_params:
          tls_minimum_protocol_version: TLSv1_2
          cipher_suites: [
            "ECDHE-ECDSA-AES256-GCM-SHA384",
            "ECDHE-RSA-AES256-GCM-SHA384"
          ]
        alpn_protocols: ["h2"]

六、可观测性

# 统计配置
stats_config:
  # 指标标签
  stats_tags:
  - tag_name: cluster_name
    regex: "^cluster\\.((.+?)\\.)"
  - tag_name: http_proxy
    regex: "^http\\.(.+?)\\."
  
  # 隐藏不需要的指标
  stats_matcher:
    exclusion_regex: 
      regex: ".*upstream_rq_.*retry.*"
  
  # 直方图分桶
  histogram_buckets:
  - name: "request_duration"
    buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
  
  # 高基数指标限制
  stats_event_tags:
  - tag_name: response_code_class
    regex: "^rsp_(\\d)\\d\\d_"

# 访问日志
access_log:
- name: envoy.access_loggers.file
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog
    path: /dev/stdout
    format: |
      [%START_TIME%] "%REQ(:METHOD)% %REQ(:PATH)%"
      %RESPONSE_CODE% %RESPONSE_FLAGS%
      %DURATION% %BYTES_RECEIVED% %BYTES_SENT%
      %UPSTREAM_HOST% %REQ(USER-AGENT)%
      %REQ(X-REQUEST-ID)%
---
# OpenTelemetry Tracing
tracing:
  provider:
    name: envoy.tracers.opentelemetry
    typed_config:
      "@type": type.googleapis.com/envoy.config.trace.v3.OpenTelemetryConfig
      grpc_service:
        envoy_grpc:
          cluster_name: otel_collector
        timeout: 5s
      service_name: envoy-proxy
  # 采样率
  random_sampling:
    value: 1                     # 100%采样(生产环境调低)

# 分布式追踪头传播
http_filters:
- name: envoy.filters.http.router
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
    start_child_span: true        # 为每个请求创建子Span

七、性能调优

# Envoy性能调优配置
static_resources:
  listeners:
  - name: main
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 8080
    # 连接重用
    socket_option_config:
    - description: "TCP_NODELAY"
      level: 1                     # IPPROTO_TCP
      name: 1                      # TCP_NODELAY
      int_value: 1
    - description: "SO_REUSEPORT"
      level: 1                     # SOL_SOCKET
      name: 15                      # SO_REUSEPORT
      int_value: 1
    
    # 连接数限制
    listener_filters_timeout: 5s
    per_connection_buffer_limit_bytes: 1048576  # 1MB
    
    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
          # 并发流数
          stream_idle_timeout: 5m
          # 请求超时
          request_timeout: 0       # 0=不超时
          request_headers_timeout: 10s
          # 空闲超时
          idle_timeout: 60s
          # 连接buffer
          max_request_headers_kb: 60
          # 背压
          max_concurrent_streams: 100

clusters:
- name: backend
  type: STRICT_DNS
  # 连接池
  upstream_connection_options:
    tcp_keepalive:
      keepalive_time: 60
    tcp_keepalive:
      keepalive_probes: 3
      keepalive_interval: 15
  # HTTP/2连接池
  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:
          max_concurrent_streams: 100
          initial_stream_window_size: 65536
          initial_connection_window_size: 1048576
  # 连接超时
  connect_timeout: 0.5s
  # 负载均衡
  lb_policy: LEAST_REQUEST
  # DNS刷新
  dns_refresh_rate: 30s
  dns_failure_refresh_rate:
    base_interval: 5s
    max_interval: 30s
  # 健康检查
  health_checks:
  - timeout: 1s
    interval: 5s
    unhealthy_threshold: 2
    healthy_threshold: 2
    http_health_check:
      path: /health
  # 熔断
  circuit_breakers:
    thresholds:
    - priority: DEFAULT
      max_connections: 1000
      max_pending_requests: 100
      max_requests: 2000
      max_retries: 50
  # 异常检测
  outlier_detection:
    consecutive_5xx: 5
    interval: 10s
    base_ejection_time: 30s
    max_ejection_percent: 50
    enforcing_consecutive_5xx: 100
    split_external_local_origin_errors: true

# 资源限制
overload_manager:
  refresh_interval: 0.25s
  resource_monitors:
  - name: envoy.resource_monitors.fixed_heap
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.resource_monitors.fixed_heap.v3.FixedHeapConfig
      max_heap_size_bytes: 2147483648    # 2GB限制
  actions:
  - name: env.overload_actions.stop_accepting_requests
    triggers:
    - name: envoy.resource_monitors.fixed_heap
      threshold: 0.95
  - name: env.overload_actions.stop_accepting_connections
    triggers:
    - name: envoy.resource_monitors.fixed_heap
      threshold: 0.98

八、总结

Envoy是云原生时代网络代理的事实标准。过滤器链架构是Envoy的核心设计——L4网络过滤器处理TCP连接,L7 HTTP过滤器处理应用层逻辑,路由器过滤器完成请求分发,每个过滤器各司其职又可组合。xDS动态配置协议让Envoy可以在不停机的情况下更新路由和集群配置,这是服务网格实现流量管理的基础。JWT认证、速率限制、WASM扩展等HTTP过滤器让Envoy可以作为功能完整的API网关使用。WASM扩展是Envoy生态的未来——用Go/Rust编写自定义过滤器,运行时加载,无需重新编译Envoy,实现了真正的可编程代理。性能调优的核心是连接池管理(HTTP/2多路复用)、熔断配置(防止级联故障)、overload_manager(内存压力保护)。生产部署Envoy的关键建议:使用ADS而非独立xDS确保配置一致性、合理设置指标基数避免Prometheus爆炸、TLS配置启用HTTP/2提升吞吐、访问日志结构化输出便于日志分析、overload_manager是防止Envoy OOM的安全网。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。