DanielDent/docker-postgres-replication

Cannot connect to database

chris opened this issue · 3 comments

chris commented

Excuse my newb-ness on this (and if there's a better place to ask, let me know), but I cannot seem to actually connect to the database once this is running. I cloned the repo, didn't change anything (as I just need this for some local dev testing), and did docker-compose up. It seems to run fine, as I see this in the output:

pg-master_1  | LOG:  database system is ready to accept connections
pg-slave_1   | LOG:  database system is ready to accept read only connections

I see the two containers in docker ps, etc. I then tried to actually attach to it, e.g.:

psql -h 172.18.0.2 -U postgres -W

IP address I got from doing docker inspect on the master's container ID. This eventually just times out. I'm running this on a Mac. Could you clue me in to what I'm missing/doing wrong?

This sounds to me like it's probably a networking issue unrelated to docker-postgres-replication.

172.18.0.2 may not be routable from your Mac. If you are using Docker Toolbox, for example, the 172. ip space isn't routed - that IP space is only accessible from within the virtual machine that Docker Toolbox spins up on your behalf.

You could try running the psql command from within another Docker container and then it would execute within a context where that IP space is routable. You could also do some port forwarding magic.

chris commented

Thanks for that, led me to a very easy solution! All I needed to do was add the ports element to each service in the docker-compose.yml to map the ports to my local host, and then it worked, so I changed docker-compose.yml to be:

version: '2'

services:
  pg-master:
    build: '.'
    image: 'danieldent/postgres-replication'
    restart: 'always'
    environment:
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'postgres'
      PGDATA: '/var/lib/postgresql/data/pgdata'
    volumes:
     - '/var/lib/postgresql/data'
    ports:
    - '7432:5432'
    expose:
     - '5432'

  pg-slave:
    build: '.'
    image: 'danieldent/postgres-replication'
    restart: 'always'
    environment:
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'postgres'
      PGDATA: '/var/lib/postgresql/data/pgdata'
      REPLICATE_FROM: 'pg-master'
    volumes:
     - '/var/lib/postgresql/data'
    ports:
    - '7433:5432'
    expose:
     - '5432'
    links:
     - 'pg-master'

This of course means one has to specify a non-default port, and I also found that I had to explicitly specify 127.0.0.1 as the host when connecting (skipping a -h flag or similar didn't seem to allow it to connect).

Glad I could help. It's intentional that I did not include the port mapping - in a production environment, having the port listening on what may be a public context could be a security risk.

Others who have the same issue as you (especially in a development context) will appreciate your solution, thanks for posting it.