[英]Exception has occurred: OperationalError could not translate host name “db” to address: Unknown host
I am running locally this script.我在本地运行这个脚本。 On postgres connection, I am facing "Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host".
在 postgres 连接上,我面临“发生异常:OperationalError 无法将主机名“db”转换为地址:未知主机”。 Database is up, I started it with
数据库已启动,我开始使用它
docker run --publish 8000:8000 --detach --name db REMOTEURL:latest
When I do the same using docker-compose, and exec to django app and run it as management command, it works.当我使用 docker-compose 执行相同操作并执行 django 应用程序并将其作为管理命令运行时,它可以工作。 The code:
编码:
conn_string = "host='db' dbname='taras' user='postgres' password='postgres'"
with psycopg2.connect(conn_string) as connection:
with connection.cursor() as cursor:
... my stuff
I dont know why when accessing docker container from local script on my computer, docker name (url) is never recognized.我不知道为什么从我计算机上的本地脚本访问 docker 容器时,docker 名称(url)永远无法识别。 Tried "localhost" instead of "db" also.
也尝试了“localhost”而不是“db”。 When running python script inside docker container, it has no problem to recognize other docker container (db in my case).
在 docker 容器内运行 python 脚本时,识别其他 docker 容器(在我的情况下为 db)没有问题。 What am I missing?
我错过了什么?
EDIT: Just to clarify, I am running only database in docker.编辑:澄清一下,我只在 docker 中运行数据库。 Python script is started locally, using in my windows command line
Python 脚本在本地启动,在我的 windows 命令行中使用
python myscript.py
Docker-compose file: Docker-compose 文件:
version: "2"
services:
db:
image: REMOTEURL:latest
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_HOST_AUTH_METHOD: trust
This probably happens because when you launch containers, they can resolve hostnames based the names you give them internally, but if you wanna access a container from the outside (I'm assuming you wanna access your postgres db), you also need to open the port for the postgres container by adding -p 5432:5432
to your postgres container.这可能是因为当您启动容器时,它们可以根据您在内部提供的名称解析主机名,但是如果您想从外部访问容器(我假设您想访问您的 postgres 数据库),您还需要打开通过将
-p 5432:5432
添加到您的 postgres 容器来为 postgres 容器提供端口。 If you want to access postgres from another container on the same network, connect with db:5432
, and from the outside with localhost:5432
如果您想从同一网络上的另一个容器访问 postgres,请使用
db:5432
连接,并从外部使用localhost:5432
Edit: Try this as your docker-compose.yml
编辑:试试这个作为你的
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.