DEV Community

Tib
Tib

Posted on

Remotely connect to a running docker container

Take control

A moment ago, when using Jenkins at $work, I discovered that I could connect remotely to a running docker container.

It is VERY handy ! Thanks to it you can deeply debug what's wrong with a continuous integration run. There is even a "Pause" button (in Jenkins) that allows you to inspect a particular step or just avoid you the rush on fast runs.

And honestly, the first time I experimented, I found it a bit "magic" ! 😁

Below is a detailed explanation on how to make the magic happens 😃

Expose tcp connection on dockerd side

To be able to connect remotely, you have to start dockerd with the -H tcp://0.0.0.0:2375 option to expose the tcp socket.

Edit your docker systemd service to add a tcp socket :

dockerd -H fd:// -H tcp://0.0.0.0:2375 --containerd=/run/containerd/containerd.sock
Enter fullscreen mode Exit fullscreen mode

Reload service config:

$ systemctl daemon-reload
Enter fullscreen mode Exit fullscreen mode

And restart dockerd:

$ systemctl restart docker
Enter fullscreen mode Exit fullscreen mode

Run a sample container

I will take a small alpine and just run a "never ending script" inside:

Write a Dockerfile:

FROM alpine

COPY w.sh w.sh
CMD ["./w.sh"]
Enter fullscreen mode Exit fullscreen mode

And a while/sleep loop w.sh to maintain it alive:

#!/bin/sh

while true; do sleep 2 ; echo "alive"; done
Enter fullscreen mode Exit fullscreen mode

Build the image:

$ docker build . -t persist
Enter fullscreen mode Exit fullscreen mode

And finally, start the container:

$ docker run -itd persist
f70b46b77105700d3420b88323d07edff9146f435a13c73029efd92197ef9030
Enter fullscreen mode Exit fullscreen mode

Connect from client

Now on your laptop (for instance) you can now connect to your docker container simply like this:

$  docker -H tcp://the-url-or-ip exec -ti f70b46b77105700d3420b88323d07edff9146f435a13c73029efd92197ef9030 /bin/sh
Enter fullscreen mode Exit fullscreen mode

And you get your shell:

/ #
Enter fullscreen mode Exit fullscreen mode

Tadaaa !

Tadaaa

Top comments (0)