2

How can I get the Docker container ID within the container itself using PHP?

I just found linux commands as here:

DOCKER_CID=$(cat /proc/1/cpuset | cut -c9-)
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
WeSee
  • 3,158
  • 2
  • 30
  • 58

2 Answers2

6

You can use get_env() to get environment variables of the system.

if after running echo $DOCKER_CID in the CLI you get the ID you can then use this code in your PHP:

$docker_cid = getenv('DOCKER_CID'); 
Marcin
  • 1,488
  • 1
  • 13
  • 27
1

Everyone's answers combined means that after running the following command in the cotainer:

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

You are able to get the id using:

$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
  • Make a PHP script: 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.

ALZlper
  • 61
  • 1
  • 9