LoginSignup
5
4

More than 3 years have passed since last update.

docker-compose.ymlとDockerコンテナのPHPで環境変数を使用する

Last updated at Posted at 2019-05-12

はじめに

これは個人的な備忘録になります。

docker-compose.ymlで環境変数を使用する

docker-compose.ymlがあるディレクトリ直下に、「.env」 を用意する。そのファイル内で定義した値を使用できる。

例えば、以下のように定義をした場合

.env
# REDIS関係
REDIS_PORT=6379
REDIS_PASSWORD=password

docker-compose.ymlでは、以下のように使用できる

docker-compose.yml
  redis:
    image: redis:alpine3.9
    command: redis-server --requirepass ${REDIS_PASSWORD}
    ports:
      - "${REDIS_PORT}:${REDIS_PORT}"

dockerコンテナで環境変数を使用する

dockerコンテナ内で環境変数を使用する場合は、docker-compose.ymlで定義する。

環境変数を1個〜2個指定する場合は、「environment」で定義をする。
以下のファイルでは、DATABASE_HOST/REDIS_HOSTを定義している。

docker-compose.yml
  app:
    build: ./app
    env_file: .env
    environment:
      DATABASE_HOST: db
      REDIS_HOST: redis
    depends_on:
      - db
      - redis
    volumes:
      - ./data/html:/var/www/html

また、複数指定したい場合は、「env_file」として、環境変数を記載しているファイルを指定する。

この時に、「.env」ファイルを使い回すことで、環境変数を「.env」ファイルに集約ができる。

PHPのコンテナでPHP.iniで注意点

PHP.iniでは、環境変数を使う、使わない、または有効にする変数の優先順位設定があります。

それが「variables_order」になります。デフォルトでは、「GPCS」となっていますので、環境変数は使えないです。

Dockerの環境変数が読み込めなくてハマりました。
「EGPCS」にすると、環境変数を優先して使ってくれます。

php.ini
; This directive determines which super global arrays are registered when PHP
; starts up. G,P,C,E & S are abbreviations for the following respective super
; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty
; paid for the registration of these arrays and because ENV is not as commonly
; used as the others, ENV is not recommended on productions servers. You
; can still get access to the environment variables through getenv() should you
; need to.
; Default Value: "EGPCS"
; Development Value: "GPCS"
; Production Value: "GPCS";
; http://php.net/variables-order
variables_order = "GPCS"

これでPHPのコード内で環境変数を使えるようになります。

$redis = new Redis();
$redis->connect($_ENV['REDIS_HOST'], $_ENV['REDIS_PORT']);

コードだけではなくて、PHP.iniの中でも環境変数は使えるようです。

php.ini
memory_limit=${PHP_MEMORY_LIMIT}

参考文献

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4