Search code examples
postgresqldockeradminer

Adminer & Migrate Can't Connect to Postgresql Docker Container


I have three docker containers (postgresql, adminer, and go/migrate) and I've exposed both adminer and postgres ports to the host. I can access adminer in my browser, and postico can also connect to the DB. When I try to connect to the db from within adminer, it throws this error:

SQLSTATE[08006] [7] could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP
connections on port 5432? could not connect to server: Address not available
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

The migrate container throws this error too:

error: dial tcp: 127.0.0.1:5432: connect: connection refused

So, clearly there is an issue with how the containers are able to communicate with each other. Do I need to create a docker network?

version: '3.1'

services:
  db:
    image: postgres
    environment:
        POSTGRES_DB: mydbname
        POSTGRES_USER: mydbuser
        POSTGRES_PASSWORD: mydbpwd
    ports:
      - "5432:5432"

  migrate:
    image: migrate/migrate
    volumes:
        - .:/migrations
    command: ["-database", "postgres://mydbuser:mydbpwd@localhost:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
    links: 
        - db

  adminer:
    image: adminer
    restart: always
    ports:
      - "8081:8080"
    depends_on:
      - db


Solution

  • You do not need to create linking, docker-compose create default network. also service to service communication should use service name, localhost mean this container(migrate) not DB container.

    change localhost to db

      migrate:
        image: migrate/migrate
        volumes:
            - .:/migrations
        command: ["-database", "postgres://mydbuser:mybpwd@db:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
    

    as you DB service name is db so you connect with db container using it name.