-
Notifications
You must be signed in to change notification settings - Fork 12
/
run-container-fg
executable file
·81 lines (65 loc) · 2.18 KB
/
run-container-fg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/python3
import yaml
import os
import sys
import shlex
import subprocess
if not os.path.exists('./docker-compose.yml'):
print("This script requires a « docker-compose.yml » file in current directory.")
sys.exit(1)
if len(sys.argv) < 2 or sys.argv[1].startswith('-'):
print("Syntax: %s [service] <...>" % sys.argv[0])
print(" Will run the container named « service » from docker compose in foreground.")
print(" All extra arguments will be passed to Docker.")
sys.exit(1)
with open('./docker-compose.yml') as f:
compose = yaml.load(f)
service_name = sys.argv[1]
services = compose['services']
service = services.get(service_name, None)
if not service:
print("Service %s not found." % service_name)
sys.exit(1)
command = sys.argv[2:]
if not command:
command = shlex.split(service.get('command', []))
_, compose_name = os.path.split(os.getcwd())
network = '%s_default' % compose_name
image = service.get('image', None)
if image is None:
image = '%s_%s' % (compose_name, service_name)
i = 1
while True:
name = image + '_%d' % i
print("Checking %s..." % name)
output = subprocess.check_output([ "docker", "ps", "-a", "--format={{.State}}", "--filter=name=%s" % name ]).strip()
if output == b'running':
print("Container %s already running, trying next..." % name)
i += 1
continue
elif output in (b'exited', b'created'):
print("Cleaning %s..." % name)
output = subprocess.check_output([ "docker", "rm", name ])
break
else:
break
cmd_line = [ 'docker', 'run', '-it',
'--network', network,
'--name', name,
]
ports = service.get('ports', [])
for port in ports:
cmd_line.extend([ '-p', port ])
volumes = service.get('volumes', [])
for volume in volumes:
items = volume.split(':')
items[0] = os.path.abspath(items[0])
volume = ':'.join(items)
cmd_line.extend([ '-v', volume ])
env_files = service.get('env_file', [])
for env_file in env_files:
cmd_line.extend([ '--env-file', env_file ])
cmd_line.append(image)
cmd_line.extend(command)
print(" ".join(cmd_line))
os.execvp('docker', cmd_line)