Home > Enterprise >  Docker Compose & Postgres Connection Refused
Docker Compose & Postgres Connection Refused

Time:02-20

I know this question has been asked a million times, and I've read as many of the answers as I can find. They all seem to come to one conclusion (db hostname is the container service name).

I got it to work in my actual code base, but it started failing when I added ffmpeg install to the Dockerfile. Nothing else had to be done, just installing FFPMEG via apt-get install -y ffmpeg would cause my python code to get the connection refused message. If I removed the ffmpeg install line, then my code would connect to the db just fine. Although re-running the container would trigger the dreaded connection refused error.

So I created a quick sample app so I could post here and try to get some thoughts on what's going on. But now this sample code won't connect to the db no matter what I do.

So here goes - And thanks in advance for any help:

myapp.py

# import ffmpeg
import psycopg2

if __name__ == "__main__":
    print("Starting app...")
    # probe = ffmpeg.probe("131698249.mp4")
    # print(probe)

    try:
        connection = psycopg2.connect(
            user="docker", password="docker", host="db", port="5432", database="docker")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select * from test_table"

        cursor.execute(postgreSQL_select_Query)
        print("Selecting rows from table using cursor.fetchall")
        records = cursor.fetchall()

        print("Print each row and it's columns values")
        for row in records:
            print(row)

        cursor.close()
        connection.close()
    except (Exception, psycopg2.Error) as error:
        print("Error while fetching data from PostgreSQL", error)

Dockerfile


WORKDIR /usr/src/app

COPY requirements.txt .
RUN python -m pip install -r requirements.txt

COPY . .

CMD ["python", "myapp.py"]

docker-compose.yml

version: '3.8'
services:
  db:
    container_name: pg_container
    image: postgres:14.1
    restart: always
    environment:
      POSTGRES_USER: docker
      POSTGRES_PASSWORD: docker
      POSTGRES_DB: docker
    ports:
      - "8000:5432"
    expose:
      - "5432"
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      - pg_data:/var/lib/postgresql/data

  myapp:
    container_name: myapp
    build:
      context: .
      dockerfile: ./Dockerfile
    restart: "no"
    depends_on:
      - db

volumes:
  pg_data:

If I build and run the code: docker compose up --detach Everything gets built and started. The Database starts up and gets populated with table/data from the init.sql (not included here) The app container starts and the code executes, but immediately fails with the Connection refused error.

However, if from my computer I run: psql -U docker -h localhost -p 8000 -d docker it connects without any error and I can query the database as expected.

But the app in the container won't connect and if I run the container with docker run -it myapp /bin/bash and then from inside the container run: psql -U docker -h db -p 5432 -d docker I get the Connection refused error.

If anyone has any thoughts or ideas I would be so grateful. I've been wrestling with this for three days now.

CodePudding user response:

Looks like I've resolved it. I was sure I'd tried this before, but regardless adding a networks section to the docker-compose.yml seemed to fix the issue.

I also had to do the second docker-compose up -d as suggested by David Maze's comment. But the combination of the two seem to have fixed my issue.

Here's my updated docker-compose.yml for complete clarity:

version: '3.8'

services:
  postgres-db:
    container_name: pg_container
    image: postgres:14.1
    restart: always
    environment:
      POSTGRES_USER: docker
      POSTGRES_PASSWORD: docker
      POSTGRES_DB: docker
    ports:
      - "5500:5432"
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - dock-db-test

  myapp:
    container_name: myapp
    build:
      context: .
      dockerfile: ./Dockerfile
    restart: "no"
    depends_on:
      - db
    networks:
      - dock-db-test

networks:
  dock-db-test:
    external: false
    name: dock-db-test
  • Related