Skip to content

Instantly share code, notes, and snippets.

@titpetric
Created April 1, 2016 14:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save titpetric/e42514976582ca6c08a57ca58f104bff to your computer and use it in GitHub Desktop.
Save titpetric/e42514976582ca6c08a57ca58f104bff to your computer and use it in GitHub Desktop.
#!/bin/bash
function docker_run_shell {
NAME=$1
DOCKERFILE=$2
# docker needs a few libraries, but not all - essential libs here
BIND_LIBS=`ldd /usr/bin/docker | grep /lib/ | awk '{print $3}' | egrep '(apparmor|libseccomp|libdevmap|libsystemd-journal|libcgmanager.so.0|libnih.so.1|libnih-dbus.so.1|libdbus-1.so.3|libgcrypt.so.11)'`
ARGS=""
for LIB in $BIND_LIBS; do
ARGS="$ARGS -v $LIB:$LIB:ro"
done
ARGS="$ARGS -v /var/run/docker.sock:/run/docker.sock -v $(which docker):/bin/docker:ro"
# pass ssh agent
if [ ! -z "$SSH_AUTH_SOCK" ]; then
ARGS="$ARGS -v $(dirname $SSH_AUTH_SOCK):$(dirname $SSH_AUTH_SOCK) -e SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
fi
docker run -it --net=party -w /root \
-h $NAME --name $NAME \
$ARGS \
-e LANG=$LANG -e LANGUAGE:$LANGUAGE \
$DOCKERFILE /bin/bash
echo "Commiting changes to $NAME, please wait..."
docker ps --filter="name=$NAME" -a -q | xargs -n1 -I {} docker commit {} $NAME
echo "Deleting container after us."
docker rm -f $NAME
echo "Done."
}
function docker_attach_shell {
CONTAINER=$1
echo "Attaching a bash session to $CONTAINER..."
docker exec -it $CONTAINER /bin/bash
}
function give_shell {
NAME=$1
RUNNING=$(docker inspect --format="{{ .State.Running }}" $NAME 2> /dev/null)
if [[ "$RUNNING" == "true" ]]; then
# attach a shell with docker exec
docker_attach_shell $NAME
else
FRESH_START="debian:jessie"
if [[ "$(docker images -q $NAME 2> /dev/null)" == "" ]]; then
# start a clean container
echo "Spawning $NAME from scratch"
docker_run_shell $NAME $FRESH_START
else
# start from an existing image
echo "Starting $NAME from saved copy"
docker_run_shell $NAME $NAME
fi
fi
}
NAME="shell-$LOGNAME"
function show_menus {
echo "---------------------"
echo
echo "1. Enter docker shell ($NAME)"
echo "2. Drop to system shell (host: `uname -n`)"
echo
}
function read_options {
local choice
read -p "Enter choice: " choice
case $choice in
1) give_shell $NAME ;;
*) exit ;;
esac
}
if [ -z "$SSH_AUTH_SOCK" ]; then
echo "---------------------"
printf "#\n# Warning: SSH Agent not forwarded, auth_sock missing\n#\n"
fi
while true
do
show_menus
read_options
done
@titpetric
Copy link
Author

Posted in: "How to live inside a docker container",
https://scene-si.org/2016/04/01/how-to-live-inside-a-docker-container/

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