MelkorNemesis
MelkorNemesis

Reputation: 3435

PostgreSQL in Docker - access from host

I've been trying to get access to PostgreSQL running in a docker container. I'm able to connect to the PostgreSQL from within the adminer on localhost:8080, which is another container, but I'm not able to connect from my host machine, although I'm mapping the port 5432 to the host machine.

As a container's IP to connect to I've been using an IP address fetched from "docker inspect <postgre_container>" - usually 172.21.0.2/3.

This is what my docker-compose.yml looks like:

version: '3.1'

services:
  db:
    image: postgres:9.6.0
    restart: always
    environment:
      POSTGRES_PASSWORD: root
      POSTGRES_USER: root
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

volumes:
  pgdata:

I'll be glad for any hints, thanks

Upvotes: 0

Views: 526

Answers (2)

Md. Saifur Rahman
Md. Saifur Rahman

Reputation: 404

Network

sudo docker network create local_central_db_network

create a file docker-compose.yml

version: '3.3'

services:
  postgres:
    image: postgres:16.4 # Using PostgreSQL version 16.4
    container_name: local-central-db-pgsql-container-16.4
    restart: always
    ports:
      - "5432:5432" # Expose port 5432 for external access
    environment:
      POSTGRES_USER: root # Replace with your username
      POSTGRES_PASSWORD: root # Replace with your password
    volumes:
      - ./dbdata:/var/lib/postgresql/data # Persist data between restarts
    networks:
      - local_central_db_network

networks:
  local_central_db_network:
    external: true

Command : Docker : Setup : Initialized

sudo docker-compose down
sudo docker-compose build && docker-compose up -d

Connect in command line

docker exec -it local-central-db-pgsql-container-16.4 bash
psql -U root
\q

Note: in clients use like this

enter image description here

Upvotes: 0

ely
ely

Reputation: 77484

The IP address shown using docker inspect is the internal IP address within the container. Since you are using port mapping with external port 5432, you should access Postgres via localhost:5432 (e.g. 127.0.0.1:5432).

Upvotes: 1

Related Questions