简体   繁体   English

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

[英]PHP: Get Container ID in Docker Container

How can I get the Docker container ID within the container itself using PHP?如何使用 PHP 在容器本身中获取 Docker 容器 ID?

I just found linux commands as here :我刚刚在这里找到了 linux 命令:

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

You can use get_env() to get environment variables of the system.您可以使用get_env()获取系统的环境变量。

if after running echo $DOCKER_CID in the CLI you get the ID you can then use this code in your PHP:如果在 CLI 中运行echo $DOCKER_CID后获得 ID,则可以在 PHP 中使用此代码:

$docker_cid = getenv('DOCKER_CID'); 

Everyone's answers combined means that after running the following command in the cotainer:大家的答案结合起来意味着在cotainer中运行以下命令后:

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

You are able to get the id using:您可以使用以下方法获取 ID:

$docker_cid = getenv('DOCKER_CID'); 

If you don't know how to run that command in a container, here are some options:如果您不知道如何在容器中运行该命令,这里有一些选项:

  • Run it using: docker exec -it <containerId> /bin/bash使用以下命令运行它: docker exec -it <containerId> /bin/bash
  • Make a PHP script: exec('DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)');编写一个 PHP 脚本: exec('DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)'); (I don't recommend that, but if someone uses this, make sure it's secure.) (我不建议这样做,但如果有人使用它,请确保它是安全的。)

Credits to Marcin, who already answered it, but maybe not clear enough.感谢 Marcin,他已经回答了这个问题,但可能还不够清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM