postgresql - 无法从VM访问Docker容器中的postgresql

标签 postgresql docker vagrant virtual-machine

我有一个通过bash设置使用vagrant设置的VM。

我尝试在启动时安装一堆应用程序和工具以插入VM,其中一些需要PostgreSQL数据库。我简化了配置阶段,仅包括必要的部分:

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创建的广泛使用的默认docker镜像。我从中央存储库中将其启动后启动它。

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

内部VM:
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

为什么它在VM内的docker内部工作,而不是仅在VM内工作?

最佳答案

听起来好像是端口暴露问题。默认情况下,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
您将找到有关此in the documentation的更多信息。

关于postgresql - 无法从VM访问Docker容器中的postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36943331/

相关文章:

ruby-on-rails - Rails 的 ActiveRecord::Migration 的外键?

amazon-web-services - 多容器Docker(AW​​S)链接是单向的吗?

port - Vagrant,VirtualBox - 找不到适配器?

wordpress - vagrant VCCW环境下无法上传图片到wordpress

database - 将最新的各种用户元数据标签添加到用户行

python - 从 XSD 生成 Python 类和 SQLAlchemy 代码以将 XML 存储在 Postgres 上

postgresql - Postgres : Ignore DELETE triggers for cascade deletes

mysql - MediaWiki Docker官方图像-MySQL拒绝连接

docker - 通过示例一起使用 Vagrant 和 Docker

vagrant - 在哪里可以找到config.vm.boot_timeout?