1. 程式人生 > 實用技巧 >程式碼判斷是否執行在docker環境中

程式碼判斷是否執行在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