Exposing a localhost only port using socat on Kubernetes

2 min read

On Kubernetes, if we want to publish a port that it's listening just to localhost without having to modify the container image we can create another container image to work as a TCP proxy using socat

All the containers of the same pod are going to share the same network namespace, meaning that containers will not be allowed to bind on the same port, not even if they try to bind to localhost.

To expose a service listening to localhost, we can take advantage of this by adding a container on the Pod that redirects all the incoming TCP connections to a localhost port that sits on another container. One of the options for this is using socat for which is alpine has a container ready to use:

        - name: http-socat
          image: alpine/socat:latest
          args: 
            - "TCP-LISTEN:80,fork"
            - "TCP:127.0.0.1:8080"
          ports:
            - containerPort: 80
              name: http
              protocol: TCP

To use alpine/socat we won't need to actually call socat since it is defined as the entrypoint for the container, we can just add the arguments we would use on the cli using the key args


Posted on 15/07/2021

Categories