Skip to content

fix: Add container detection for other container runtimes #5835

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/lib/is-docker.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const fs = require('fs');

export function isDocker(): boolean {
return hasDockerEnv() || hasDockerCGroup();
return hasDockerEnv() || hasContainerEnv() || hasDockerCGroup();
}

function hasDockerEnv() {
try {
fs.statSync('/.dockerenv');
Expand All @@ -12,6 +13,15 @@ function hasDockerEnv() {
}
}

function hasContainerEnv() {
try {
fs.statSync('/run/.containerenv');
return true;
} catch (_) {
return false;
}
}

function hasDockerCGroup() {
try {
return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
Expand Down
19 changes: 19 additions & 0 deletions test/jest/unit/is-docker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,25 @@ describe('isDocker', () => {
expect(statSyncSpy).toHaveBeenLastCalledWith('/.dockerenv');
});

it('inside other containers (.containerenv test)', async () => {
delete require.cache[path.join(__dirname, 'index.js')];
const statSyncSpy = jest.spyOn(fs, 'statSync');

statSyncSpy.mockImplementationOnce((path): any => {
if (path === '/.dockerenv') {
throw new Error("ENOENT, no such file or directory '/.dockerinit'");
}

if (path === '/run/.containerenv') {
return {} as any
}
});
expect(isDocker()).toBeTruthy();
expect(statSyncSpy).toHaveBeenCalledTimes(2);
expect(statSyncSpy).toHaveBeenLastCalledWith('/run/.containerenv');
});


it('inside a Docker container (cgroup test)', async () => {
delete require.cache[path.join(__dirname, 'index.js')];

Expand Down