docker从容器连接到主机隧道

时间:2016-11-24 09:26:12

标签: docker ssh-tunnel docker-networking docker-container

我想从我的docker容器内部与在主机中使用隧道的postgres数据库连接。在主机中,我有一个指向数据库主机的隧道:

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       

隧道设置为:

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

从主机我可以启动psql命令:

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=# 

当我使用网络模式 BRIDGE [我无法使用 HOST ,因为docker未正确地将容器端口暴露给主机,请参阅:https://github.com/docker/compose/issues/3442] I读到我必须使用容器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 

在这种情况下, 172.17.0.1

然而,当我进入容器时:

host$ docker exec -ti container_name  /bin/bash

我尝试连接我:

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?

我缺少什么?

1 个答案:

答案 0 :(得分:7)

你错过了bind_address,所以现在你的绑定地址是127.0.0.1。 设置隧道必须添加bind_address参数。

  

-L [bind_address:] port:host:hostport

E.g。

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