I am struggling to connect to a running container with a postgres database from another container. I can connect when running locally, but I suspect that there is some networking issue that I’m overlooking when trying to connect from another container. The specific error I am currently seeing is psycopg2.OperationalError: could not translate host name "my_network" to address: Temporary failure in name resolution
Here is my docker-compose:
version: '3'
services:
data_collection:
build: ./docker/data_collection
ports:
- "8888:8888"
- "6006:6006"
- "8000:8000"
networks:
- my_network
depends_on:
- db
db:
image: 'postgres:13.2-alpine'
ports:
- "5432:5432"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=mypassword
- POSTGRES_DB=spotify
volumes:
- db-data:/var/lib/postgresql/data # persist data even if container shuts down
networks:
- my_network
volumes:
db-data: # names volumes can be managed easier using docker-compose
networks:
my_network:
~
I then enter a shell in my data_colleciton
container and try to connect by reading those params into a variables params
, which gets passed in like this:
import psycopg2
params = dict(host='my_network', database='spotify', user='postgres', password='mypassword', port='5432')
conn = psycopg2.connect(**params)
However, running this locally and replacing the host above with localhost does work as expected
>Solution :
Change the host='my_network'
to host='db'
. You are not connecting to the network, you are connecting to a specific host in that network.