How to check if a process is running inside docker container

后端 未结 8 1268
逝去的感伤
逝去的感伤 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:35

    We use the proc's sched (/proc/$PID/sched) to extract the PID of the process. The process's PID inside the container will differ then it's PID on the host (a non-container system).

    For example, the output of /proc/1/sched on a container will return:

    root@33044d65037c:~# cat /proc/1/sched | head -n 1
    bash (5276, #threads: 1)
    

    While on a non-container host:

    $ cat /proc/1/sched  | head -n 1
    init (1, #threads: 1)
    

    This helps to differentiate if you are in a container or not. eg you can do:

    if [[ ! $(cat /proc/1/sched | head -n 1 | grep init) ]]; then {
        echo in docker
    } else {
        echo not in docker
    } fi
    

提交回复
热议问题