Why can't I ping docker container within python? Why can't I ping docker container within python? docker docker

Why can't I ping docker container within python?


Your issue is that you run the container and don't wait for the service to comeup. You should wait for the service to get up. You can use something like below

def wait_net_service(server, port, timeout=None):    """ Wait for network service to appear         @param timeout: in seconds, if None or 0 wait forever        @return: True of False, if timeout is None may return only True or                 throw unhandled network exception    """    import socket    import errno    s = socket.socket()    if timeout:        from time import time as now        # time module is needed to calc timeout shared between two exceptions        end = now() + timeout    while True:        try:            if timeout:                next_timeout = end - now()                if next_timeout < 0:                    return False                else:                    s.settimeout(next_timeout)            s.connect((server, port))        except socket.timeout, err:            # this exception occurs only if timeout is set            if timeout:                return False        except socket.error, err:            # catch timeout exception from underlying network library            # this one is different from socket.timeout            if type(err.args) != tuple or err[0] != errno.ETIMEDOUT:                raise        else:            s.close()            return True

and then update your code to

docker_client.containers.run(docker_image, detach=True, ports={'80/tcp': 83})wait_net_service("localhost", 83, 10)r = requests.get("http://localhost:83")

PS: the code has been taken from https://code.activestate.com/recipes/576655-wait-for-network-service-to-appear/