1

There is a docker php container run by docker run command.

1.How to pass by using docker run command a variable to the php container?

2.How to read value of the passed variable from php script in that container?

Context: PHP script inside a docker container connects to a database that is located on an another container. I need to run several php containers that connect to differently named database containers.

I can't have hardcoded database container name inside the php script and need to pass database conatainer name dynamically when I use docker run to startup php containers.

Jimmix
  • 5,644
  • 6
  • 44
  • 71
  • 1
    You can set environment variables - https://stackoverflow.com/questions/30494050/how-do-i-pass-environment-variables-to-docker-containers – Nigel Ren Feb 06 '19 at 17:08

2 Answers2

1

This didn't work for me on Ubuntu 22.04 with PHP 8.1, however using the same env variable in docker run:

-e DB_NAME='hostname'

and in PHP:

echo "My DB name is ".getenv('DB_NAME').".\n";

... did work correctly.

Harry
  • 154
  • 3
0

You can pass an environment variable using the -e DB_NAME='hostname' as mentioned in this answer https://stackoverflow.com/a/30494145/2940966.

The environment variable can be accessed from the PHP script as follows.

echo 'The DB Name is ' .$_ENV["DB_NAME"];
joseph
  • 940
  • 10
  • 19