首页 > 解决方案 > 从 Windows Docker 主机连接到 dockerized postgres

问题描述

我的设置是安装了 postgres(不是数据库,只有命令行工具)的 Windows 10 Pro 机器上的 Docker for Windows(版本 18.09.2)。

我从 docker hub 运行官方 postgres 图像

docker run -it -v D:/postgres:/home/dump --name some_postgres -e POSTGRES_PASSWORD=root -d postgres

之后我可以通过

docker exec -it <docker-id> bash

并运行

psql -U postgres

一切正常。现在我想从我的主机连接。我打电话

psql -h <local-ip> -U postgres

并得到

psql: could not connect to server: Connection refused (0x0000274D/10061)
        Is the server running on host "192.168.116.74" and accepting
        TCP/IP connections on port 5432?

我很确定,可以访问数据库。因为如果我改变我收到的 IP

psql: could not connect to server: Connection timed out (0x0000274C/10060)
        Is the server running on host "192.168.116.11" and accepting
        TCP/IP connections on port 5432?

有谁知道如何解决这个问题?或者我做错了什么?

标签: windowspostgresqldocker

解决方案


要从您的主机连接到容器,您必须将端口发布到您的主机。这是使用端口发布和-p选项完成的:

docker run -it -v D:/postgres:/home/dump --name some_postgres -p 5432:5432 -e POSTGRES_PASSWORD=root -d postgres

注意-p选项。现在,当您尝试连接到5432本地主机上的端口时,流量将被重定向到5432容器的端口。


推荐阅读