How to determine if a process runs inside lxc/Docker?

后端 未结 16 1309
情歌与酒
情歌与酒 2020-11-28 18:15

Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a v

相关标签:
16条回答
  • 2020-11-28 19:11

    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.

    0 讨论(0)
  • 2020-11-28 19:12

    On a new ubuntu 16.04 system, new systemd & lxc 2.0

    sudo grep -qa container=lxc /proc/1/environ
    
    0 讨论(0)
  • 2020-11-28 19:12

    Here's a solution in Ruby,

    # Usage: DockerHelper.running_in_docker?
    module DockerHelper
      extend self
    
      def running_in_docker?
        !!(File.read("/proc/1/cgroup") =~ %r[^\d+:\w+:/docker/]) # !! => true/false
      rescue Errno::ENOENT
        false
      end
    end
    

    If you like tests with your code, here's a spec in the gist.

    0 讨论(0)
  • 2020-11-28 19:13

    This is an old question, but a REALLY good one. :)

    I've written some automation scripts that we run on baremetal, VM and in a docker container, with logic branching based on which platform the script is executing on. In my case I have the privilege of creating both the container and the docker image, so this solution will only work if you are in control of the entire stack:

    Snippet of Dockerfile:

    FROM ubuntu:18.04
    
    ENV PLATFORM="docker"
    
    RUN apt update; \
    ...
    

    The script can then just check the value of $PLATFORM for desired outcomes on each platform:

    #!/bin/bash
    
    # Check for executor specification in environment
    case $PLATFORM in
      docker)
        # If running in Docker, do this stuff
        echo "Running containerized, proceeding..."
        ;;
      virtual)
        # If running in a VM, do different stuff
        echo "Running on a VM, loading VM stuff..."
        modprobe some-kernel-module
        ;;
      *)
        echo "Unknown executor specified! Exiting..."
        exit 1
        ;;
    esac
    

    I've omitted baremetal in the above code to keep it concise.

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