简体   繁体   English

如何拦截对 Kubernetes 中服务的请求?

[英]How to intercept requests to a service in Kubernetes?

Let's say I define a Service named my-backend in Kubernetes.比方说,我定义了一个Servicemy-backend的Kubernetes。 I would like to intercept every request sent to this service, what is the proper way to do it?我想拦截发送到此服务的每个请求,正确的方法是什么? For example, another container under the same namespace sends a request through http://my-backend .例如,同一命名空间下的另一个容器通过http://my-backend发送请求。

I tried to use Admission Controller with a validation Webhook.我尝试将准入控制器与验证 Webhook 一起使用。 However, it can intercept the CRUD operations on service resources, but it fails to intercept any connection to a specific service.但是,它可以拦截对服务资源的 CRUD 操作,但无法拦截与特定服务的任何连接。

There is no direct way to intercept the requests to a service in Kubernetes.在 Kubernetes 中没有直接的方法来拦截对服务的请求。

For workaround this is what you can do-对于解决方法,这是您可以执行的操作-

  1. Create a sidecar container just to log the each incoming request.创建一个 sidecar 容器只是为了记录每个传入的请求。 logging 日志记录

  2. Run tcpdump -i eth0 -n in your containers and filter out requests在容器中运行tcpdump -i eth0 -n并过滤掉请求

  3. Use Zipkin使用Zipkin

  4. Creating service on cloud providers, will have their own logging mechanism.在云提供商上创建服务,将有自己的日志记录机制。 for ex - load balancer service on aws will have its logs generated on S3.对于前 - aws 上的负载均衡器服务将在 S3 上生成其日志。 aws elb logs aws elb 日志

You can use a service mesh such as istio .您可以使用服务网格,例如istio An istio service mesh deploys a envoy proxy sidecar along with every pod. istio 服务网格与每个 pod 一起部署了一个特使代理边车。 Envoy intercepts all the incoming requests to the pod and can provide you metrics such as number of requests etc. A service mesh brings in more features such as distributed tracing, rate limiting etc. Envoy 拦截所有传入 pod 的请求,并可以为您提供诸如请求数量等指标。服务网格带来了更多功能,例如分布式跟踪、速率限制等。

Kubernetes NetworkPolicy object will help on this. Kubernetes NetworkPolicy 对象将对此有所帮助。 A network policy controls how group of pods can communicate with each other and other network endpoints.网络策略控制 Pod 组如何相互通信以及如何与其他网络端点通信。 You can only allow the ingress traffic to the my-backend service based on pod selector.您只能根据 pod 选择器允许进入 my-backend 服务的流量。 Below is the example that will allow the ingress traffic from specific下面是允许来自特定的入口流量的示例

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
   name: ingress-only-from-frontend-to-my-backend
   namespace: default    
spec:
   podSelector:
      matchLabels:
          <my-backend pod label>
   policyTypes:
   - Ingress
   ingress:
    - from:  
      - podSelector:
          matchLabels:
            <Frontend web pod label>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM