How to docker exec -ti CONTAINER_NAME /bin/bash on deployed docker stack?
The other answers failed, because they no not extract the container it from the task. Swarm wraps a task object around a container:
taskid=$(docker service ps -q ${servicename} |head -1) containerid=$(docker inspect -f '{{.Status.ContainerStatus.ContainerID}}' ${taskid}) docker exec -it ${containerid} "$*"
Of course, this will only take the first container in the list.
Here is an example on my local macOS.
$ docker stack lsNAME SERVICESgospot_web 1$ docker service lsID NAME MODE REPLICAS IMAGE PORTSqigx492p2lbe gospot_web_web global 1/1 gospot/gospot-web:0.1.20.g225306b *:80->80/tcp, *:443->443/tcp
You can use either container id or container name to access the container.
$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESb3824a85d3c8 gospot/gospot-web:0.1.20.g225306b "nginx -g 'daemon of…" 2 hours ago Up 2 hours (healthy) 80/tcp, 443/tcp gospot_web_web.3cqcd1v22vaon517j7p5h1d9a.wrel676fcllssrm3151ymkse9$ docker exec -it b3824a85d3c8 sh/ # lsbin etc lib mnt root sbin sys usrdev home media proc run srv tmp var/ #$ docker exec -it gospot_web_web.3cqcd1v22vaon517j7p5h1d9a.wrel676fcllssrm3151ymkse9 sh/ # lsbin dev etc home lib media mnt proc root run sbin srv sys tmp usr var/ #
If the target service name is unique enough, you can use the following one-liner.
$ docker exec -it $(docker ps | grep gospot_web_web | awk '{print $1}') sh/ # lsbin etc lib mnt root sbin sys usrdev home media proc run srv tmp var/ #
Hope this helps.
You can use below command and replace SERVICE_NAME with your service name:
docker exec -it \ $(docker stack ps pipeline| grep SERVICE_NAME | cut -d' ' -f1) /bin/bash
this command finds the container id of your service:
docker stack ps pipeline| grep SERVICE_NAME | cut -d' ' -f1