forward a localhost port to a remote docker container

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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top