Skip to content

Instantly share code, notes, and snippets.

@nicovillanueva
Last active August 29, 2015 14:21
Show Gist options
  • Save nicovillanueva/8b3904cd926a2e5e500a to your computer and use it in GitHub Desktop.
Save nicovillanueva/8b3904cd926a2e5e500a to your computer and use it in GitHub Desktop.
Get the IP of a running Docker container, by partial name search
#!/usr/bin/python3
# If you have the exact name of the container, just run:
# docker inspect --format {{.NetworkSettings.IPAddress}} <container_name>
import subprocess, json, argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--name', required=True, help='Name of the container you want the IP of')
params = parser.parse_args()
ps = subprocess.Popen(('docker', 'ps'), stdout=subprocess.PIPE)
try:
grp = subprocess.check_output(['grep', params.name], stdin=ps.stdout)
except subprocess.CalledProcessError:
print("Container %s not found." % params.name)
sys.exit(1)
contId = grp[:12].decode('utf-8')
j = subprocess.check_output(["docker", "inspect", contId])
insp = json.loads(j.decode('utf-8'))
ip = insp[0].get("NetworkSettings").get("IPAddress")
print("Container %s has ID %s and it's IP is: %s" % (params.name, contId, ip))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment