无法从虚拟机访问Docker容器中的postgresql

我有一个虚拟机通过bash供应设置与stream浪汉。

我尝试安装一系列应用程序和工具,在启动时将虚拟机虚拟化,其中一些需要PostgreSQL数据库。 我精简了configuration阶段,只包含必要的部分:

install.sh:

function installPostgresql() { docker pull postgres:9.4 docker run --name dbcontainer -e POSTGRES_PASSWORD=$POSTGRES_PASSWORD -e POSTGRES_DB=dbname -e POSTGTES_HOST=localhost -d postgres } ... installPostgresql 

这使用为postgresql创build的默认广泛使用的docker镜像。 从中央存储库中取出后开始。

出于某种原因,我无法访问虚拟机内运行的postgres服务,但是如果在运行的docker上执行/ bin / bash并在虚拟机内部的docker中使用psql,则可以连接它。

虚拟机内部:

 vagrant@debian-jessie:~$ psql -h localhost -p 5432 -U postgres -W Password for user postgres: psql: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? 

VM内部的docker里面:

 root@1d0b5be83f6e:/# psql -h localhost -p 5432 -U postgres -W Password for user postgres: psql (9.5.2) Type "help" for help. postgres=# 

pg_hba.conf的:

 local all all trust host all all 127.0.0.1/32 trust host all all ::1/128 trust host all all 0.0.0.0/0 md5 

为什么它在虚拟机内部的docker里面工作,而不是在虚拟机上“only”呢?

听起来好像这是一个端口曝光问题。 默认情况下,Docker容器不会将任何端口发布到主机(在本例中是您的VM)。 但是,如果链接容器,则这些容器可以与暴露的端口交互(例如,在相关的Dockerfile描述)。

尝试添加-p选项到您的docker run命令,将PostgreSQL端口发布到您的主机上:

docker run --name dbcontainer -e POSTGRES_PASSWORD=$POSTGRES_PASSWORD -e POSTGRES_DB=dbname -e POSTGTES_HOST=localhost -d -p 5432:5432 postgres

你会在文档中find更多关于这个的信息 。