How to check if a process is running inside docker container

后端 未结 8 1266
逝去的感伤
逝去的感伤 2020-11-30 23:08

[Updated1] I have a shell which will change TCP kernel parameters in some functions, but now I need to make this shell run in Docker container, that means, the shell need to

8条回答
  •  情歌与酒
    2020-11-30 23:28

    We needed to exclude processes running in containers, but instead of checking for just docker cgroups we decided to compare /proc//ns/pid to the init system at /proc/1/ns/pid. Example:

    pid=$(ps ax | grep "[r]edis-server \*:6379" | awk '{print $1}')
    if [ $(readlink "/proc/$pid/ns/pid") == $(readlink /proc/1/ns/pid) ]; then
       echo "pid $pid is the same namespace as init system"
    else
       echo "pid $pid is in a different namespace as init system"
    fi
    

    Or in our case we wanted a one liner that generates an error if the process is NOT in a container

    bash -c "test -h /proc/4129/ns/pid && test $(readlink /proc/4129/ns/pid) != $(readlink /proc/1/ns/pid)"
    

    which we can execute from another process and if the exit code is zero then the specified PID is running in a different namespace.

提交回复
热议问题