【发布时间】:2020-06-09 04:19:33
【问题描述】:
我希望能够为我的 docker 容器配置 env 变量,并在构建过程中使用 .env 文件
我目前有以下.env 文件:
SSH_PRIVATE_KEY=TEST
APP_PORT=8040
我的 docker-compose:
version: '3'
services:
companies:
image: companies8
environment:
- SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}
ports:
- ${APP_PORT}:${APP_PORT}
env_file: .env
build:
context: .
args:
- SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}
我的Dockerfile:
FROM python:3.7
# set a directory for the app
COPY . .
#Accept input argument from docker-compose.yml
ARG SSH_PRIVATE_KEY=abcdef
ENV SSH_PRIVATE_KEY $SSH_PRIVATE_KEY
RUN echo $SSH_PRIVATE_KEY
# Pass the content of the private key into the container
RUN mkdir -p /root/.ssh
RUN chmod 400 /root/.ssh
RUN echo "$SSH_PRIVATE_KEY" > /root/.ssh/id_rsa
RUN echo "$SSH_PUBLIC_KEY" > /root/.ssh/id_rsa.pub
RUN chmod 400 /root/.ssh/id_rsa
RUN chmod 400 /root/.ssh/id_rsa.pub
RUN eval $(ssh-agent -s) && ssh-add /root/.ssh/id_rsa && ssh-keyscan bitbucket.org > /root/.ssh/known_hosts
RUN ssh -T git@bitbucket.org
#Install the packages
RUN pip install -r v1/requirements.txt
# Tell the port number the container should expose
EXPOSE 8040
# run the command
CMD ["python", "v1/__main__.py"]
我在我的 Windows 上设置了相同的 SSH_PRIVATE_KEY 环境变量,值为“test1”,构建日志给了我来自
的结果“test1”ENV SSH_PRIVATE_KEY $SSH_PRIVATE_KEY
RUN echo $SSH_PRIVATE_KEY
不是 .env 文件中的值。
我需要这个,因为我的 requirements.txt 中列出的一些库位于内部存储库中,我需要 ssh 来访问它们,因此需要 ssh 私钥。可能有另一种正确的方法来使用它,但它是我想要实现的一般场景 - 将 env 变量值从 .env 文件传递到我的 docker build
【问题讨论】:
-
尝试在
ARG SSH_PRIVATE_KEY和args: - SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}此处保留一个空值(最好完全删除args)。当 docker 使用--build-arg NAME运行时,它会尝试从环境中获取 VALUE。 -
或者可能是this?
-
你为什么不直接取消设置环境变量,否则它将覆盖来自
.env的值
标签: python docker docker-compose environment-variables containers