我运行了Python容器,想要连接本地的PostgreSQL。我尝试了一些方法,但都没有成功。请告诉我该怎么做?谢谢。
我已经在5432端口上运行了PostgreSQL,并创建了数据库和授权用户。
运行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 run --name=python3 -v ${pwd}:/code -w /code --network="host" python
,但不起作用。我的操作系统是Windows 10。数据库在本地机器上运行,而不是容器中。谢谢。我还需要做什么吗? - frank