docker connecting to host tunnel from container

dawez picture dawez · Nov 24, 2016 · Viewed 7.8k times · Source

I would like to connect from inside my docker container with a postgres db that is using a tunnel in the host. In the host I have a tunnel pointing to the DB host:

host$ sudo netstat -tulpen  | grep 555
tcp        0      0 127.0.0.1:5555          0.0.0.0:*               LISTEN      1000       535901      18361/ssh       
tcp6       0      0 ::1:5555                :::*                    LISTEN      1000       535900      18361/ssh       

the tunnel is setup with :

host$ ps -aux | grep 18361
ubuntu    9619  0.0  0.0  10432   628 pts/0    S+   10:11   0:00 grep --color=auto 18361
ubuntu   18361  0.0  0.0  46652  1420 ?        Ss   Nov16   0:00 ssh -i /home/ubuntu/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -f -N -L 5555:localhost:5432 user@remotehost

and from the host I can launch psql commands:

host$ psql -h localhost -p 5555 --username user db_name
psql (9.3.15, server 9.5.4)
SSL connection (cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256)
Type "help" for help.
db_name=# 

As I am using the network mode BRIDGE [I cannot use HOST as docker is not correctly exposing the containers ports to host see: https://github.com/docker/compose/issues/3442 ] I read that I have to use the container ip:

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:6c:01:5c:a5 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:6cff:fe01:5ca5/64 scope link 

Which in this case would be 172.17.0.1

However when I go inside the container:

host$ docker exec -ti container_name  /bin/bash

I try to connect I have:

container# psql -h 172.17.0.1 -p 5555                                                                                                                                                                                              
psql: could not connect to server: Connection refused
    Is the server running on host "172.17.0.1" and accepting
    TCP/IP connections on port 5555?

Anything that I am missing ?

Answer

gile picture gile · Nov 24, 2016

You missed bind_address, so now your binding address is 127.0.0.1. Setting your tunnel you have to add bind_address parameter.

-L [bind_address:]port:host:hostport

E.g.

sudo ssh -f -N -L 172.17.0.1:5555:localhost:5432 user@remotehost