docker-build-and-run
I've created a little helper command for building and running, in a single command. On Linux or Mac, you can add this to your ~/.bash_profile
to make it available in the Terminal.
Usage:
docker-build-and-run BUILD_ARGS [-- RUN_ARGS] [-- RUN_COMMAND]
Examples:
docker-build-and-run . -- npm run test
docker-build-and-run --file ./Dockerfile . -- -v ~/volume:/var/volume -- node server.js
The Script:
Add this to a .sh
file, or add it to your ~/.bash_profile
:
TERM_GREEN="\033[1;32m"
TERM_BLUE="\033[1;34m"
TERM_NC="\033[0m"
docker-build-and-run() {
if [[ -z "$@" ]]; then
echo "
Usage:
docker-build-and-run BUILD_ARGS [-- RUN_ARGS] [-- RUN_COMMAND]
Examples:
docker-build-and-run . -- npm run test
docker-build-and-run --file ./Dockerfile . -- -v ~/volume:/var/volume -- node server.js
"
return
fi
# Extract the segments between the dashes:
BEFORE_THE_DASHES=
while (( "$#" )); do
if [[ "$1" = "--" ]]; then
shift
break
fi
BEFORE_THE_DASHES="$BEFORE_THE_DASHES $1"
shift
done
SEGMENT_1=$BEFORE_THE_DASHES
BEFORE_THE_DASHES=
while (( "$#" )); do
if [[ "$1" = "--" ]]; then
shift
break
fi
BEFORE_THE_DASHES="$BEFORE_THE_DASHES $1"
shift
done
SEGMENT_2=$BEFORE_THE_DASHES
SEGMENT_3=$@
BUILD_ARGS=$SEGMENT_1
RUN_ARGS=$SEGMENT_2
RUN_COMMAND=$SEGMENT_3
if [ -z "$RUN_COMMAND" ]; then
RUN_COMMAND=$RUN_ARGS
RUN_ARGS=
fi
TEMP_TAG=docker-build-and-run-temp
docker rm -f $TEMP_TAG 2>/dev/null
printf "${TERM_GREEN}Building Docker container (${TERM_BLUE}docker build $BUILD_ARGS${TERM_GREEN})${TERM_NC}\n" \
&& docker build --tag $TEMP_TAG $BUILD_ARGS \
&& printf "${TERM_GREEN}Running Docker container (${TERM_BLUE}docker run $RUN_ARGS $RUN_COMMAND${TERM_GREEN})${TERM_NC}\n" \
&& docker run --rm -it $RUN_ARGS --label $TEMP_TAG $TEMP_TAG $RUN_COMMAND
}