PHP:在Docker容器中获取容器ID

时间:2019-02-05 09:55:59

标签: php docker containers php-7.2

如何使用PHP在容器本身中获取Docker容器ID?

我刚刚发现Linux命令为here

DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)

2 个答案:

答案 0 :(得分:3)

您可以使用{ "name": "biolerplate", "version": "1.0.0", "description": "a boilerplate for react, redux, & express", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "build-watch": "npm run build -- -w -d", "start": "node server/index.js", "start-watch": "nodemon server/index.js --watch server --watch db", "dev": "cross-env NODE_ENV=development concurrently --kill-others --prefix \"[{name}]\" --names \"BUILD,SERVE\" -c \"bgBlack.bold.green,bgBlack.bold.red\" \"npm run build-watch\" \"npm run start-watch\"" }, "author": "", "license": "ISC", "dependencies": { "@material-ui/core": "^3.9.2", "axios": "^0.16.2", "bcryptjs": "^2.4.3", "body-parser": "^1.17.1", "connect-session-sequelize": "^4.1.0", "express": "^4.15.2", "express-session": "^1.15.3", "immutable": "^4.0.0-rc.12", "nodemon": "^1.11.0", "passport": "^0.3.2", "passport-google-oauth2": "^0.1.6", "pg": "^6.2.4", "pg-hstore": "^2.3.2", "react": "^15.5.4", "react-dom": "^15.5.4", "react-helmet": "^5.2.0", "react-redux": "^5.0.4", "react-router": "^4.1.1", "react-router-dom": "^4.1.1", "react-select": "^2.3.0", "redux": "^3.6.0", "redux-logger": "^3.0.1", "redux-thunk": "^2.2.0", "reselect": "^4.0.0", "sequelize": "^4.4.0", "styled-components": "^4.1.3", "volleyball": "^1.4.1", "webpack-livereload-plugin": "^0.11.0" }, "devDependencies": { "babel-core": "^6.24.1", "babel-loader": "^7.0.0", "babel-plugin-styled-components": "^1.10.0", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-1": "^6.24.1", "concurrently": "^3.4.0", "cross-env": "^5.0.1", "css-loader": "^0.28.0", "eslint": "^5.13.0", "eslint-config-airbnb": "^17.1.0", "eslint-config-airbnb-base": "^13.1.0", "eslint-config-prettier": "^4.0.0", "eslint-import-resolver-webpack": "^0.11.0", "eslint-plugin-import": "^2.16.0", "eslint-plugin-jsx-a11y": "^6.2.1", "eslint-plugin-prettier": "^3.0.1", "eslint-plugin-react": "^7.12.4", "node-sass": "^4.5.2", "redux-devtools-extension": "^2.13.0", "sass-loader": "^6.0.3", "style-loader": "^0.16.1", "webpack": "^2.4.1" } } 来获取系统的环境变量。

如果在CLI中运行get_env()之后,您获得了ID,然后可以在PHP中使用此代码:

echo $DOCKER_CID

答案 1 :(得分:1)

每个人的答案加在一起意味着在容器中运行以下命令后:

DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)

您可以使用以下方法获取ID:

$docker_cid = getenv('DOCKER_CID'); 

如果您不知道如何在容器中运行该命令,可以使用以下选项:

  • 使用以下命令运行它:docker exec -it <containerId> /bin/bash
  • 制作一个PHP脚本:exec('DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)');(我不建议这样做,但是如果有人使用它,请确保它是安全的。)

感谢已经回答了问题的Marcin,但可能还不够清楚。