【问题标题】:Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host发生异常:OperationalError 无法将主机名“db”转换为地址:未知主机
【发布时间】:2021-03-27 13:28:53
【问题描述】:

我在本地运行这个脚本。在 postgres 连接上,我面临“发生异常:OperationalError 无法将主机名“db”转换为地址:未知主机”。数据库已启动,我使用它启动了

docker run --publish 8000:8000 --detach --name db REMOTEURL:latest

当我使用 docker-compose 执行相同操作并执行 django 应用程序并将其作为管理命令运行时,它可以工作。代码:

conn_string = "host='db' dbname='taras' user='postgres' password='postgres'"
with psycopg2.connect(conn_string) as connection:
    with connection.cursor() as cursor:
    ... my stuff

我不知道为什么从我的计算机上的本地脚本访问 docker 容器时,永远无法识别 docker 名称(url)。也尝试了“localhost”而不是“db”。在 docker 容器中运行 python 脚本时,识别其他 docker 容器(在我的情况下为 db)没有问题。我错过了什么?

编辑:澄清一下,我只在 docker 中运行数据库。 Python 脚本在本地启动,在我的 Windows 命令行中使用

python myscript.py

Docker 编写文件:

version: "2"
services:
  db:
    image: REMOTEURL:latest
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_HOST_AUTH_METHOD: trust

【问题讨论】:

    标签: python django postgresql docker docker-compose


    【解决方案1】:

    这可能是因为当您启动容器时,它们可以根据您在内部提供的名称解析主机名,但如果您想从外部访问容器(我假设您想访问您的 postgres 数据库),您还需要通过将-p 5432:5432 添加到您的 postgres 容器来打开 postgres 容器的端口。如果您想从同一网络上的另一个容器访问 postgres,请使用 db:5432 连接,从外部使用 localhost:5432 连接

    编辑: 试试这个作为你的docker-compose.yml

    version: "2"
    services:
      db:
        image: REMOTEURL:latest
        environment:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_HOST_AUTH_METHOD: trust
        ports:
          - 5432:5432
    

    【讨论】:

    • 感谢您的回答。我发布的代码中已经有 --publish 8000:8000(相当于 -p)。试过 5432:5432,没区别 :(
    • 也许我刚才误解了你的问题,你能再描述一下吗?
    • 我可以看看你的 docker compose 文件吗?
    • 尝试将 docker-compose.yml 从答案中进行编辑
    • 另外请问REMOTEURL:latest是什么图片?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2020-10-03
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多