Skip to content

Instantly share code, notes, and snippets.

@manarth
Created May 29, 2019 07:39
Show Gist options
  • Save manarth/a9e606ce28bf0ab68a127d4d4dd7bd0c to your computer and use it in GitHub Desktop.
Save manarth/a9e606ce28bf0ab68a127d4d4dd7bd0c to your computer and use it in GitHub Desktop.
docker-connect: Shortcut for connecting to a container managed by docker-compose
#!/bin/bash
# Short-cut to connect to a running docker-compose managed container.
# Instead of invoking `docker ps` to list containers, then calling
# `docker exec -it <container id> /bin/bash, simply invoke
# `docker-connect <name of service>`
if [ $# -ne 1 ]
then
printf "%s\n" "Usage: docker-connect <name of service>"
fi
# Selected service (e.g. "solr", "dev", etc).
service="$1"
# Validate that the command is invoked within a docker-compose context.
services=($(docker-compose ps --services 2>/dev/null))
if [ $? -ne 0 ]
then
printf 1>&2 "%s\n\a" "Unable to identify services. Are you in the right directory?"
exit 1
fi
#Validate that the argument is a valid service.
if [[ ! " ${services[@]} " =~ " ${service} " ]]
then
printf 1>&2 "%s\n\a" "'${service}' is not a valid service name. Options are:"
for var in "${services[@]}"
do
printf 1>&2 "%s%s\n" "- " "${var}"
done
exit 2
fi
# Look up the container ID for the service.
container=($(docker-compose ps -q ${service}))
# Check whether the container is running.
running=($(docker ps -q --no-trunc))
if [[ ! " ${running[@]} " =~ " ${container} " ]]
then
printf 1>&2 "%s\n\a" "Service '${service}' is not running. Start the container first."
exit 3
fi
docker exec -it ${container} /bin/bash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment