Search code examples
network-programmingdockerfirewallssh-tunnel

How can I expose a Docker container port only to localhost so that it is also accessible via an ssh tunnel?


Hopefully straightforward. I know how to bind to the host only with

-p 127.0.0.1:$HOSTPORT:$CONTAINERPORT

The issue I'm encountering is that doing this preventing me from accessing the mapped host port over an ssh tunnel to the docker host.

Is there way to do this without having to block the port upstream from the docker host somewhere?


Solution

  • Just make the target of your ssh tunnel localhost or 127.0.0.1.

    ssh -L local-port:127.0.0.1:container-port docker-host
    

    Would forward your local-port to localhost:container-port on docker-host. No need to expose the container port to the external network.