Unable to Connect to Postgres inside container

I have a Django application on gitlab and I am trying to add CI/CD using gitlab-ci. I started a server on EC2 and installed gitlab-runner on it.

I added .gitlab-ci.yml file to my project and pushed the latest changes. I can see the pipeline running and dependencies being installed. But When the script tries to run tests, I get an error like this:

django.db.utils.OperationalError: could not connect to server: Connection refused

Is the server running on host “localhost” (::1) and accepting TCP/IP connections on port 5432?

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?

My .gitlab-ci.yml file:

image: python:3-jessie

services:
  - postgres:latest

before_script:
  - python -V
  - apt-get -y update
  - apt-get install -y python-dev python-pip
  - pip install --upgrade pip

stages:
  - build
  - deploy

build:
  type: build
  variables:
    DATABASE_URL: postgres://postgres@postgres:5432/opensys_erp
  script:
  - pip install -r requirements.txt
  - python manage.py test
  only:
  - branches

deploy:
  type: deploy
  script:
  - echo "Deploying"
  only:
  - master

@manish2492 any updates on this?

Instead of database url define these params in gitlab-ci.yml and in django project use os.env.get("POSTGRES_DB", "default_name") to fetch db_name and other params from environment.

POSTGRES_DB: db_name
POSTGRES_HOST: postgres
POSTGRES_PORT: 5432
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres