kubernetes redirecting outgoing http traffic from the service to localhost:port

5/23/2018

I have a chart in it two containers:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: catalog
  labels:
    app: catalog
    chart: catalog-0.1.0
    heritage: Tiller
spec:
  replicas: 1
  selector:
    matchLabels:
      app: catalog
  template:
    metadata:
      labels:
        app: catalog
    spec:
      containers:
        - name: catalog
          image: catalog:v1
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
        - name: myproxy
          image: myproxy:v1
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 8008
              protocol: TCP
          env:
            - name: PROXY_PORT
              value: '8080'
---
apiVersion: v1
kind: Service
metadata:
  name: catalog
  labels:
    app: catalog
    chart: catalog-0.1.0
    heritage: Tiller
spec:
  type: NodePort
  ports:
    - port: 8008
      targetPort: http
      protocol: TCP
      name: http
  selector:
    app: catalog

I need to redirect all outbound traffic from the catalog container to myproxy container by localhost.

And already in the container to determine whether the catalog can send requests, log them, etc.

Prompt please whether it is possible to implement it using kubernetes.

Thanks.


Update:

The problem is that I can not change the code in the catalg container and send queries to localhost

The container also does not have iptables to do something like this

containers:
    - name: catalog
      image: catalog:v1
      imagePullPolicy: IfNotPresent
      command:
        - 'iptables -t nat -A OUTPUT -p tcp --dport 8080 -j DNAT --to-destination 127.0.0.1:8008'
      ports:
        - name: http
          containerPort: 8080
          protocol: TCP

Ideally done with kubernetes

-- Igor Ognichenko
devops
docker
google-kubernetes-engine
kubernetes

2 Answers

5/23/2018

If catalog application respects http_proxy environment variable, it it easy. Just add an environment variable to catalog container.

    - name: catalog
      image: catalog:v1
      imagePullPolicy: IfNotPresent
      ports:
        - name: http
          containerPort: 8080
          protocol: TCP
      env:
      - name: HTTP_PROXY
        value: localhost:8008
-- ccshih
Source: StackOverflow

5/23/2018

For your update, if you need to manipulate iptables, you can add another initContainer, for example:

  initContainers:
  - image: centos
    imagePullPolicy: Always
    name: run-iptables
    securityContext:
      privileged: true
    command:
    - "sh"
    - "-c"
    - 'yum -y install iptables; iptables -t nat -A OUTPUT -p tcp --dport 8080 -j DNAT --to-destination 127.0.0.1:8008'

Since all containers in a pod share the same net namespace, it effects to catalog container as well.

-- ccshih
Source: StackOverflow