class DockerContainer(object): def __init__(self, image, version): self.env = {} self.ports = {} self._docker = DockerClient() self.image = "{}:{}".format(image, version) self._container = None def add_env(self, key, value): self.env[key] = value return self def expose_port(self, container, host=None): self.ports[container] = host return self def _configure(self): pass def start(self): self._configure() self._container = self._docker.run(self.image, detach=True, environment=self.env, ports=self.ports, publish_all_ports=True) return self def stop(self): self._container.remove(force=True) def __enter__(self): return self.start() def __exit__(self, exc_type, exc_val, exc_tb): self.stop() def get_container_host_ip(self) -> str: return "0.0.0.0" def get_exposed_port(self, port) -> str: return self._docker.port(self._container.id, port)
def test_docker_port(): docker = DockerClient() container = docker.run('selenium/hub:2.53.0', name='selenium-hub') print docker.port(container, 4444) print "End"
class DockerContainer(object): def __init__(self, image_name, version, container_name): self._docker = DockerClient() self._config = ContainerConfig(image_name=image_name, version=version, container_name=container_name) self._container = None def __enter__(self): return self.start() def __exit__(self, type, value, traceback): self.stop() def start(self): self._container = self._docker.run( image=self._config.image, bind_ports=self._config.port_bindings, env=self._config.environment, links=self._config.container_links, name=self._config.container_name, volumes=self._config.volumes) self.print_ports() return self def print_ports(self): logging.warning("Container port mappings {}".format( self.inspect()['NetworkSettings']['Ports'])) def stop(self): self._docker.stop(self._container) def get_host_info(self, port): info = self._docker.port(self._container, port) return info[0] def get_host_port(self, port): return self.get_host_info(port)['HostPort'] def get_host_ip(self, port): return self.get_host_info(port)['HostIp'] @property def container_name(self): return self._config.container_name def get_env(self, key): return self._config.environment[key] def add_env(self, key, value): self._config.add_env(key, value) def bind_ports(self, host, container): self._config.bind_ports(host, container) def mount_volume(self, host, container): self._config.mount_volume(host, container) def link_containers(self, target, current): self._config.link_containers(target, current) def inspect(self): return self._docker.inspect(self._container)