skip to Main Content

How can a script detect whether it is running inside a container?

#!/bin/sh
if [ ... ]; then                 # ?
  echo 'running in container'
else
  echo 'running on host'
fi

2

Answers


  1. Chosen as BEST ANSWER

    The /.dockerenv file always exists in a docker container, so I check that:

    #!/bin/sh
    if [ -f /.dockerenv ]; then
      echo 'running in container'
    else
      echo 'running on host'
    fi
    

    But note that file is an artefact of an older docker design, and could be removed in a future docker version. So this is a workaround, rather than a solution.


  2. This is one way with bash :

    #!/bin/bash
    
    in_docker(){
        local cgroup=/proc/self/cgroup
        test -f $cgroup && [[ "$(<$cgroup)" = *:cpuset:/docker/* ]]
    }
    
    if in_docker; then
      echo 'running in container'
    else
      echo 'running on host'
    fi
    

    You need to convert to sh syntax if you don’t have bash in your container.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search