Connecting to a service container while inside a Docker container on Bitbucket Cloud Pipelines

Platform Notice: Cloud Only - This article only applies to Atlassian products on the cloud platform.

Summary

The Docker service containers in Pipelines, such as MongoDB and MySQL database containers, are made available on localhost and are usually accessible from the step container at 127.0.0.1:<port> or localhost:<port>. However, if you want to access the service URL from within a Docker container spun under a step, you won't be able to use 127.0.0.1:<port> or localhost:<port> since localhost is referred to within the step Docker container.

For Example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 image: postgres pipelines: default: - step: script: - docker run -d -t -p 5433:5432 --name db2 -e POSTGRES_DB=pipelines -e POSTGRES_USER=test_user -e POSTGRES_PASSWORD=test_user_password postgres           - docker exec db2 psql postgresql://test_user1:test_user_password1@localhost:5432/pipelines services: - postgres - docker definitions: services: postgres: image: postgres variables: POSTGRES_DB: 'pipelines' POSTGRES_USER: 'test_user1' POSTGRES_PASSWORD: 'test_user_password1'

Pipeline error:

1 2 3 4 docker exec db2 psql postgresql://test_user1:test_user_password1@localhost:5432/pipelines<1s + docker exec db2 psql postgresql://test_user1:test_user_password1@localhost:5432/pipelines psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: role "test_user1" does not exist

Solution

Starting from version 20.10, the Docker Engine also supports communication with the Docker host via "host.docker.internal" on Linux. The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name "host.docker.internal", which resolves to the internal IP address used by the host.

You need to provide the following run flag when you start the container:

1 --add-host=host.docker.internal:host-gateway

For Example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 image: postgres pipelines: default: - step: script: - docker run -d -t --add-host=host.docker.internal:host-gateway -p 5433:5432 --name db2 -e POSTGRES_DB=pipelines -e POSTGRES_USER=test_user -e POSTGRES_PASSWORD=test_user_password postgres - docker exec db2 psql postgresql://test_user1:test_user_password1@host.docker.internal:5432/pipelines services: - postgres - docker definitions: services: postgres: image: postgres variables: POSTGRES_DB: 'pipelines' POSTGRES_USER: 'test_user1' POSTGRES_PASSWORD: 'test_user_password1'

Updated on February 25, 2025

Still need help?

The Atlassian Community is here for you.