How to detect if the current script is running in a docker build?

Viewed 785

Suppose I have a Dockerfile which runs a script,

RUN ./myscript.sh

How could I write the myscript.sh so that it could detect if itself is launched by the RUN command during a docker build?

#! /bin/bash

# myscript.sh

if <What should I do here?>
then
  echo "I am in a docker build"
else
  echo "I am not in a docker build"
fi

Ideally, it should not require any changes in the Dockerfile, so that the caller of myscript.sh does not need specialized knowledge about myscript.sh.

3 Answers

Try this :

#!/bin/bash

# myscript.sh

isDocker(){
    local cgroup=/proc/1/cgroup
    test -f $cgroup && [[ "$(<$cgroup)" = *:cpuset:/docker/* ]]
}

isDockerBuildkit(){
    local cgroup=/proc/1/cgroup
    test -f $cgroup && [[ "$(<$cgroup)" = *:cpuset:/docker/buildkit/* ]]
}

isDockerContainer(){
    [ -e /.dockerenv ]
}

if isDockerBuildkit || (isDocker && ! isDockerContainer)
then
  echo "I am in a docker build"
else
  echo "I am not in a docker build"
fi

Just to chime in on this, it seems I cannot comment (nor edit as the edit is two characters long... not enough for SO) on the accepted answer but it contains a typo.

the isDockerContainer should read

isDockerContainer(){
    [ -e /.dockerenv ]
}

which created a silent bug in our case.

Cheers

In your Dockerfile, you can try this to run the script

ADD myscript.sh .

RUN chmod +x myscript.sh

ENTRYPOINT ["myscript.sh"]
Related