Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Created August 15, 2021 04:26
Show Gist options
  • Save bmcculley/98a805c63314991737feabbabc54e092 to your computer and use it in GitHub Desktop.
Save bmcculley/98a805c63314991737feabbabc54e092 to your computer and use it in GitHub Desktop.
Running a docker container from Python example.
import docker
import os
def run_container(container_name):
client = docker.from_env()
client.containers.run(container_name, ports={8080:8080}, detach=True)
def get_id(container_name):
client = docker.from_env()
if client.containers.list(filters={'ancestor': container_name}):
response = client.containers.list(filters={'ancestor': container_name})
return str(response[0].id)
else:
return None
def tail_container(cid):
client = docker.from_env()
container = client.containers.get(cid)
for line in container.logs(stream=True):
print(line.strip())
def stop_container(cid):
client = docker.from_env()
container = client.containers.get(cid)
container.stop()
if __name__ == '__main__':
try:
run_container('hello-world')
container_id = get_id('hello-world')
tail_container(container_id)
except KeyboardInterrupt:
print('Stopping container')
try:
stop_container(container_id)
print('Great success! See you next time.')
except SystemExit:
print('oh snap')
os._exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment