1

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:
        try:
            with socket.create_connection((host, port), timeout=timeout):
                break
        except OSError as ex:
            time.sleep(1.0)
            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 
2

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 (192.168.65.2): 56 data bytes
64 bytes from 192.168.65.2: seq=0 ttl=37 time=0.735 ms
64 bytes from 192.168.65.2: seq=1 ttl=37 time=1.898 ms
64 bytes from 192.168.65.2: seq=2 ttl=37 time=0.720 ms
64 bytes from 192.168.65.2: 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

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.