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

烂漫一生 提交于 2019-12-10 19:16:55

问题


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?


回答1:


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 run deleter:local

will import the environment variables as expected.



来源:https://stackoverflow.com/questions/48930991/how-to-pass-through-environment-variables-in-docker-run-through-an-env-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!