Created
April 17, 2019 11:38
-
-
Save danrjohnson/f16ca136529e35960d017c2b027643c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import docker | |
class DockerContainer(): | |
def __init__(self, docker_client=None, **container_opts): | |
self.container_opts = container_opts | |
self.docker_client = docker_client or docker.from_env() | |
self.container = None | |
def __enter__(self): | |
self.container = self.docker_client.containers.run(**self.container_opts) | |
return self.container | |
def __exit__(self, *args): | |
self.container.kill() | |
self.container.remove() | |
class MySQLDocker(): | |
def __init__(self, docker_image_name='mysql', mysql_version='5.7'): | |
self.mysql_version = mysql_version | |
self.docker_client = docker.from_env() | |
self.docker_image_name = docker_image_name | |
super().__init__() | |
@property | |
def image_name(self): | |
return '{}:{}'.format(self.docker_image_name, self.mysql_version) | |
def ensure_image(self): | |
self.docker_client.images.pull(self.image_name) | |
def run(self): | |
with DockerContainer(image=self.image_name, detach=True, environment={'MYSQL_ROOT_PASSWORD': 'my-secret-pw'}) as container: | |
init_complete = False | |
for log in container.logs(stream=True): | |
decoded = log.decode('utf-8').strip() | |
print(decoded) | |
if 'init process done' in decoded: | |
init_complete = True | |
if 'ready for connections.' in log.decode('utf-8') and init_complete: | |
print("We're done! exiting!") | |
return | |
if __name__ == '__main__': | |
mysql_docker = MySQLDocker() | |
mysql_docker.ensure_image() | |
mysql_docker.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment