Skip to content

Instantly share code, notes, and snippets.

@paulmakepeace
Created September 24, 2020 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulmakepeace/7f7c9f1710c34e1c3d909f567fc1bbc1 to your computer and use it in GitHub Desktop.
Save paulmakepeace/7f7c9f1710c34e1c3d909f567fc1bbc1 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# DockerHelper provides methods to work with Docker containers.
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
# frozen_string_literal: true
require "spec_helper"
RSpec.describe DockerHelper do
let(:cgroup_docker) do
<<~CGROUP
3:cpuacct:/docker/deadbeef
2:cpu:/docker/acecafe8
1:cpuset:/docker/104decaf
CGROUP
end
let(:cgroup_linux) do
<<~CGROUP
3:cpu,cpuacct:/init.scope
2:devices:/init.scope
1:name=systemd:/init.scope
CGROUP
end
it "detects running on Docker" do
# /proc/1/cgroup contains Docker strings
allow(File).to receive(:read).and_return(cgroup_docker)
expect(DockerHelper.running_in_docker?).to eq(true)
end
it "detects not running on Docker (Linux)" do
# /proc/1/cgroup contains non-Docker strings
allow(File).to receive(:read).and_return(cgroup_linux)
expect(DockerHelper.running_in_docker?).to eq(false)
end
it "detects not running on Docker (macOS)" do
# /proc/1/cgroup doesn't exist
allow(File).to receive(:read).and_raise(Errno::ENOENT)
expect(DockerHelper.running_in_docker?).to eq(false)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment