If your cluster supports network policy enforcement, you can utilize NetworkPolicy  resources, to block incoming and/or outgoing requests between pods & services, based on a particular set of characteristics. (Network policies are supported by providers such as AWS and GKE, but you may have to enable the feature in the provider console, or manually set up a network plugin such as Calico, before the rules will take effect. )

This example assumes that our cluster is running in GKE, has an existing deployment named postgres , and uses a NodePort service for load balancing. By default, pods are non-isolated, meaning that they will accept any traffic from any source that can connect to it. To improve security, we can use a NetworkPolicy to reject requests from other pods, based upon characteristics such as CIDR range, or pod labels. In this example, we will configure a NetworkPolicy to reject requests to the postgres pod, if the pod initiating the request, does not have the label: role: db_client .


Here is the configuration of the existing NodePort service:


apiVersion: v1
kind: Service
metadata:
  creationTimestamp: 2018-01-24T15:15:23Z
  name: postgres
  namespace: default
  resourceVersion: "2012"
  selfLink: /api/v1/namespaces/default/services/postgres
  uid: 65e3b7b1-0119-11e8-87f7-42010a8000e4
spec:
  clusterIP: 10.47.244.8
  externalTrafficPolicy: Cluster
  ports:
  - name: tcp
    nodePort: 31217
    port: 6543
    protocol: TCP
    targetPort: 5432
  selector:
    app: postgres
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

Any pod in the cluster should be able to connect to the postgres  pod, by using the clusterIP  and port  above: 10.47.244.8:6543 . Now, lets define the NetworkPolicy :

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: postgres-network-policy
spec:
  podSelector:
    matchLabels:
      app: postgres
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: db_client
    ports:
    - protocol: TCP
      port: 5432
  egress:
  - {}

The policy above applies to all pods with the label app: postgres . It will only accept incoming traffic from other pods with the label role: db_client , but will allow all outgoing traffic, to any destination.

To apply this NetworkPolicy on Containershp Cloud, click the Create  button, and select Firewall Rule :

Next, select the cluster where you would like to apply this rule:

Enter the NetworkPolicy YAML above into the following screen, or drag & drop a custom YAML file:

After the NetworkPolicy  is applied, you should be able to view it on the Firewalls  tab:

Now, only pods in the cluster, having the tag role: db_client will be able to connect to the postgres  pod. 

Did this answer your question?