如何通过环境文件在Docker中传递环境变量? [英] How to pass through environment variables in docker run through an env file?
问题描述
给出此Dockerfile:
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"]
我希望能够通过传递多个变量.env
文件,格式为 key = value
。
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
我的 delete.sh
看起来像这样:
#!/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
我期望看到env变量,但它们都是空的。 -env-file
选项似乎不起作用。脚本的输出为:
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
我通过以下方式创建并运行docker容器:
I create and run the docker container via:
docker build -t deleter:local
docker run deleter:local --env-file stage.env
我尝试过-env-file stage.env
,-env-file = stage.env
,-env文件./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.
stage.env
与我的Dockerfile处于同一级别。
The stage.env
is on the same level as my Dockerfile.
env文件有效,我可以在本地计算机上获取该文件,并访问其中的变量。
The env file is valid, I can source it on my local machine an access the variables there.
我的错误在哪里?
推荐答案
请记住 docker运行参数顺序是强制性的:
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
因此:
docker run --env-file stage.env run deleter:local
将按预期导入环境变量。
will import the environment variables as expected.
这篇关于如何通过环境文件在Docker中传递环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!