SLOBY
SLOBY

Reputation: 1107

Can't access postgresql in a docker container from a VM

I have a VM that is set up with vagrant via bash provisioning.

I try to install a bundle of applications and tools insode the VM upon startup and a few of those require a PostgreSQL database. I stripped down the provisioning phase to only include the necessary parts:

install.sh:

function installPostgresql() {
  docker pull postgres:9.4
  docker run --name dbcontainer -e POSTGRES_PASSWORD=$POSTGRES_PASSWORD -e POSTGRES_DB=dbname -e POSTGTES_HOST=localhost -d postgres
}

...
installPostgresql

This uses a default widely used docker image created for postgresql. I start it after pulling it from central repository.

For some reason, I cannot access the running postgres service inside of my VM but I CAN connect it if I execute /bin/bash on the running docker and use psql inside the docker inside the VM.

Inside VM:

vagrant@debian-jessie:~$ psql -h localhost -p 5432 -U postgres -W
Password for user postgres: 
psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
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?

Inside docker inside the VM:

root@1d0b5be83f6e:/# psql -h localhost -p 5432 -U postgres -W
Password for user postgres: 
psql (9.5.2)
Type "help" for help.

postgres=#

pg_hba.conf:

local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust
host    all             all             0.0.0.0/0               md5

Why is it working inside the docker inside the VM but not "only" from the VM?

Upvotes: 0

Views: 1384

Answers (1)

Rick
Rick

Reputation: 443

Sounds as if this is a port exposure issue. By default, Docker containers do not publish any ports to the host (in this case, your VM). However, if you link containers, those containers can interact with ports that are exposed (for example described in the related Dockerfile).

Try adding the -p option to your docker run command, to publish the PostgreSQL port to your host:

docker run --name dbcontainer -e POSTGRES_PASSWORD=$POSTGRES_PASSWORD -e POSTGRES_DB=dbname -e POSTGTES_HOST=localhost -d -p 5432:5432 postgres

You'll find more information about this in the documentation.

Upvotes: 3

Related Questions