在我的情况下如何连接到Docker中的数据库?

时间:2017-03-23 04:32:15

标签: node.js postgresql docker docker-compose

我正试图通过docker容器连接到我的postgres。我读过了 很多帖子但似乎无法解决它。

我运行了以下命令。

docker run --name some-postgres -e POSTGRES_PASSWORD=mypw -d -p 5432:5432 postgres

之后,我做docker inspect $(containerID)

"NetworkSettings": {
            "Bridge": "",
            "SandboxID": "773de825919cb75482af47b85b1804f96a32bc6e9951cc0ea80752f880789717",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "5432/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "5432"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/773de825919c",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "29c872cb1487519a8f605f7ba371e5ce84c2b163140babbb981ace8a12a273cd",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "9d69c3e1dfa70572306fbe6dd14ed91d7ee96796deb27057b1c2992f573875f9",
                    "EndpointID": "29c872cb1487519a8f605f7ba371e5ce84c2b163140babbb981ace8a12a273cd",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02"
                }
            }
        }

我的理解是我可以使用"IPAddress": "172.17.0.2"连接到数据库

所以我做了

psql -h 172.17.0.2 -p 5432 -U postgres

但是,我收到操作超时错误,无法登录postgres。

错误

psql: could not connect to server: Operation timed out
    Is the server running on host "172.17.0.2" and accepting
    TCP/IP connections on port 5432?

任何人都可以帮我吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

你没有提到你如何运行docker。如果您在Workstation上使用它,如Docker for OSx,则必须使用“localhost”进行连接:

psql -h localhost -p 5432 -U postgres

如果您在Docker VM或远程主机上运行容器,则需要本地网络中的外部接口IP。

psql -h 192.168.99.100 -p 5432 -U postgres

此外,如果PostgreSQL配置为允许远程连接,则必须验证“pg_hba.conf”并添加

host    all             all             0.0.0.0/0               md5

并将listen_addresses更改为listen_addresses='*':/etc/postgresql/9.1/main/postgresql.conf

请注意:此设置仅用于测试,并在数据库配置中打开一个漏洞。