Sharing process namespace (PID) between containers managed by docker-compose

Sharing process namespace (PID) between docker containers managed by docker-compose

Every time I want to do non-standard things in docker I struggle a lot. Usually doing something not obvious but not impossible requires lots of Googling, reading the documentation and digging into Github repositories. This time wasn’t any different.

Use case & problem

My docker-compose file contains definition of service that uses a docker image provided by a third party company – let say this is externally developed application to be deployed on-premises. We do not control what’s inside the image.

The problem is that, by definition, I don’t trust this image. I would like to, as a first resort, monitor all processes that are spawned inside that container. Fortunately, docker provides --pid option that allows us to bind to the process (PID) namespace of other container: documented here

That’s a great feature, even docker-compose supports pid field to be set on the service.

Unfortunatelly, it turned out that below solution doesn’t work as pid field value refer to container that doesn’t exists yet – it will be created, but validation happens first :

version: '3.7'
services:
  third-party-provider-service:
    image: "ubuntu"
    entrypoint: tail -f /dev/null
  monitoring:
    pid: "container:third-party-provider-service"
    image: "ubuntu"
    entrypoint: tail -f /dev/null

Solution

Let the code speak itself:

version: '3.7'
services:
  third-party-provider-service:
    image: "ubuntu"
    entrypoint: tail -f /dev/null
  monitoring:
    pid: "service:third-party-provider-service"
    image: "ubuntu"
    entrypoint: tail -f /dev/null

Did you spot the difference? Just replace container with service. I know, I could guess that… I spend a couple of hours trying to pinpoint down what happens, why the first version doesn’t work.

After applying docker-compose up on the above definition, I could see all processes spawned inside third-party-provider-service container while still being in bash session in monitoring:

home:test ajedro$ docker exec -it test_monitoring_1 /bin/bash
root@07bc0df89020:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0   4564   772 ?        Ss   20:48   0:00 tail -f /dev/null
root         7  0.0  0.0   4564   768 ?        Ss   20:48   0:00 tail -f /dev/null
root        12  0.0  0.0  18504  3416 pts/0    Ss+  20:48   0:00 /bin/bash
root        23  1.5  0.0  18504  3436 pts/1    Ss   21:28   0:00 /bin/bash
root        33  0.0  0.0  34396  2780 pts/1    R+   21:28   0:00 ps aux

It turned out that support for service namespace was added in this PR and is not yet documented (at the time of writing) here. And of course, this is how you collect contributions 🙂

Leave a Reply