使用环境变量从运行在Docker容器上的php YII应用程序连接到RDS mysql数据库

f5emj3cl  于 2022-11-09  发布在  Docker
关注(0)|答案(1)|浏览(192)

我正在运行一些docker容器上的aws ecs,所有运行在php Yii应用程序。
应用程序需要连接到AWS RDS数据库。目前,数据库名称、主机、用户名和密码硬编码在文件“main-local.php”中

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=dbinstancename.xxxxx.region.rds.amazonaws.com;dbname=xxxxxxx',
        'username' => 'xxxxxxxx',
        'password' => 'xxxxxxxx',
        'charset' => 'utf8',
    ],

我知道在Docker容器中硬编码数据库细节不是最佳做法。我可以在运行时将环境变量传递到Docker中,例如“DB_HOST”、“DB_NAME”、“DB_USER”、“DB_PASSWORD”具有相应的值。我可以在Docker容器中键入命令“env”看到相同的细节。
如何在main-local.php中使用它?我们可以直接用env变量替换代码中的db细节吗?这是开发人员端要做的事情吗?

ztigrdn8

ztigrdn81#

要添加env支持,您可以使用此扩展名https://github.com/vlucas/phpdotenv
只需安装即可

composer.phar require vlucas/phpdotenv

创建.env文件。该文件应该在.gitignore中,并且不能从Web访问。如果您使用基本或高级模板,请将其与yii.bat一起放入项目根目录中。您也可以使用空变量创建.env.example

YII_DEBUG=1
YII_TRACE_LEVEL=3
YII_ENV=dev

然后将其添加到index.php中,如下所示

require_once __DIR__ . '/protected/vendor/autoload.php';

$factory = new Dotenv\Environment\DotenvFactory([
    new Dotenv\Environment\Adapter\EnvConstAdapter(),
]);
// Specify path to directory with .env file here (for advanced you should up twice)
\Dotenv\Dotenv::create(__DIR__ . DIRECTORY_SEPARATOR . '/../', null, $factory)->load();

defined('YII_DEBUG') or define('YII_DEBUG', (bool) $_ENV['YII_DEBUG']);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $_ENV['YII_TRACE_LEVEL']);
defined('YII_ENV') or define('YII_ENV', $_ENV['YII_ENV']);

我建议只使用EnvConstAdapter。导致$_SERVER变量被记录,并且getenv()有时在并发请求中具有空值。
boolnull和空字符串进行了小改进在$factory示例化之前添加此内容,并使用env()而不是$_ENV

if (!function_exists('env')) {
    /**
     * Gets the value of an environment variable.
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    function env($key, $default = null)
    {
        if (!isset($_ENV[$key])) {
            return $default;
        }

        $value = $_ENV[$key];

        switch ($value) {
            case 'true':
            case '(true)':
                return true;
            case 'false':
            case '(false)':
                return false;
            case 'empty':
            case '(empty)':
                return '';
            case 'null':
            case '(null)':
                return null;
            default:
                return $value;
        }
    }
}

相关问题