How to Connect to Docker Postgres Container from Host Machine

21,088

Solution 1

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.

Solution 2

By default, postgres exposes port 5432. This will only expose the port to other containers within the same Docker network -- i.e. all the other containers in the compose file. This is because by default, docker compose creates a network for all the containers in the compose file.

You have a few options for connecting to a container from the host:

  1. Expose the port with HOST:CONTAINER format which will make the container's port available on HOST IP. For example, use 127.0.0.1:5432 so you can access the port at that address on your host.
  2. Use the Docker network's gateway IP as the interface/source address. For example, if the container is 172.18.0.2, then likely the gateway is 172.18.0.1. There's usually a way to do this with postgres and socket libraries, but unfortunately I don't see a way to do it with psql.
  3. Set up IP tables so your host can access the Docker network.

Another option is to access it from a container within the Docker network. You can do docker-compose run --rm db psql -h db -U postgres which will run a one-off container with the same Docker image as the db container and within the same network.

Share:
21,088
Rayhan Muktader
Author by

Rayhan Muktader

Updated on July 09, 2022

Comments

  • Rayhan Muktader
    Rayhan Muktader almost 2 years

    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?