Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't to connect to postgres container

I define postgres server in docker-compose.yml:

db:
    image: postgres:9.5
    expose:
        - 5432

Then in another docker container I tried to connect to this postgres container. But it gives an error with warning:

Is the server running on host "db" (172.22.0.2) and accepting
data-service_1  |   TCP/IP connections on port 5432?

Why container can't to connect to another by provided information (host="db" and port=5432)?

PS Full docker-compose.yml:

version: "2"
services:
    data-service:
        build: .
        depends_on:
            - db
        ports:
          - "50051:50051"
    db:
        image: postgres:9.5
        depends_on:
            - data-volume
        environment:
            - POSTGRES_USER=cobrain
            - POSTGRES_PASSWORD=a
            - POSTGRES_DB=datasets
        ports:
          - "8000:5432"
        expose:
            - 5432
        volumes_from:
            - data-volume
            # - container:postgres9.5-data
        restart: always

    data-volume:
        image: busybox
        command: echo "I'm data container"
        volumes:
            - /var/lib/postgresql/data
like image 341
Kenenbek Arzymatov Avatar asked Feb 01 '26 00:02

Kenenbek Arzymatov


1 Answers

Solution #1. Same file.

To be able to access the db container, you have to define your other containers in context of docker-compose.yml. When containers are started, each container gets all other containers mapped in /etc/hosts.

Just do

version: '2'
services:
  web:
    image: your/image
  db:
    image: postgres:9.5

If you do not wish to put your other containers into the same docker-compose.yml, there are other solutions:

Solution #2. IP

Do docker inspect <name of your db container> and look for IPAddress directive in the result listing. Use that IPAddress as host to connect to.

Solution #3. Networks

Make your containers join same network. For that, under each service, define:

services:
  db:
    networks:
     - myNetwork

Don't forget to change db for each container you are starting.

I usually go with the first solution during development. I use apache+php as one container and pgsql as another one, a separate DB for every project. I do not start more than one setting of docker-compose.yml, so in this case defining both containers in one .yml config is perfect.

like image 184
Alex Karshin Avatar answered Feb 04 '26 00:02

Alex Karshin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!