Search code examples
dockerdocker-swarmdocker-exec

Access container from service on other node in Docker Swarm


I have Docker running in swarm mode, and created a service that runs one container. The service my-service runs on node1 (Manager node), and the container my-container is spawned on node2

From node1, how can I make a docker exec on the my-container running on node2 ?


Solution

  • I found this project, skopos-plugin-swarm-exec, that solves my issue.

    It can be used like this:

    docker run -v /var/run/docker.sock:/var/run/docker.sock datagridsys/skopos-plugin-swarm-exec task-exec --image <task id> <command>
    

    How It Works (Internals)
    Starting from a task ID and a command to execute, here are the steps that are taken:

    • Obtain the node ID on which the target task is running, as well as the container ID of the task on that node
    • Create a temporary service, using the same container image, and a scheduling constraint that places the task of the temporary service on the same node where the target task is
    • Execute the equivalent of a docker exec command using the node-local Docker engine API
    • Upon completion of the command, terminate the temporary service, propagating the exit code of the executed command
    • Upon termination of the temporary service, extract the exit code and return it