I have the following two containers in my docker-compose.yml file
postgres:
image: postgres:10.5
ports:
- 5105:5432
...
web:
restart: always
build: ./web
ports: # to access the container from outside
- "8000:8000"
env_file: .env
command: /usr/local/bin/gunicorn directory.wsgi:application --reload -w 1 -b :8000
volumes:
- ./web/:/app
depends_on:
- postgres
When I'm logged in to my "web" container (an Ubuntu 18 container), I'd like to be able to login to the PostGres container. How do I do this? I tried this
root@0868cef9c65c:/my-app# PGPORT=5432 PGPASSWORD=password psql -h localhost -Uchicommons directory_data
psql: error: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
but this doesn't seem to be working.
CodePudding user response:
In a Docker container, localhost
refers to the container itself.
By default, Docker compose creates a docker bridge network and connects each container to it. From a container on the bridge network, you can reach other containers using their service names. So to reach the database container, you'd use postgres
as the host name, like this
PGPORT=5432 PGPASSWORD=password psql -h postgres -Uchicommons directory_data
On the bridge network, you use the native ports. So it's port 5432 for Postgres. If you only need to access a container from other containers on the bridge network, you don't need to map the port to a host port. Mapping to a host port is only needed if you need to access the container from the host computer.