我最近一直在使用Docker和QGIS,并按照本教程中的说明安装了一个容器。

一切都很好,尽管我无法连接到包含我所有GIS数据的本地主机postgres数据库。我想这是因为我的postgres数据库没有配置为接受远程连接,并且一直在编辑postgres conf文件以允许使用本文中的说明进行远程连接。

I'm still getting an error message when I try and connect to my database running QGIS in Docker: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections to port 5433? The postgres server is running, and I've edited my pg_hba.conf file to allow connections from a range of IP addresses (172.17.0.0/32). I had previously queried the IP address of the docker container using docker ps and although the IP address changes, it has so far always been in the range 172.17.0.x

知道为什么我无法连接到这个数据库吗?我想可能是非常简单的事情!

我运行的是Ubuntu 14.04;Postgres 9.3


当前回答

简单的解决方案

docker的最新版本(18.03)提供了一个内置的端口转发解决方案。在docker容器中,只需将db主机设置为host.docker.internal。这将被转发到运行docker容器的主机。

相关文档在这里:https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

其他回答

我的设置还需要添加一个东西

172.17.0.1  localhost

到 /etc/hosts

这样Docker就会指向172.17.0.1作为数据库主机名,而不是依赖于改变外部ip来找到DB。希望这能帮助其他人解决这个问题!

为了建立一个简单的Postgresql连接,从docker容器到我的本地主机,我在Postgresql .conf中使用了这个:

listen_addresses = '*'

并添加了这个pg_hba.conf:

host    all             all             172.17.0.0/16           password

然后重新启动。我的客户端从docker容器(在172.17.0.2)可以连接到Postgresql运行在我的本地主机使用host:密码,数据库,用户名和密码。

另一种解决方案是服务卷,您可以定义一个服务卷,并将主机的PostgreSQL Data目录挂载在该卷中。查看给定的合成文件以获得详细信息。

version: '2'
services:
  db:   
    image: postgres:9.6.1
    volumes:
      - "/var/lib/postgresql/data:/var/lib/postgresql/data" 
    ports:
      - "5432:5432"

通过这样做,另一个PostgreSQL服务将运行在容器下,但使用与主机PostgreSQL服务使用的相同的数据目录。

简单的解决方案

只需在docker run中添加——network=host。这是所有!

这样容器将使用主机的网络,因此localhost和127.0.0.1将指向主机(默认情况下它们指向容器)。例子:

docker run -d --network=host \
  -e "DB_DBNAME=your_db" \
  -e "DB_PORT=5432" \
  -e "DB_USER=your_db_user" \
  -e "DB_PASS=your_db_password" \
  -e "DB_HOST=127.0.0.1" \
  --name foobar foo/bar

对于docker-compose,您可以尝试只添加

network_mode: "host"

例子:

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

https://docs.docker.com/compose/compose-file/#network_mode