Created
September 19, 2023 21:48
-
-
Save legovaer/f3f6441f985e0d85040829aae02e2eb9 to your computer and use it in GitHub Desktop.
Bash script to run docker exec in a docker swarm environment
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
#!/bin/bash | |
set -e | |
SERVICE_NAME=$1; shift | |
DOCKER_CMD=docker | |
TASK_ID=$(${DOCKER_CMD} service ps --filter 'desired-state=running' $SERVICE_NAME -q) | |
NODE_ID=$(${DOCKER_CMD} inspect --format '{{ .NodeID }}' $TASK_ID) | |
CONTAINER_ID=$(${DOCKER_CMD} inspect --format '{{ .Status.ContainerStatus.ContainerID }}' $TASK_ID) | |
TASK_NAME=swarm_exec_${RANDOM} | |
TASK_ID=$(${DOCKER_CMD} service create \ | |
--detach \ | |
--name=${TASK_NAME} \ | |
--restart-condition=none \ | |
--mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \ | |
--constraint node.id==${NODE_ID} \ | |
dockreg.biswb.com:5000/docker:060722 docker exec ${CONTAINER_ID} "$@") | |
while : ; do | |
STOPPED_TASK=$(${DOCKER_CMD} service ps --filter 'desired-state=shutdown' ${TASK_ID} -q) | |
[[ ${STOPPED_TASK} != "" ]] && break | |
sleep 1 | |
done | |
${DOCKER_CMD} service logs --raw ${TASK_ID} | |
${DOCKER_CMD} service rm ${TASK_ID} > /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment