docker容器连接本地postgresql

我运行python容器,我想连接本地主机postegresql。 我尝试一些方法。 但不行。 请跟我说说 我能怎么做 ? 谢谢。

我已经在端口5432上运行postegresql,创build数据库并授予用户。

运行docker指令

docker run --name=python3 -v ${pwd}:/code -w /code python 

python代码

 import psycopg2 def main(): #Define our connection string conn_string = "host='localhost' dbname='testDB' user='test' password='test'" # print the connection string we will use to connect print ("Connecting to database\n ->{}".format(conn_string)) # get a connection, if a connect cannot be made an exception will be raised here conn = psycopg2.connect(conn_string) # conn.cursor will return a cursor object, you can use this cursor to perform queries cursor = conn.cursor() print ("Connected!\n") if __name__ == "__main__": main() 

错误信息

服务器是否在主机“localhost”(:: 1)上运行,并接受端口5432上的TCP / IP连接? 无法连接到服务器:连接被拒绝服务器是否运行在主机“localhost”(127.0.0.1)上并接受端口5432上的TCP / IP连接?

这取决于你的主机操作系统和你的docker版本。
我在这里假设你的数据库不是在一个容器中运行,而是在主机本身(localhost)上运行。

例如,如Docker for Mac v 17.06及更高版本(2017年6月)中的“ 从Docker容器的内部,我如何连接到本机的本地主机? ”中所述,您可以连接到特殊的仅限Mac的DNS名称docker.for.mac.localhost ,它将parsing为主机使用的内部IP地址。

直接在Linux上,您将使用主机模式,安装有ifconfig的映像:

 docker run --network="host" -id <Docker image ID> 

读取你在Windows 10上运行postgresql的主机,我build议你在容器中运行postgresql。 这使得这种方式更容易。

为了将python容器连接到postgres容器,你需要一个dockernetworking。 我们称之为postgres_backend。

docker network create postgres_backend

您可以使用以下命令创buildpostgresql容器。 只需将/ path / to / store / data更改为您要存储postgres数据的本地目录即可:

 docker run --name postgres \ -e POSTGRES_PASSWORD=test \ -e POSTGRES_USER=test \ -d --restart always \ -v /path/to/store/data:/var/lib/postgresql/data \ --net postgres_backend \ postgres:9.6 

现在你的postresql容器应该正常运行:)

要连接你的Python容器,你必须添加一个--net postgres_backend到你的--net postgres_backend run命令中,并把你的脚本中的主机改为“postgres”(这是我们给postgres容器命名的名字)。

如果python容器找不到主机“postgres”,那么在input命令docker exec -ti postgres ip addr show