0
votes

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
1

1 Answers

0
votes

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