简体   繁体   English

Docker compose 从 .env 文件中获取 env 变量并传递给 docker build

[英]Docker compose obtain env variables from .env file and pass to docker build

I'd like to be able to configure env variables for my docker containers and use them in build process with .env file我希望能够为我的 docker 容器配置 env 变量,并在带有 .env 文件的构建过程中使用它们

I currently have the following .env file:我目前有以下.env文件:

SSH_PRIVATE_KEY=TEST
APP_PORT=8040

my docker-compose :我的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}

my Dockerfile :我的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"]

and i have the same SSH_PRIVATE_KEY environment variable set on my windows with value "test1" and the build log gives me the result 'test1' from我在我的 Windows 上设置了相同的 SSH_PRIVATE_KEY 环境变量,值为“test1”,构建日志给了我结果“test1”来自

ENV SSH_PRIVATE_KEY $SSH_PRIVATE_KEY
RUN echo $SSH_PRIVATE_KEY

not the value that's in the .env file.不是 .env 文件中的值。

I need this because some of the libraries listed in my requirements.txt are in an internal repository and I need ssh to access them, therefore the ssh private key.我需要这个是因为我的 requirements.txt 中列出的一些库在内部存储库中,我需要 ssh 来访问它们,因此需要 ssh 私钥。 There might be another proper way to use this, but its the general scenario i want to achieve - to pass env variables values from .env file to my docker build可能有另一种正确的方法来使用它,但它是我想要实现的一般场景 - 将 .env 文件中的 env 变量值传递给我的 docker build

There's a certain overlap between ENV and ARG as shown in the image below: ENVARG之间有一定的重叠,如下图所示:

在此处输入图片说明

Since you are having the variable already exported in the operating system, its value will be present in the image from the ENV instruction.由于您已经在操作系统中导出了变量,因此它的值将出现在ENV指令的图像中。

But if you do not really need the variable in the image and only in the build step (as far as I see from the docker-compose file), then the ARG instruction is enough.但是如果你真的不需要镜像中的变量,而只是在构建步骤中(就我从docker-compose文件中看到的),那么ARG指令就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM