docker 无法插入记录,服务器是否正在该主机上运行并接受TCP/IP连接?

ergxz8rk  于 2022-12-18  发布在  Docker
关注(0)|答案(1)|浏览(144)

我已经在Docker中配置了一个Postgresql映像,我用PGAdmin 4打开了它,到服务器的连接工作正常。我还创建了一个名为test的数据库来做一些测试。我有下面的脚本来尝试在表中插入一个简单的行:-

def insert_teams():
    try:
        connection = psycopg2.connect(user="postgres",
                                    password="123456",
                                    host="172.18.0.3",
                                    port="5432",
                                    database="testdb")
        cursor = connection.cursor()

        postgres_insert_query = """ INSERT INTO Teams (ID, TEAM, POINTS) VALUES (%s,%s,%s)"""
        record_to_insert = (5, 'Brazil', 950)
        cursor.execute(postgres_insert_query, record_to_insert)

        connection.commit()
        count = cursor.rowcount
        print(count, "Record inserted successfully into teams table")

    except (Exception, psycopg2.Error) as error:
        print("Failed to insert record into teams table", error)

    finally:
        # closing database connection.
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

然而,我得到一个错误:-

Failed to insert record into teams table connection to server at "172.18.0.3", port 5432 failed: Connection timed out (0x0000274C/10060)
        Is the server running on that host and accepting TCP/IP connections?

我做了一些研究,我认为这很可能是由于postgresql.conf文件没有侦听:-

listen_addresses = '*'

然而,我不知道在哪里可以找到这个文件,因为我有一个码头形象。
如果这是问题所在,我如何访问此文件?
谢谢你的帮助和时间

qyswt5oh

qyswt5oh1#

我终于解决了这个问题!我不得不改变我与localhost的连接:-

connection = psycopg2.connect(user="postgres",
                                    password="123456",
                                    **host="127.0.0.1"**,
                                    port="5432",
                                    database="testdb")

不知道为什么,虽然因为我认为我是连接到数据库内的图像容器。

相关问题