简体   繁体   中英

how get env variables from docker in symfony yml config file

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

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

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"]

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.

In your app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: 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']);

There now (as of Symfony 3.2) is a syntax to do this in yaml files:

# app/config/parameters.yml
parameters:
    database_host: '%env(DATABASE_HOST)%'

see http://symfony.com/doc/current/configuration/external_parameters.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM