Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvgenyOrekhov/82a78debf7dea8ab1dd4da9c034aee14 to your computer and use it in GitHub Desktop.
Save EvgenyOrekhov/82a78debf7dea8ab1dd4da9c034aee14 to your computer and use it in GitHub Desktop.
docker-run - a POSIX shell script for running command-line tools in containers

A POSIX shell script for running command-line tools in containers

Install

  1. Clone this repo

    git clone https://gist.github.com/82a78debf7dea8ab1dd4da9c034aee14.git docker-run
    
  2. Create a link to docker-run in your /usr/local/bin/

    sudo ln -s "$PWD/docker-run/docker-run" /usr/local/bin/docker-run
    

Usage examples

   docker-run IMAGE COMMAND [COMMAND_OPTIONS]...

Node.js and npm

  1. Create /usr/local/bin/node with the following contents

    #!/bin/sh
    exec docker-run node:latest node "$@"
    
  2. Create /usr/local/bin/npm with the following contents

    #!/bin/sh
    exec docker-run node:latest npm "$@"
    
  3. Make the scripts executable

    sudo chmod +x /usr/local/bin/node /usr/local/bin/npm
    
  4. Now you can use them like regular CLI tools

    npm -v
    5.6.0
    

Advanced usage examples

   OPTIONS=[DOCKER_RUN_OPTIONS] docker-run IMAGE COMMAND [COMMAND_OPTIONS]...

Node.js with inspector agent enabled

   #!/bin/sh
   OPTIONS='-p 9229:9229' exec docker-run node:latest node --inspect=0.0.0.0:9229 "$@"

Credits

Inspired by docker-compose wrapper script

#!/bin/sh
#
# Run a command in a container
#
# This script will attempt to mirror the host paths by using volumes for the
# following paths:
# * $PWD
# * $HOME if it's set
#
set -eu
EX_USAGE=64
if [ $# -lt 2 ]; then
echo 'Error: missing argument' >&2
echo "Usage: $(basename "$0") IMAGE COMMAND [COMMAND_OPTIONS]..." >&2
exit $EX_USAGE
fi
DOCKER_RUN_OPTIONS=${OPTIONS:-''}
VOLUMES=''
DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS --rm --workdir $PWD"
# Only allocate tty if we detect one
if [ -t 1 ]; then
DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS --tty"
fi
if [ -t 0 ]; then
DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS --interactive"
fi
# Setup volume mounts
if [ "$PWD" != '/' ]; then
VOLUMES="$VOLUMES --volume $PWD:$PWD"
fi
if [ -n "$HOME" ]; then
VOLUMES="$VOLUMES --volume $HOME:$HOME --volume $HOME:/root"
fi
# shellcheck disable=SC2086
exec docker run $DOCKER_RUN_OPTIONS $VOLUMES "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment