PHP docker容器中的环境变量

PHP docker容器中的环境变量,php,docker,environment-variables,openshift,openshift-origin,Php,Docker,Environment Variables,Openshift,Openshift Origin,我想在docker容器中显示一个环境变量。 PHP脚本如下所示: <html> <head> <title>Show Use of environment variables</title> </head> <body> <?php print "env is: ".$_ENV["USER"]."\n"; ?> </body> </html> 现在我更改容器的dc

我想在docker容器中显示一个环境变量。 PHP脚本如下所示:

<html>
 <head>
  <title>Show Use of environment variables</title>
 </head>
 <body>
  <?php
  print "env is: ".$_ENV["USER"]."\n";
  ?>
 </body>
</html>
现在我更改容器的dc配置:

oc env dc/envar USER=Pieter
deploymentconfig "envar" updated
当我进入容器时。用户的环境变量是Pieter

docker exec -it 44a0f446ae36 bash
bash-4.2$ echo $USER
Pieter
但是我的脚本仍然显示:“
env is:
”它没有填充变量。

更改

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

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>
    <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>
php 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>
    <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>

显示环境变量的使用
PHP注意:第7行/test.PHP中的数组到字符串转换
PHP注意:未定义索引:第7行/test.PHP中的用户
通过$\u环境的环境是:
通过getenv的环境是:Sascha

为了解决这个问题,我做了以下工作:

  • 使用此命令将环境变量写入项目文件夹中名为.env的文件

    CMD ["env >> /path/to/project/.env"]
    
  • 安装dotenv包,将环境变量从文件加载到$\u env

    composer require vlucas/phpdotenv
    
  • 加载包并将其用作

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

  • 希望有帮助。

    你只需要使用不同的引号,这对我很有用

    
    显示环境变量的使用
    
    日志显示了什么?有人找到解决方案了吗?为我工作。这就是我一直在寻找的答案!请进一步解释——你指的是什么“不同的引用”
    $\u ENV[“用户”]
    $\u ENV[“用户”]
    应执行完全相同的结果。如果没有,请打开一个错误报告他使用打印“env is:”.$\u env[“USER”]。“\n”。索引应该是单引号,而不是双引号。我在我的电脑上测试了它,它工作正常。你为什么认为使用单引号或双引号有什么区别?您确定您的代码在使用双引号时不起作用吗?那么请提交一份错误报告
    require 'vendor/autoload.php'
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    getenv('VAR_NAME');