Run postgreSQL gitlab docker

Viewed 838

I'm trying to run a pipeline on gitlab of a python webapp made with Django, that uses a postgre database. After installing postgre, the psql command gives the error:

psql: error: could not connect to server: No such file or directory

Here's (part of) my .gitlab-ci.yml file:

image: python:latest

# Install postgreSQL service on container
services:
    - postgres:12.2-alpine

# Change pip's cache directory to be inside the project directory
variables:
  PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
  DJANGO_SETTINGS_MODULE: "my_app.settings"
  POSTGRES_DB: $POSTGRES_DB
  POSTGRES_USER: $POSTGRES_USER
  POSTGRES_PASSWORD: $POSTGRES_PASSWORD
  POSTGRES_HOST_AUTH_METHOD: trust

# Let's cache also the packages
# Install packages in a virtualenv and cache it as well
cache:
  paths:
    - .cache/pip
    - venv/

before_script:
  - pip install virtualenv --upgrade pip
  - virtualenv venv
  - source venv/bin/activate
  - apt-get update
  #- apt-get install -y postgresql postgresql-client libpq-dev # postgre db requirements

stages:          # List of stages for jobs, and their order of execution
  - build
  - verify
  - unit_test
  - integration_test
  - package
  - release
  - deploy

build:
  stage: build
  script: 
    - pip install -r requirements.txt
    - echo "Build stage finished"

verify:
  stage: verify
  script:
    - prospector -X ./my_app  # static code analysis
    - bandit -r ./my_app     # static code analysis pt. 2
    - echo "Verify stage finished"

unit_test:
  stage: unit_test
  script:
    - echo "Running unit_test 1"
    - pytest ./my_app/unit_test.py #running unit_test    
    - echo "Creating db"
    - apt-get install -y postgresql postgresql-client libpq-dev # postgre db
    - psql -U postgres
    - psql -d "CREATE USER $POSTGRES_USER WITH PASSWORD $POSTGRES_PASSWORD CREATEDB;"
    - psql -d "CREATE DATABASE $POSTGRES_DB OWNER $POSTGRES_USER;"
    - echo "Unit testing stage finished"

How can I make psql work on gitlab CI/CD pipeline?

1 Answers

You're on the right track with the "services" keyword, which will cause a postgres database to run on the host "postgres" (the DNS of the service is based on the name of the container unless you specify an "alias" with the service).

Your issue is that psql attempts to connect to localhost unless you specify otherwise, so your psql -U postgres attempts to connect on localhost. Try using psql -U postgres -p 5432 -h postgres instead.

Related