postgresqldockerrails-postgresqlremote-connection

How to Connect to Docker Postgres Container from Host Machine


I put together a Rails dev environment by following instructions from https://docs.docker.com/compose/rails/

It works, but I am unable to connect to the Postgres server from the host machine. I am running macOS High Sierra. When I run docker container ls I see 5432/tcp as the port for the Postgres container. Note that there's not IP listed in front of 5432. When I run docker network inspect <postgress_container_ID> I get 172.18.0.2 as the IP.

But when I run psql -h 172.18.0.2 -p 5432 -U postgres I get

xpsql: could not connect to server: Operation timed out
  Is the server running on host "172.18.0.2" and accepting
  TCP/IP connections on port 5432?

What am I doing wrong?


Solution

  • By looking at your details 5432/tcp, It seems to me you have not exported port number 5432.

    if you have exported port, then it should look like.

     0.0.0.0:5432->5432/tcp
    

    and then by using HOST IP address (your local mac machine ip) you should be able to connect, if still not work, please share your docker command - how you are running container?

    Docker compose file

    version: '3'
    services:
      db:
        image: postgres
        ports:
         - "5432:5432"
      web:
        build: .
        command: bundle exec rails s -p 3000 -b '0.0.0.0'
        volumes:
          - .:/airbnb
        ports:
          - "3000:3000"
        depends_on:
          - db
    

    In your docker-compose file, you are not exposing port number 5432, hence from externally you won't able to connect Postgres DB.

    Try adding ports: - "5432:5432" in your docker-compose file. and then by using your machine IP address, you should able to connect database.