【发布时间】:2018-01-02 15:16:30
【问题描述】:
我运行 python 容器,我想连接本地主机 postegresql。我尝试了一些方法。但不行。请跟我谈谈。我能怎么做 ?谢谢。
我已经在 5432 端口运行 postegresql,创建数据库并授予用户。
运行 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 连接?
【问题讨论】:
标签: python postgresql docker