Created
March 23, 2018 19:09
-
-
Save jriquelme/fa7c7e782f97c78fc98e988298e9e87c to your computer and use it in GitHub Desktop.
Python script to build simple Docker images using GO binaries (located in $GOPATH/bin)
This file contains hidden or 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 argparse | |
import io | |
import os | |
import tarfile | |
import docker | |
parser = argparse.ArgumentParser() | |
parser.add_argument('app', help='GO app name (located in $GOPATH/bin/)') | |
parser.add_argument('tag', help='Docker image tag') | |
parser.add_argument('--save-ctx', help='save Docker build context', action='store_true') | |
args = parser.parse_args() | |
# check if the given app exists in $GOPATH/bin | |
gopath = os.getenv('GOPATH') | |
if (gopath is None): | |
raise Exception('GOPATH not set') | |
app_path = os.path.join(gopath, 'bin', args.app) | |
if not os.path.exists(app_path): | |
raise Exception(f'file {app_path} not found') | |
with io.BytesIO() as buff: | |
# create tar.gz with context | |
with tarfile.open(fileobj=buff, mode='w:gz') as ctx: | |
# Dockerfile | |
dockerfile = (f'''FROM buildpack-deps:jessie-curl | |
COPY {args.app} /usr/bin/ | |
ENTRYPOINT ["/usr/bin/{args.app}"]''').encode("utf-8") | |
df_info = tarfile.TarInfo('Dockerfile') | |
df_info.size = len(dockerfile) | |
ctx.addfile(df_info, io.BytesIO(dockerfile)) | |
# $GOPATH/bin/app | |
ctx.add(app_path, arcname=args.app) | |
ctx.close() | |
# save context to <app>.tar.gz | |
if args.save_ctx: | |
with open(f'{args.app}.tar.gz', 'wb') as f: | |
f.write(buff.getvalue()) | |
# build the image using buff as build context | |
client = docker.from_env() | |
client.images.pull('buildpack-deps', 'jessie-curl') | |
buff.seek(0) | |
img = client.images.build(fileobj=buff, tag=args.tag, custom_context=True, encoding='gzip') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment