/
gockerize
executable file
·89 lines (73 loc) · 2.82 KB
/
gockerize
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
82
83
84
85
86
87
88
#!/bin/bash
#
# Copyright (c) 2015-2017, Air Computing Inc. <oss@aerofs.com>
# All rights reserved.
set -e
[[ $# -ge 2 ]] && [[ $# -lt 6 ]] || {
echo "Usage: $0 <image> <service> [<source> [<mapping> [<Dockerfile>]]]"
echo " <image> name of the docker image to be produced"
echo " <service> fully qualified name of the go package to build"
echo " e.g. 'aerofs.com/ca-server'"
echo " <source> path to source hierarchy to be imported into container"
echo " Default: ."
echo " <mapping> location into which sources are copied, under GOPATH/src/"
echo " Default: <service>/<source> if <source> starts with \"..\""
echo " <service> otherwise"
echo " <Dockerfile> path to Dockerfile"
echo " Default: ./Dockerfile"
echo ""
echo "Extra arguments, such as build tags, can be passed to the go build command via"
echo "the GOARGS environment variable."
exit 11
}
IMAGE=$1
SERVICE=$2
SRC_DIR=${3:-.}
if [[ $SRC_DIR == ..* ]] ; then
DST_DIR=${4:-${SERVICE}/${SRC_DIR}}
else
DST_DIR=${4:-${SERVICE}}
fi
DOCKERFILE=${5:-/dev/null}
# TODO: auto-detect latest stable golang release
# NB: stick to 1.5.3 by default for backwards compatibility
GOVERSION=${GOVERSION:-1.5.3}
BUILDER_PREFIX=aerofs/gockerize
BUILDER_BASE=${BUILDER_PREFIX}.base
BUILDER=${BUILDER_PREFIX}-${GOVERSION}
THIS_DIR="$( cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$THIS_DIR/img_fresh.sh"
if img_fresh "$IMAGE" "$SRC_DIR" ; then
echo "${IMAGE} already up-to-date"
exit 0
fi
echo "Building $BUILDER ..."
# build base builder container
docker build -t ${BUILDER_BASE} "$THIS_DIR"
# build builder with specific go version
docker build -t ${BUILDER} - <<EOF
FROM ${BUILDER_BASE}
RUN curl https://storage.googleapis.com/golang/go${GOVERSION}.linux-amd64.tar.gz -o go.tar.gz &&\
tar -C /usr/local -xzf go.tar.gz &&\
rm -rf go.tar.gz &&\
mkdir /gopath
EOF
tmpimg="${BUILDER}-$(echo "$IMAGE" | sed 's/\//./g')"
echo "Building $tmpimg ..."
# one cannot use a Dockerfile outside of the build context, hence the use of a tempfile
tmpfile="${SRC_DIR}/.gockerize.dockerfile"
cat - > "$tmpfile" <<EOF
FROM ${BUILDER}
COPY . /gopath/src/$DST_DIR
EOF
# build temporary container w/ build context
# NB: disable docker cache, it's not much use for the temporary container and
# some versions of docker do not correctly invalidate it upon file changes in
# the build context
docker build --no-cache=true -t "$tmpimg" -f "$tmpfile" "$SRC_DIR"
rm -f "$tmpfile"
echo "Building container image $IMAGE ..."
docker run --rm -i -v /var/run/docker.sock:/var/run/docker.sock \
${GOARGS:+"-e=GOARGS=$GOARGS"} "$tmpimg" "$IMAGE" "$SERVICE" < "$DOCKERFILE"
# remove temporary container
docker rmi "$tmpimg"