Skip to content

Instantly share code, notes, and snippets.

@michaelconnor00
Forked from zbyte64/sample.py
Last active October 22, 2022 21:42
Show Gist options
  • Save michaelconnor00/b3c332a2d6b70f6443d33459d3a731aa to your computer and use it in GitHub Desktop.
Save michaelconnor00/b3c332a2d6b70f6443d33459d3a731aa to your computer and use it in GitHub Desktop.
Docker Python put_archive example
import tarfile
import time
import json
from io import BytesIO
import docker
src_code = """
if __name__ == "__main__":
print('Hello World, From Alpine!!!!!!!!!')
"""
pw_tarstream = BytesIO()
pw_tar = tarfile.TarFile(fileobj=pw_tarstream, mode='w')
file_data = src_code.encode('utf8')
tarinfo = tarfile.TarInfo(name='test.py')
tarinfo.size = len(file_data)
tarinfo.mtime = time.time()
#tarinfo.mode = 0600
pw_tar.addfile(tarinfo, BytesIO(file_data))
pw_tar.close()
pw_tarstream.seek(0)
dest_path = '/root/'
client = docker.from_env()
conts = client.containers.list()
alpine = [c for c in conts if c.attrs['Config']['Image'] == 'alpine']
alpine = alpine[0]
success = alpine.put_archive(dest_path, pw_tarstream)
if not success:
raise Exception('Put file failed')
new_entrypoint = 'ENTRYPOINT ["echo", "Hello World"]'
alpine.commit('michaelconnor00/test', 'latest', changes=new_entrypoint)
for line in client.images.push('michaelconnor00/test', 'latest', stream=True):
all_lines = line.split('\r\n')
all_lines = [x for x in all_lines if x != '']
done = False
for l in all_lines:
line_dict = json.loads(l)
print(line_dict)
if 'aux' in line_dict.keys():
print('=== Push Sucessfull ===')
done = True
if done:
break
"""
{u'status': u'The push refers to a repository [docker.io/michaelconnor00/radd_test]'}
{u'status': u'Preparing', u'progressDetail': {}, u'id': u'0d44291adc24'}
{u'status': u'Preparing', u'progressDetail': {}, u'id': u'23b9c7b43573'}
{u'status': u'Layer already exists', u'progressDetail': {}, u'id': u'0d44291adc24'}
{u'status': u'Layer already exists', u'progressDetail': {}, u'id': u'23b9c7b43573'}
{u'status': u'latest: digest: sha256:9186c1d40bb58696b6e3f46ffdd9ecef0aecc24b591e0294114103b10731a50f size: 735'}
{u'progressDetail': {}, u'aux': {u'Tag': u'latest', u'Digest': u'sha256:9186c1d40bb58696b6e3f46ffdd9ecef0aecc24b591e0294114103b10731a50f', u'Size': 735}}
=== Push Sucessfull ===
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment