【问题标题】:python connect to postgres docker instance outside dockerpython连接到docker外部的postgres docker实例
【发布时间】:2021-04-23 12:20:34
【问题描述】:

我可以确认 docker 容器正在运行:

Name                      Command                  State     Ports
-----------------------------------------------------------------------------------------------
adminer_1             entrypoint.sh docker-php-e ...   Up      0.0.0.0:8080->8080/tcp
db_1                  docker-entrypoint.sh postgres    Up      5432/tcp

我也可以通过管理员连接到数据库(下图):

但是我无法从外部 docker 使用 Python 连接:

# import the connect library from psycopg2
from psycopg2 import connect

table_name = "trips"

# declare connection instance
conn = connect(
    dbname = "postgres",
    user = "postgres",
    host = "localhost", #known ip 172.20.0.2
    password = "password"
)

# declare a cursor object from the connection
cursor = conn.cursor()

# execute an SQL statement using the psycopg2 cursor object
cursor.execute(f"SELECT * FROM {table_name};")

# enumerate() over the PostgreSQL records
for i, record in enumerate(cursor):
    print ("\n", type(record))
    print ( record )

# close the cursor object to avoid memory leaks
cursor.close()

# close the connection as well
conn.close()

出现错误:

psycopg2.OperationalError: 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" (fe80::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?

还尝试使用 postgres 检查 ip 是否正在侦听:

docker inspect db_1 | grep "IPAddress"
            "SecondaryIPAddresses": null,
            "IPAddress": "",
                    "IPAddress": "172.20.0.2",

并用172.20.0.2替换了我的python脚本中的host,但我仍然无法连接。

【问题讨论】:

    标签: python python-3.x postgresql docker


    【解决方案1】:

    您的 docker 容器“集合”只是将一个端口暴露(转发)给外部世界(也就是您的本地主机); 8080 是您的管理员网站。所以你可以做到这一点,并且与数据库在同一个内部网络上可以找到数据库,但由于端口未公开/转发,你无法访问数据库。

    您将希望以与 Web 端口相同的方式转发 DB 端口。请注意,在您的第一个屏幕截图中,您可以看到 adminer_1 正在将 8080 转发到外部,而 db_1 没有转发。

    如果您使用的是 docker-compose,您可能需要添加:

    ports:
      - "5432:5432"
    

    到您的 postgres 容器规范。

    【讨论】:

    • 正确!这解决了问题,非常感谢。
    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多