Skip to content

Instantly share code, notes, and snippets.

@xenithorb
Last active January 28, 2018 18:11
Show Gist options
  • Save xenithorb/5a76b018967ef33d6123c06781791877 to your computer and use it in GitHub Desktop.
Save xenithorb/5a76b018967ef33d6123c06781791877 to your computer and use it in GitHub Desktop.
Bashrc-style function/alias for running a container within a container
# Typically just stick this in ~/.bashrc
# call it with `docker-dind` or `dind` like you would `docker`
if command -v docker &>/dev/null; then
dind () { docker-dind "$@"; }
dind-deactivate() { unset DOCKER_HOST; }
dind-activate () { unset DOCKER_HOST; dind-info; export DOCKER_HOST="$DOCKER_DIND_HOST" DOCKER_DIND_PORTS; }
dind-info () {
local info host_info dind_info tmpfile
info="{{.Name}}, {{.ServerVersion}}, {{.OperatingSystem}}"
host_info=$(DOCKER_HOST='' docker info -f "$info")
tmpfile="/tmp/docker-dind-out.$$"
docker-dind info -f "$info" > "$tmpfile"; dind_good="$?"
dind_info=$(<"$tmpfile"); rm -f "$tmpfile"
if [[ "$host_info" == "$dind_info" ]] || (( dind_good != 0 )); then
echo "DIND NOT ACTIVE: ${dind_info}"
else
echo -ne "DIND ACTIVATED:\n\tHOST: ${host_info}\n\tDIND: ${dind_info}" \
"\n\n\tForwarded Ports: ${DOCKER_DIND_PORTS}\n"
fi
}
docker-dind () {
local port host id range_s range_e count name
name=docker_dind; host=localhost; port=4444; range_s=10001; range_e=10101
if (( $(docker ps -q -f name="${name}" | wc -l) <= 0 )); then
docker run --privileged \
-e PORT="$port" -p "${port}":2375 \
--net host \
-v "${name}:/var/lib/docker" \
--name "${name}" \
-d docker:dind \
dockerd --host unix:///var/run/docker.sock \
--host tcp://0.0.0.0:${port} \
>/dev/null
fi &&
until (( $(curl -sio /dev/null -w "%{http_code}" http://${host}:${port}/_ping) == 200 )); do
sleep .1; (( count > 50 )) \
&& { echo "Cannot connect to DinD daemon"; return 1; } \
|| ((++count))
done
if [[ $(DOCKER_HOST='' docker inspect ${name} --format="{{ .HostConfig.NetworkMode }}") == "host" ]]; then
DOCKER_DIND_PORTS="NONE: In host network mode"
else
DOCKER_DIND_PORTS="${range_s}${range_e:+-${range_e}}"
fi
export DOCKER_DIND_HOST="${host}:${port}" DOCKER_DIND_PORTS
DOCKER_HOST="$DOCKER_DIND_HOST" docker "$@"
}
fi
@xenithorb
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment