问题描述
我正在使用firesh/nginx-lua(Linux发行版为Alpine)创建的docker映像:
I am working on a docker image I created using firesh/nginx-lua (The Linux distribution is Alpine):
FROM firesh/nginx-lua
COPY ./nginx.conf /etc/nginx
COPY ./handler.lua /etc/nginx/
COPY ./env_var_echo.py /etc/nginx/
RUN apk update
RUN apk add python3
RUN nginx -s reload
我运行映像,然后进入docker:
I run the image and then get in the docker:
docker run -it -d -p 8080:80 --name my-ngx-lua nginx-lua
docker exec -it my-ngx-lua sh
然后我在docker内部定义一个新的环境变量 :
Then I define a new environment variable from inside the docker:
/etc/nginx # export SECRET=thisIsMySecret
/etc/nginx # echo $SECRET
thisIsMySecret
/etc/nginx #
编辑:在定义了新的环境变量后,我退出了容器,然后再次进入容器,它不再存在了:
After defining the new env var, I exit the container and then get into it again and it is not there anymore:
/etc/nginx # exit
iy@MacBook-Pro ~ % docker exec -it my-ngx-lua sh
/etc/nginx # echo $SECRET
/etc/nginx #
我运行python脚本,希望收到"thisIsMySecret",这是我定义的值.
I run the python script and I expect to receive "thisIsMySecret", which is the value I defined.
import os
secret_key = os.environ.get('SECRET')
print(secret_key + '\n')
但是我得到的是无.
仅当我使用docker(例如PATH)调用已附带的任何env var时,python才会返回它的值.但是,如果它是我刚刚定义的env var,它将返回None.
Only if I call any env var that already came with the docker (PATH for example), python will return the value of it. But if it is an env var that I just defined, it will return None.
顺便说一句,我在lua上尝试了同样的操作,并收到了 nil .因此,我很确定问题出在Alpine.
BTW, I tried the same with lua and received nil. hence I am pretty sure the issue is from Alpine.
我不是正在寻找一种解决方案,例如从docker build中定义env var.
I am not looking for a solution like defining the env var from docker build.
谢谢.
推荐答案
此
是原因.导出的变量仅在主进程运行时才存在,并且仅在声明它的进程中可见.
is the cause. Exported variable only exists while the main process does and it is only visible to the process it was declared in.
您需要的是在启动容器时使用 -e
选项:
What you need is to use the -e
option when you start the container:
docker run -e SECRET=mysecret ...
使用此docker会将环境变量添加到主进程(在本例中为NGINX),也将添加到 docker exec
命令.
With this docker will add the environment variable to the main process (NGINX in this case) and to docker exec
commands as well.
这篇关于Env var在docker上定义,但返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!