When building an image of a docker container I need to access a service on host localhost.

It looks like --add-host option for docker command updates /etc/hosts both at image build time and container runtime.

The analogous option for docker-compose command, extra_hosts seems to work only at container runtime. How do I enable it at docker image build time?

Looks like there feature request for that: https://github.com/docker/compose/issues/7323, but not implemented yet. What would be workaround until this is solved?

Minimal working example

Here's my Dockerfile:

FROM python:3.8-slim-buster
RUN grep "host.docker.internal" /etc/hosts || echo "Missing"
CMD grep "host.docker.internal" /etc/hosts || echo "Missing"

and docker-compose.yml:

version: "3.9"
    build: .
      - "host.docker.internal:host-gateway"

Running docker:

docker build . --add-host host.docker.internal:host-gateway  --no-cache -t test \
    && docker run --add-host host.docker.internal:host-gateway test

prints:      host.docker.internal
...      host.docker.internal


docker-compose build --no-cache && docker-compose up


test_1  |    host.docker.internal


I have a Flask app that depends on my private Python package that I install during docker image build. I store my private Python packages in my local devpi instance hosted on the same machine I use for building docker image. Hence, my Flask app pyproject.toml points to the devpi instance:

url = "http://localhost:3141/testuser/dev/+simple"

or rather

url = "http://host.docker.internal:3141/testuser/dev/+simple"

1 Answer 1


The solution is to use Compose V2 and then:

docker compose build --no-cache && docker compose up

(note dashes replaced with spaces).

Here's specific line in implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.