Search code examples
dockerenvironment-variablesalpine-linux

How to pass through environment variables in docker run through an env file?


Given this Dockerfile:

FROM alpine:3.7
ENV LAST_UPDATED=2018-02-22
ARG XDG_CACHE_HOME=/tmp/cache/
RUN apk update && \
    apk add libxslt && \
    apk add sed && \
    apk add py-pip && \
    apk add mariadb-client && \
    apk add bash bash-doc bash-completion && \
    pip install httpie && \
    rm -rf /var/cache/apk/*
WORKDIR /usr/deleter/
COPY delete.sh ./
ENTRYPOINT ["/usr/deleter/delete.sh"]

I expected to be able to pass multiple variables through an .env file with the key=value format.

$ cat stage.env 
MYSQL_DATABASE=database
MYSQL_HOST=127.0.0.1:3306
MYSQL_PASSWORD=password
MYSQL_PORT=3306
MYSQL_USER=a_user

My delete.sh only looks like this:

#!/bin/bash
set -e
set -o pipefail
echo "hello world"
echo ${MYSQL_DATABASE} ${MYSQL_HOST} ${MYSQL_PASSWORD} ${MYSQL_PORT} ${MYSQL_USER}
echo "ALL VARIABLES"
env

I expected to see the env variables, yet they all are empty. The --env-file options seems to be not working. The output of the script is:

hello world

ALL VARIABLES
HOSTNAME=f52c5c2aa22b
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/usr/deleter
LAST_UPDATED=2018-02-22
SHLVL=1
HOME=/root
_=/usr/bin/env

I create and run the docker container via:

docker build -t deleter:local
docker run deleter:local --env-file stage.env

I tried --env-file stage.env, --env-file=stage.env, --env-file ./stage.env, yet I don't see anything being included nor any thrown error. I also tried it with the absolute path.

The stage.env is on the same level as my Dockerfile.

The env file is valid, I can source it on my local machine an access the variables there.

Where is my mistake?


Solution

  • Keep in mind that the docker run argument order is mandatory:

    $ docker help run 
    Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
    

    The environment setting fall under options:

     -e, --env list                       Set environment variables
         --env-file list                  Read in a file of environment 
    

    Hence:

    docker run --env-file stage.env deleter:local
    

    will import the environment variables as expected.