Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to postgres in Gitlab CI

I am trying to use GitLab CI PostgreSQL for my integration tests but it doesn´t work.

Here's the code of the stage:

integration_test:
  stage: test
  tags:
    - custom_tag
  services: 
    - postgres
  variables: 
    POSTGRES_DB: test
    POSTGRES_HOST: postgres
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: postgres
    POSTGRES_HOST_AUTH_METHOD: trust
  script:
    - docker login -u ${DOCKER_USER} -p ${DOCKER_PASSWORD} ${DOCKER_REGISTRY}
    - docker pull ${DOCKER_IMAGE_CI}
    - export PGPASSWORD=${POSTGRES_PASSWORD}
    - docker run --rm postgres psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "SELECT 'OK' AS status;" 

It returns an error like this:

psql: error: could not connect to server: could not translate host name "postgres" to address: Name or service not known Anybody can help me?

like image 740
Mario Cruzado Avatar asked Nov 06 '22 09:11

Mario Cruzado


1 Answers

Perhaps it's better to look at dockerizing test functions. This approach also provides better control over networking by means of docker bridge. In this way your config could looks like this:

.gitlab-ci.yml:

stages:
 - test
before_script:
 - docker login -u ${DOCKER_USER} -p ${DOCKER_PASSWORD} ${DOCKER_REGISTRY}
integration_test:
  stage: test
  script:
    - docker-compose build
    - docker-compose up

docker-compose.yml:

version: '3'
networks:
  database:
services:
  postgres-db:
    image: ${DOCKER_IMAGE_CI}
    networks:
      - database
    container_name: postgres

  test-container:
    build:
      context: .
      dockerfile: Dockerfile
    networks:
      - database
    container_name: testcon

Dockerfile:

FROM postgres
ENV POSTGRES_DB=test \
    POSTGRES_HOST=postgres \
    POSTGRES_USER=postgres \
    POSTGRES_PASSWORD=postgres \
    POSTGRES_HOST_AUTH_METHOD=trust
CMD psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "SELECT 'OK' AS status;"
like image 170
Egor Avatar answered Nov 12 '22 10:11

Egor