During the Dockerfile's development, and later it's deployment, the need for debugging might arise. Sometimes it would be nice to have a possibility to attach to a newly deployed, running container, to do the troubleshooting, in case if something inside of a container happened unexpected. 

First, check what Docker version you are using, because, since version >=0.9 the attach procedure has changed - the use of lxc-attach app won't work, because of dropped LXC's userland tools. Instead, for the later Docker's there is a dedicated tool called nsenter, which is shipped by the util-linux (ver. >=2.24) package.

Using nsenter to attach to a running Docker container is a quite simple task.
1) Find the PID of the first process of a running container.

1.1) Get container's ID - example:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED         STATUS   (...)         
1b3e4917343c     container:latest       /run.sh             1 days ago     Up 1 days   

1.2) Export PID env variable for later usage, which will contain the 1st PID from the container (note: PID number "1" in the container itself but from the outside of a container this will be probably a quite high, positive value...):

$ PID=$(docker inspect --format '{{.State.Pid}}' 1b3e4917343c)
$ echo $PID

2) Execute nsenter to attach to a container:

$ nsenter --mount --uts --ipc --net --pid --target $PID
-bash-4.2# ps aux
root         1  0.0  0.8 110664  4276 ?        Ss   Oct02   0:00 nginx: master process nginx
nginx      490  0.0  0.6 111112  3300 ?        S    Oct02   0:00 nginx: worker process
root       604  0.0  0.4  15176  2032 ?        S    02:13   0:00 -bash
root       620  0.0  0.2  23184  1368 ?        R+   02:14   0:00 ps aux


Currently unrated


There are currently no comments

New Comment


required (not published)