How to check if a process is running inside docker container

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

    What works for me is to check for the inode number of the '/.' Inside the docker, its a very high number. Outside the docker, its a very low number like '2'. I reckon this approach would also depend on the FileSystem being used.

    Example

    Inside the docker:

    # ls -ali / | sed '2!d' |awk {'print $1'}
    1565265
    

    Outside the docker

    $ ls -ali / | sed '2!d' |awk {'print $1'}
    2
    

    In a script:

    #!/bin/bash
    INODE_NUM=`ls -ali / | sed '2!d' |awk {'print $1'}`
    if [ $INODE_NUM == '2' ];
    then
            echo "Outside the docker"
    else
            echo "Inside the docker"
    fi
    
    0 讨论(0)
  • 2020-11-30 23:40

    Thomas' solution as code:

    running_in_docker() {
      (awk -F/ '$2 == "docker"' /proc/self/cgroup | read non_empty_input)
    }
    

    Note

    The read with a dummy variable is a simple idiom for Does this produce any output?. It's a compact method for turning a possibly verbose grep or awk into a test of a pattern.

    Additional note on read

    0 讨论(0)
提交回复
热议问题