I have a Dockerfile which I want to run some tests inside of as part of a multistage build. The tests attempt to make a connection to localhost, however it appears that they're not able to connect to the specific port (which is ready on the host machine) inside the RUN command of the Dockerfile. Is such a thing possible, and if so how do I achieve it? Obviously external connections can be made at build time (to download dependencies and such) and loopbacks at run time

FROM python:3.7-alpine as tester
COPY . .
RUN python -m unittest discover

And for reference, the Python code checking the connection

def setUp():
    timeout = 120.0
    port = 15903
    host = 'localhost'
    start_time = time.perf_counter()
    while True:
            with socket.create_connection((host, port), timeout=timeout):
        except OSError as ex:
            if time.perf_counter() - start_time >= timeout:
                raise TimeoutError('Waited too long for the port {} on host {} to start accepting connections.'.format(port, host)) from ex 

1 Answer 1


From your container's perspective localhost is the container itself. If you want to communicate with the host machine, you will need the IP address of the host itself. Depending on your Operating System and Docker configuration, this IP address varies.

edit host.docker.internal is recommended from 18.03 onward.

Here is an example of communicating with the Docker host from a container on Mac:

# Dockerfile

FROM python:3.7-alpine

RUN ping host.docker.internal -c 4
sending build context to Docker daemon  562.7kB
Step 1/2 : FROM python:3.7-alpine
 ---> a93594ce93e7
Step 2/2 : RUN ping host.docker.internal -c 4
 ---> Running in 54ce465f7386
PING host.docker.internal ( 56 data bytes
64 bytes from seq=0 ttl=37 time=0.735 ms
64 bytes from seq=1 ttl=37 time=1.898 ms
64 bytes from seq=2 ttl=37 time=0.720 ms
64 bytes from seq=3 ttl=37 time=0.643 ms

--- host.docker.internal ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.643/0.999/1.898 ms
Removing intermediate container 54ce465f7386
 ---> b2f32c26a135
Successfully built b2f32c26a135
  • What's about Docker on Linux? I'm having this error with Docker on Debian 12 > [backend-apitest-client 5/9] RUN ping host.docker.internal:4873 -c 4: 0.383 ping: host.docker.internal:4873: Name or service not known ------ failed to solve: process "/bin/sh -c ping host.docker.internal:4873 -c 4" did not complete successfully: exit code: 2
    – Lewis
    Oct 2, 2023 at 9:56

Your Answer

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

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