Skip to content

Instantly share code, notes, and snippets.

@konradkonrad
Last active February 28, 2018 09:26
Show Gist options
  • Save konradkonrad/fa11b13b3fa6d68f2c9a13296e99f29a to your computer and use it in GitHub Desktop.
Save konradkonrad/fa11b13b3fa6d68f2c9a13296e99f29a to your computer and use it in GitHub Desktop.
[D]ocker [O]ne [OF]f script (run a container inside the current working directory)
#!/usr/bin/env sh
## Features:
## - host's working directory is mounted to random location as the container's working directory
## - uid/gid of the current user are preserved inside the container
## - a host tmp dir will be mounted as /home/user and published as HOME environment variable inside the container
## - all EXPOSED ports will be published (check `docker port $(docker ps -q|head -n1)`).
## - container will be removed on exit
##
## Examples:
### doof pypy # start a pypy repl in $PWD
### doof pypy pypy3 script.py # run `$PWD/script.py` inside the pypy container
### doof ruby /bin/bash # run bash inside a ruby container
### doof elasticsearch -Dpath.data=/home/user/data # run elasticsearch, write inside the temporary home
CONTAINER="${1:--h}"
if [ "$#" -gt 1 ]
then
shift 1
CMD=$@
else
CMD=
fi
if [ $CONTAINER = "-h" ]
then
echo "Run a Docker One-OFf command."
echo "Usage:\n\t$(basename $0) IMAGE_NAME [CMD inside container]"
exit
fi
DIR=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
HOME_DIR=$(mktemp -d)
check_ports () {
RUNNING="$(docker ps -q|head -n1)"
if [ ${#RUNNING} -gt 0 ]
then
PORTS=$(docker port $RUNNING)
# FIXME: formatting is off
printf "\n\nDOOF PORTS:\n\n$PORTS\n\n"
fi
}
(sleep 3 && check_ports) &
docker run --rm -it --publish-all \
-v $HOME_DIR:/home/user \
-e HOME=/home/user \
-v $(pwd):/$DIR \
--workdir /$DIR \
--user $(id -u):$(id -g) \
"$CONTAINER" $CMD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment