如何在 symfony yml 配置文件中从 docker 获取环境变量

2021-12-26 00:00:00 docker docker-compose php mysql symfony

在 docker-compose.yml 中:

in docker-compose.yml:

mysql:
  image: mysql:latest
  container_name: mysql
  environment:
    - MYSQL_ROOT_PASSWORD=root
    - MYSQL_DATABASE=symfony
    - MYSQL_USER=symfony
    - MYSQL_PASSWORD=symfony

如何在 yml 配置文件中获取此变量:

how i can get this variables in yml config file:

parameters:
    database_host: 172.17.42.4
    database_port: 3306
    database_name: symfony
    database_user: symfony
    database_password: symfony

在 $_SERVER 中,它们的获取方式如下:

in $_SERVER they are fetch like:

$_SERVER["SYMFONY_MYSQL_ENV_MYSQL_DATABASE"],
$_SERVER["SYMFONY_MYSQL_PORT_3306_TCP_ADDR"],
$_SERVER["SYMFONY_MYSQL_ENV_MYSQL_PASSWORD"],
$_SERVER["SYMFONY_MYSQL_ENV_MYSQL_USER"]

推荐答案

在 symfony 中,你可以在 yaml 配置中包含 PHP 文件,你可以在运行时设置参数,覆盖来自 parameters.yml 的静态参数值.

In symfony, you can include PHP files in yaml configuration, where you can set parameters in runtime overriding the static parameter values from parameters.yml.

在你的 app/config/config.yml

In your app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: parameters.php }

然后使用以下内容创建文件 app/config/parameters.php

Then create the file app/config/parameters.php with the following content

<?php
// app/config/parameters.php

$container->setParameter('database_name', $_SERVER['SYMFONY_MYSQL_ENV_MYSQL_DATABASE']);
$container->setParameter('database_host', $_SERVER['SYMFONY_MYSQL_PORT_3306_TCP_ADDR']);
$container->setParameter('database_user', $_SERVER['SYMFONY_MYSQL_ENV_MYSQL_USER']);
$container->setParameter('database_password', $_SERVER['SYMFONY_MYSQL_ENV_MYSQL_PASSWORD']);

相关文章