Environment variable in PHP-docker container

人盡茶涼 提交于 2019-12-05 02:48:33

问题


I want to show an env var in my docker container. The PHP script looks like this:

<html>
 <head>
  <title>Show Use of environment variables</title>
 </head>
 <body>
  <?php
  print "env is: ".$_ENV["USER"]."\n";
  ?>
 </body>
</html>

I use OpenShift to start the container. The PHP - container shows:

env is: 

Now I change the dc config of my container:

oc env dc/envar USER=Pieter
deploymentconfig "envar" updated

When I access the container. The env var of USER is Pieter

docker exec -it 44a0f446ae36 bash
bash-4.2$ echo $USER
Pieter

But my script remains showing: "env is:" It does not fill in the variable.


回答1:


Change

print "env is: ".$_ENV["USER"]."\n";

to

print "env is: ".getenv("USER")."\n";

.

/# cat test.php
<html>
 <head>
  <title>Show Use of environment variables</title>
 </head>
 <body>
  <?php
  print "env via \$_ENV is: ".$_ENV["USER"]."\n";
  print "env via getenv is: ".getenv("USER")."\n";
  ?>
 </body>
</html>
/ #
/ # export USER=Sascha
/ # echo $USER
Sascha
/ # php test.php 
<html>
 <head>
  <title>Show Use of environment variables</title>
 </head>
 <body>
  PHP Notice:  Array to string conversion in /test.php on line 7
PHP Notice:  Undefined index: USER in /test.php on line 7
env via $_ENV is: 
env via getenv is: Sascha
 </body>
</html>
/ # 



回答2:


I did the following to solve this issue:

  1. Use this command that writes the environment variables to a file called .env in your project folder.

    CMD ["env >> /path/to/project/.env"]
    
  2. Install dotenv package that loads the env variables from a file to $_ENV

    composer require vlucas/phpdotenv
    
  3. Load the package and use it as

    require 'vendor/autoload.php'
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    getenv('VAR_NAME');
    

Hope it helps.



来源:https://stackoverflow.com/questions/35479304/environment-variable-in-php-docker-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!