Traefik IngressRoute。如何将请求代理到外部 IP 地址?

Traefik IngressRoute。如何将请求代理到外部 IP 地址?

我在 Kubernetes 中使用 Traefik IngressRoute。

我的目标是在访问 https://kubernetes_host.com/my_api/... 时代理请求http://10.139.158.30:5000/api/v1/

我将在 Nginx 中执行以下操作:

location /my_api {
    proxy_pass http://10.139.158.30:5000/api/v1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme http;
    proxy_set_header X-Forwarded-Proto http;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
    }

但我不知道如何在 Traefik IngressRoute 中做到这一点。在文档中,仅代理内部 Kubernetes 服务的请求。示例:

---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: route-proxy
  namespace: xxx
spec:
  entryPoints:
  - xxx
  routes:
  - kind: Rule
    match: PathPrefix(`/my_api`)
    services:
    - kind: Service
      name: some-service
      port: 80

答案1

您可以尝试创建一个Endpoint-Service对来指向您的 IP:

apiVersion: v1
kind: Endpoints
metadata:
  name: api
subsets:
  - addresses:
      - ip: 10.139.158.30
    ports:
      - port: 5000
---
kind: Service
apiVersion: v1
metadata:
  # Service name has to match Endpoints so k8s can route traffic
  name: api
spec:
  ports:
    - port: 80
      # targetPort has to match the Endpoints ports above
      targetPort: 5000

或者使用较新的EndpointSliceAPI(来自 k8s v1.21):

kind: Service
apiVersion: v1
metadata:
  name: api
spec:
  ports:
    - port: 80
      # targetPort has to match the EndpointSlice port
      targetPort: 5000
---
apiVersion: discovery.k8s.io/v1
kind: EndpointSlice
metadata:
  name: api-endpoint # by convention, use the name of the Service
                     # as a prefix for the name of the EndpointSlice
  labels:
    # You should set the "kubernetes.io/service-name" label.
    # Set its value to match the name of the Service
    kubernetes.io/service-name: api
addressType: IPv4
ports:
  - appProtocol: http
    protocol: TCP
    port: 5000
endpoints:
  - addresses:
      - "10.139.158.30"

Service然后,在您的定义中引用IngressRoute

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: route-proxy
  namespace: xxx
spec:
  entryPoints:
  - xxx
  routes:
  - kind: Rule
    match: PathPrefix(`/my_api`)
    services:
    - kind: Service
      name: api
      port: 80

更多信息:https://kubernetes.io/docs/concepts/services-networking/service/#services-without-selectors

相关内容