django test failed to start in gitlab ci

Viewed 407

i used docker and django for this project and gitlab ci/cd pipleline and test wont even start and exit below error:

tests was running until i add some tests in django app and after that it failed.


django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known

here is my Dockerfile

FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

my docker-compose.yml:

version: "3.9"

services:
  db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

and my gitlab-ci.yml:

image: python:latest

services:
  - mysql:latest
  - postgres:latest

variables:
  POSTGRES_DB: postgres
  
cache:
  paths:
    - ~/.cache/pip/

test:
  variables:
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
  script:
    - pip install -r requirements.txt
    - python manage.py test



build:
  image: docker:19.03.12
  stage: build
  services:
    - docker:19.03.12-dind
  variables:
    IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker build -t $IMAGE_TAG .
    - docker push $IMAGE_TAG
1 Answers

Create a network for the containers in your docker-compose file and share the network between your app and db.

something like this

  db:
    networks:
      - network_name
    # your other db setup follows

  web:
    networks:
      - network_name
    # your other web setup follows


networks:
  network_name:
Related