how to limit source IP in a outside service that requests come from a pod inside kubernetes

3/30/2019

let's say I have a mysql service, on this vm, I want limit source ip through iptables, but sources are come from kubernetes pod, is there a way to achieve this goal? let some pods can reach mysql, other pods can't.

btw, all my services' type in kubernetes cluster are clusterIP

I know I can do some network policy inside kubernetes cluster, but in DBAs view,

it's your business, I can't believe you, I'll do my rules through iptables.

  • kubernetes version: 1.13.4
  • kube proxy mode: ipvs
  • overlay network: calico
  • ingress-controller: nginx
-- Alex.Lee
kubernetes
kubernetes-networkpolicy

2 Answers

5/23/2019

Try to define two kind of Kubernetes services, add ExternalIP to them and later accordingly to your preferences block ExternalIP (which is assign to service which expose deployment or pod you do not want to accept connection from using iptables to access your database or properly accept this connection.

For example :

For pods you want to accept connection:

  1. Label this pods:

    $ kubectl label pod test app=MyApp --namespace development

  2. Define service for them wich appropriate selector corresponding label which you add to pod

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 9376
  externalIPs:
  - 80.11.12.10
  1. Create it:

    $ kubectl create -f service.yaml --namespace development

  2. You can also patch service with externaiIP instead of adding it in configuration file.

  3. Execute command from MySQL to allow connection between pods

    $ iptables -A INPUT -m state --state NEW,ESTABLISHED,RELATED --source x.x.x.x -p tcp --dport 80 -j ACCEPT

x.x.x.x is externalIP

Remeber to create service in appropraite namespace when your pods are deployed.

For pods you do not want to reject connection:

  1. Label this pods:

    $ kubectl label pod egg app=test --namespace development

  2. Define service for them wich appropriate selector corresponding label which you add to pod

apiVersion: v1
kind: Service
metadata:
  name: example1-service
spec:
  selector:
    app: test
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 9376
  externalIPs:
  - y.y.y.y
  1. Create it:

    $ kubectl create -f service.yaml --namespace development

  2. You can also patch service with externaiIP instead of adding it in configuration file.

  3. Execute command from MySQL to allow connection between pods

    $ iptables -A INPUT -m state --state NEW,ESTABLISHED,RELATED --source y.y.y.y -p tcp -- dport 80 -j DROP

y.y.y.y is externalIP

I hope this helps.

-- MaggieO
Source: StackOverflow

3/31/2019

Define network policy rules on mysql pod. With network policy you can control the traffic to mysql pod from a specific pod or namespace

-- P Ekambaram
Source: StackOverflow