Skip to content

Instantly share code, notes, and snippets.

@cypx
Created March 1, 2018 15:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cypx/a2b4765fc1ccb497c99f77c78d0d4933 to your computer and use it in GitHub Desktop.
Save cypx/a2b4765fc1ccb497c99f77c78d0d4933 to your computer and use it in GitHub Desktop.
Docker command wrapper to add ability to use "docker service exec <SERVICE_NAME> <CMD>" for executing a task on a Docker service
#!/bin/bash
# add ability to use "docker service exec <SERVICE_NAME> <CMD>" for executing a task on a Docker service
# to use this script you need to expose Docker API over TCP on all nodes of you swarm cluster
declare -A NODE_IPS
# here list all nodes of you cluster
NODE_IPS[<NODE01_NAME>]="<NODE01_IP>"
NODE_IPS[<NODE02_NAME>]="<NODE02_IP>"
NODE_IPS[<NODE03_NAME>]="<NODE03_IP>"
lsof -ti:12375 | xargs kill -9
# here give a way to connect to one manager node
ssh <SSH_USER>@<MANAGER_NODE_IP> -fN -L 12375:localhost:12375
if [[ $1 == "service" && $2 == "exec" ]]; then
# find a node running the task
SERVICE_INFO=($(docker -H 127.0.0.1:12375 service ps $3 --filter "desired-state=running" --format "{{.Node}} {{.ID}}" --no-trunc | head -1))
ID_CONTAINER=$(docker -H 127.0.0.1:12375 inspect ${SERVICE_INFO[1]} --format '{{.Status.ContainerStatus.ContainerID}}')
NODE_IP=${NODE_IPS[${SERVICE_INFO[0]}]}
# connect to a node running task
lsof -ti:12376 | xargs kill -9
ssh <SSH_USER>@$NODE_IP -fN -L 12376:localhost:12375
docker -H 127.0.0.1:12376 exec -it $ID_CONTAINER ${@:4}
else
docker -H 127.0.0.1:12375 "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment