代碼判斷是否運行在docker環境中


屬於一個比較常見的需求,而且社區已經有了好多實現了,原理很簡單

原理說明

判斷/.dockerenv 是否存在或者是否包含cgroup

參考代碼

'use strict';
const fs = require('fs');
let isDocker;
function hasDockerEnv() {
    try {
        fs.statSync('/.dockerenv');
        return true;
    } catch (_) {
        return false;
    }
}
function hasDockerCGroup() {
    try {
        return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
    } catch (_) {
        return false;
    }
}
module.exports = () => {
    if (isDocker === undefined) {
        isDocker = hasDockerEnv() || hasDockerCGroup();
    }
    return isDocker;
};

說明

類似的方法可以移植到其他語言,而且也已經有了類似的實現了,比如golang

func (app *App) isRunningInDockerContainer() bool {
    // docker creates a .dockerenv file at the root
    // of the directory tree inside the container.
    // if this file exists then the viewer is running
    // from inside a container so return true
    if _, err := os.Stat("/.dockerenv"); err == nil {
        return true
    }
    return false
}

參考資料

https://github.com/sindresorhus/is-docker


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM