Forward a remote Docker container's port onto localhost

Viewed 4870

I have containers running in docker-compose networks on a remote VPS. I would like to be able to access a database running in one of these containers from my localhost.

Eg, if the containers app and db are in a container network on the VPS, I want to access db:5432 from my machine's localhost:5432. Kubernetes' CLI allows this with kubectl port-forward <service-name> 5432:5432.

Are there any existing solutions to achieve this effect within existing unix commands and Docker's API? My searching around the Internet hasn't yielded any CLI to do this.

Cheers.


Edit: I have accepted Ali Tou's answer, however, it would be great to see a solution which does not require restarting a container to re-configure its ports to expose them onto the host.

Edit 2: I found a clever method for forwarding traffic in the Docker network using socat in a tangentially-related post https://stackoverflow.com/a/42071577/12406113. This is, however, publicly exposing the port instead of creating a tunnel, such as in the SSH solution.

2 Answers

Assuming you have SSH access to the target machine where the container is running, you can achieve this in two steps:

  1. Expose container port into your VPS port, binding to its loopback IP for security:
ports:
  - 127.0.0.1:5432:5432
  1. Use SSH port-forwarding to access port 5432 of that container:
ssh -f -N -L 127.0.0.1:5432:127.0.0.1:5432 <VPS_IP>

The above command might seem confusing, but it's requesting SSH to listen on 127.0.0.1:5432 on your client system (first ip:port pair) and port forward its connections through an ssh tunnel to 127.0.0.1:5432 (second ip:port pair) of the remote system (demonstrated with <VPS_IP>). See this answer for more info.

Note that this ssh connection is persistent until your network remains connected. If you want to close this connection, do a ps aux | grep ssh to find PID of ssh-forwarding process, then use sudo kill -9 $PID to kill it.

P.S. However, this is not different with the case you connect directly to VPS_IP:5432 if you don't have security concerns.

Related