Passing Laravel .env variable to Dockerfile

Viewed 6085

I have code in my Dockerfile that install NewRelic php client

RUN \
  curl -L https://download.newrelic.com/php_agent/release/newrelic-php5-8.3.0.226-linux.tar.gz | tar -C /tmp -zx && \
    NR_INSTALL_USE_CP_NOT_LN=1 NR_INSTALL_SILENT=1 /tmp/newrelic-php5-*/newrelic-install install && \
      rm -rf /tmp/newrelic-php5-* /tmp/nrinstall* && \
        sed -i -e 's/"REPLACE_WITH_REAL_KEY"/"${MY_NEWRELIC_KEY}"/' \
     -e 's/newrelic.appname = "PHP Application"/newrelic.appname = "MyApp"/' \
         /usr/local/etc/php/conf.d/newrelic.ini

How to pass variable MY_NEWRELIC_KEY that defined in Laravel .env file to DockerFile?

1 Answers

You need to define ARG and ENV values. ARG are also known as build-time variables. They are only available from the moment they are 'announced' in the Dockerfile with an ARG instruction up to the moment when the image is built. ENV variables are also available during the build, as soon as you introduce them with an ENV instruction. Here is a Dockerfile example, both for default values and without them:

ARG some_variable
# or with a hard-coded default:
#ARG some_variable=default_value

RUN echo "Oh dang look at that $some_variable"

When building a Docker image from the commandline, you can set ARG values using –build-arg:

$ docker build --build-arg some_variable=a_value

Running that command, with the above Dockerfile, will result in the following line being printed (among others):

Oh dang look at that a_value

Here is a basic Dockerfile, using hard-coded ENV default values:

# no default value
ENV blablabla
# a default value
ENV foo /bar
# or ENV foo=/bar

# ENV values can be used during the build
ADD . $foo
# or ADD . ${foo}
# translates to: ADD . /bar

And here is an example of a Dockerfile, using dynamic on-build env values:

# expect a build-time variable
ARG A_VARIABLE
# use the value to set the ENV var default
ENV an_env_var=$A_VARIABLE
# if not overridden, that value of an_env_var will be available to your containers!

If you use docker-compose you may set it in the file (link): version: '3'

services:
  php:
    image: my_php
      environment:
        - MY_NEWRELIC_KEY=keykey

EDIT: You can specify a file to read values from. The file above is called env_file (name arbitrary) and it’s located in the current directory. You can reference the filename, which is parsed to extract the environment variables to set:

$ docker run --env-file=env_file php env

With docker-compose.yml files, we just reference a env_file, and Docker parses it for the variables to set.

version: '3'

services:
  php:
    image: php
      env_file: env_file
Related