Created
April 27, 2019 11:46
-
-
Save seeekr/d2b57b11ac0bb368fc2777d52ec95742 to your computer and use it in GitHub Desktop.
`docker exec -it` equivalent in multi-node Docker Swarm context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
docker_containerinfo() { | |
local taskid=$(docker service ps -f desired-state=running -q $1) | |
[[ -n "$taskid" ]] || { echo "no running task for service $1" >&2; return 1; } | |
local containerinfo=($(docker inspect --format '{{.NodeID}} {{.Status.ContainerStatus.ContainerID}}' $taskid)) | |
local host=$(docker node ls -f id="${containerinfo[0]}" --format '{{.Hostname}}') | |
echo "$host ${containerinfo[1]}" | |
} | |
docker_exec() { | |
svc=$1 | |
shift | |
info=$(docker_containerinfo $svc) | |
(( $? == 0 )) || { return 1; } | |
local containerinfo=($info) | |
local host="${containerinfo[0]}" | |
if [[ "$host" == $(hostname) ]] || [[ "$host" == "docker-desktop" ]]; then | |
hostflag="" | |
else | |
hostflag="-H ssh://$host" | |
fi | |
if [[ -n "$PS1" ]]; then | |
iflag="i" | |
else | |
iflag="" | |
fi | |
docker $hostflag exec -${iflag}t ${containerinfo[1]} "$@" | |
return $? | |
} | |
# usage: | |
# source docker_exec.sh | |
# docker_exec <service_name> <command> <args...> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment