Kubernetes pod as a Bastion Host - Access private database

In Cloud Native environment private networks, databases and services are best practice. An infrastructure should be fully private and only a limited number of entry points can be available.

Important: Obviously the more restricted the better.

Still there are cases where you have to access infrastructure components from your private network of your Kubernetes cluster. Therefore HAProxy can help.

Solution:
HAProxy can accept a configuration file. Uploading that file as a configmap and then mount the configmap to a Kubernetes pod will be easy. Then the HAProxy Kubernetes pod can be used via port forwarding to access your database,...

Access MySQL Database with a private IP (This setup can also be used for other databases and services e.g. redis, mongoDB,...):

1) Start with the ha-proxy configuration - config.yaml

apiVersion: v1
 data:
   haproxy.cfg: |
     global
     defaults
         timeout client          30s
         timeout server          30s
         timeout connect         30s
     frontend frontend
         bind    0.0.0.0:PORT
         default_backend backend
     backend backend
         mode tcp
         server upstream HOSTNAME_OR_IP:PORT
 kind: ConfigMap
 metadata:
   name: mysql-db-forward

2) Apply ConfigMap:

kubectl apply -f config.yaml

3) Let`s create our HAProxy pod - proxy.yaml:

apiVersion: v1
 kind: Pod
 metadata:
   labels:
     run: mysql-db-forward-pod
   name: mysql-db-forward-pod
 spec:
   containers:
     - command:
       - haproxy
       - -f
       - /usr/local/etc/haproxy/haproxy.cfg
       image: haproxy:2.6.5-alpine
       name: mysql-db-forward-pod
       resources: {}
       volumeMounts:
         - mountPath: /usr/local/etc/haproxy/
           name: mysql-db-forward
   dnsPolicy: ClusterFirst
   restartPolicy: Always
   volumes:
     - name: mysql-db-forward
       configMap:
         name: mysql-db-forward

On the volume section we set the configmap from step 1 as a volume. On the container section we mount the configmap to a path thus having access to the file.

4) Apply Proxy pod:

kubectl apply -f proxy.yaml

5) Connect to HAProxy pod:

kubectl port-forward mysql-db-forward-pod PORT:PORT

6) Connect with your database client: