1

I am trying to spin up a Postgres service and access it from within a docker container. This is my .gitlab-ci.yml:

image: docker:dind

stages:
  - build
  
services:
 - docker:dind
 - postgres:11-alpine

variables:
  POSTGRES_HOST_AUTH_METHOD: trust
  POSTGRES_DB: gitlabci

build_and_test:
  when: manual
  stage: build
  script:
    - docker run --rm postgres psql postgresql://postgres@postgres/gitlabci -c "SELECT 1;"

however, when I run this job I get an error:

psql: error: could not translate host name "postgres" to address: Name or service not known

How do I specify hostname from within a docker container?

1
  • You might find it easier to create your own docker and docker-compose files that contain some service (postgres) and then do docker-compose up in the ci. The service name you give in docker-compose will be the hostname you can use to connect to it. Then you simply create ci env variables that have those hostnames as the value so your other services can connect to it. Commented Feb 18, 2021 at 16:43

1 Answer 1

0

You can simplify your setup to

build_and_test:
  when: manual
  stage: build
  services:
    - name: postgres:11-alpine
      alias: postgres
  variables:
    POSTGRES_HOST_AUTH_METHOD: trust
    POSTGRES_DB: gitlabci  
    POSTGRES_USER: postgres
  script:
    - apk add postgresql-client
    - psql -h postgres -U postgres -d gitlabci -c "select 1;"

I assume your setup does not work because of different networks. Also, since you are using non-default postgres image, its auto-generated name could be different.

You can do

  services:
    - name: postgres:11-alpine
      alias: postgres

Sign up to request clarification or add additional context in comments.

3 Comments

your example works, but in my case I need to access service from within docker, see docker run in my example. That is the main problem.
try give service alias as in my example and run your container with --network host option
I have a similar scenario where the container that can't reach postgres is built in a previous step and the current step is needed to test the image (not just its code). Removing the docker run misses the intent of the question even though the MCVE loses the "why" of the question. I've tried this with --network=host too, and unfortunately it didn't help. It seems that postgresql doesn't have an exposed IP address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.