简体   繁体   中英

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". 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. 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. Tried "localhost" instead of "db" also. When running python script inside docker container, it has no problem to recognize other docker container (db in my case). What am I missing?

EDIT: Just to clarify, I am running only database in docker. Python script is started locally, using in my windows command line

python myscript.py

Docker-compose file:

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. If you want to access postgres from another container on the same network, connect with db:5432 , and from the outside with localhost:5432

Edit: Try this as your 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM