skip to Main Content

I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run

django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "database" (172.19.0.3) and accepting
TCP/IP connections on port 5432?

My gitlab-ci file is like this

image: docker:latest
services:
  - docker:dind

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2

test:
  stage: test
  image: tiangolo/docker-with-compose
  script:
    - docker-compose -f docker-compose.yml build
    - docker-compose run app python3 manage.py test

my docker-compose is like this:

version: '3'
volumes:
  postgresql_data:
services:
  database:
    image: postgres:12-alpine
    environment:
        - POSTGRES_DB=test
        - POSTGRES_USER=test
        - POSTGRES_PASSWORD=123
        - POSTGRES_HOST=database
        - POSTGRES_PORT=5432
    volumes:
        - postgresql_data:/var/lib/postgresql/data
    healthcheck:
        test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -e "SHOW DATABASES;""]
        interval: 5s
        timeout: 5s
        retries: 5
    ports:
        - "5432"
    restart: on-failure

  app:
    container_name: proj
    hostname: proj
    build:
      context: .
      dockerfile: Dockerfile
    image: sampleproject
    command: >
      bash -c "
        python3 manage.py migrate  &&
        python3 manage.py wait_for_db  &&
        gunicorn sampleproject.wsgi:application -c ./gunicorn.py
      "
    env_file: .env
    ports:
      - "8000:8000"
    volumes:
        - .:/srv/app
    depends_on:
       - database
       - redis

So why its refusing connection? I don’t have any idea and it was working last week.

3

Answers


  1. Could you do a docker container ls and check if the container name of the database is in fact, "database"?
    You’ve skipped setting the container_name for that container, and it may be so that docker isn’t creating it with the default name of the service, i.e. "database", thus the DNS isn’t able to find it under that name in the network.

    Login or Signup to reply.
  2. Reboot the server. I encounter similar errors on Mac and Linux from time to time when I run more than one container that use postgres.

    Login or Signup to reply.
  3. Unsure if it would help in your case but I was getting the same issue with docker-compose. What solved it for me was explicitly specifying the hostname for postgres.

    services:
      database:
        image: postgres:12-alpine
        hostname: database
        environment:
            - POSTGRES_DB=test
            - POSTGRES_USER=test
            - POSTGRES_PASSWORD=123
            - POSTGRES_HOST=database
            - POSTGRES_PORT=5432
    
        ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search