Docker container talks to service container

Hi,

I have a service container (postgres) running. As outlined in workflows/postgres-service.yml

The job and all the steps are running on a Linux Runner (not inside a docker container). But, I’d like to invoke a docker container on the runner to run a command inside a container talking to the service container.

E.g.,

steps:
  - name: test postgres connection
    run: psql -h localhost -d postgres -p 5432 -U user -t -c 'SELECT datname FROM pg_database;'

This works. But now I’d like to run the exact same command from within a docker container targeting the service postgres container:

steps:
  - name: test docker connection
    run: docker run --rm postgres:11.8-alpine sh -c "exec psql -h postgres -d postgres -p 5432 -U user -t -c 'SELECT datname FROM pg_database;"

# fails
# Error: raw error: psql: could not translate host name "postgres" to address: Name does not resolve

This fails, because the 2 containers are on different networks.

Is it possible to run the jobs on Linux Runner (not container) while invoking a docker container with docker run and having said container talk to the service container?

Based on how Docker networking works: You’d just need to connect your container to the same network as the service containers. According to documentation the name of the network is available in the job context as job.container.network, so something like this should work:

steps:
  - name: test docker connection
    run: docker run --rm --network ${{ job.container.network }} postgres:11.8-alpine sh -c "exec psql -h postgres -d postgres -p 5432 -U user -t -c 'SELECT datname FROM pg_database;"

My guess is that they use a custom network because Docker doesn’t provide DNS on the default network.

1 Like

Awesome, ${{ job.container.network }} is what I was missing. Need to spend a bit more time with the docs.

Indeed each gets a unique docker network.

 /usr/bin/docker network create --label 8118cb github_network_2ebe68e5c753469eb53b397da5c04539

# where 2ebe68e5c753469eb53b397da5c04539 is some unique hash every time

thank you @airtower-luna

1 Like