Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active June 27, 2018 10:50
Show Gist options
  • Save taikedz/0c80db21b153231b4928c532586e1222 to your computer and use it in GitHub Desktop.
Save taikedz/0c80db21b153231b4928c532586e1222 to your computer and use it in GitHub Desktop.
Run a shell inside a shell-less docker image (Ubuntu host, ephemeral container)
#!/bin/bash
# ++++++++++++++++++++++
die() {
echo -e "\033[31;1m$*\033[0m"
exit 1
}
# ++++++++++++++++++++++
do_run() {
docker run -it -v "$HBBOX:/$GBBOXd/busybox" --entrypoint="/$GBBOXd/busybox" "$@" "$TARGET" sh
}
do_exec() {
docker cp "$HBBOX" "$TARGET:/$GBBOXd/busybox"
docker exec -it "$@" "$TARGET" "/$GBBOXd/busybox" sh
}
# ++++++++++++++++++++++
printhelp() {
cat <<EOHELP
Adds busybox to an image or a running container, and runs an interactive shell inside the container.
$0 { run IMAGE | exec CONTAINER } BOXDIR [DOCKER_ARGS ...]
run IMAGE : run the shell in a new container from IMAGE
exec CONTAINER : run the shell in a running CONTAINER
BOXDIR : where to copy busybox to in the container - e.g. "/bin"
You may need to set this to a user directory if container is not running as root
Example:
$0 run hello-world /bin --rm
Runs /bin/busybox in an ephemeral container ('--rm' is passed to 'docker run', not to the image entrypoint)
EOHELP
}
# ++++++++++++++++++++++
main() {
if [[ "$*" =~ --help ]]; then
printhelp
exit 0
fi
ACTION="${1:-}"; shift || die "No action specified (run/exec)"
TARGET="${1:-}"; shift || die "No image/container specified"
HBBOX="$(which busybox)" || die "Busybox not in \$PATH on host."
GBBOXd="${1:-}" ; shift || die "You must indicate a full path to a directory in the container into which to copy busybox\n\n\te.g. '/home/user'"
case "$ACTION" in
exec)
do_exec "$@"
;;
run)
do_run "$@"
;;
*)
die "Not a supported action '$ACTION'"
;;
esac
}
main "$@"
@taikedz
Copy link
Author

taikedz commented Jun 27, 2018

At this point I should announce this script is released GPLv3.

Works so long as bash and busybox are both available on the host system. installing busybox does not replace the utilites it would normally substitute for if they are already present.

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