Dockerfile:如何从文件内容设置环境变量 [英] Dockerfile: how to set env variable from file contents

查看:2340
本文介绍了Dockerfile:如何从文件内容设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Dockerfile中设置一个环境变量.

I want to set an environment variable in my Dockerfile.

我有一个.env文件,看起来像这样: FOO=bar.

I've got a .env file that looks like this: FOO=bar.

在我的Dockerfile中,我有一个命令来解析该文件的内容并将其分配给FOO.

Inside my Dockerfile, I've got a command that parses the contents of that file and assigns it to FOO.

RUN 'export FOO=$(echo "$(cut -d'=' -f2 <<< $(grep FOO .env))")'

我遇到的问题是上面的脚本没有返回我需要的内容.实际上,它什么也不会返回.

The problem I'm running into is that the script above doesn't return what I need it to. In fact, it doesn't return anything.

当我运行docker-compose up --build时,它失败并显示此错误.

When I run docker-compose up --build, it fails with this error.

The command '/bin/sh -c 'export FOO=$(echo "$(cut -d'=' -f2 <<< $(grep FOO .env))")'' returned a non-zero code: 127

我知道命令/bin/sh -c 'echo "$(cut -d'=' -f2 <<< $(grep FOO .env))"'会生成正确的输出,但是我不知道如何将输出分配给环境变量.

I know that the command /bin/sh -c 'echo "$(cut -d'=' -f2 <<< $(grep FOO .env))"' will generate the correct output, but I can't figure out how to assign that output to an environment variable.

关于我在做什么错的任何建议?

Any suggestions on what I'm doing wrong?

推荐答案

环境变量

如果要在Docker映像中设置许多环境变量(以在容器内使用),则可以简单地在docker-compose.yml文件中使用env_file配置选项.使用该选项,.env文件中的所有条目都将被设置为映像中的环境变量,因此将被设置为容器.

Environment Variables

If you want to set a number of environment variables into your docker image (to be used within the containers) you can simply use env_file configuration option in your docker-compose.yml file. With that option, all the entries in the .env file will be set as the environment variables in image and hence into containers.

有关env_file的更多信息

如果您的要求是仅在Dockerfile中使用某些变量,则可以按以下方式指定它们

If your requirement is to use some variables only within your Dockerfile then you specify them as below

ARG FOO
ARG FOO1
ARG FOO2
等等...

ARG FOO
ARG FOO1
ARG FOO2
etc...

并且您必须在docker-compose.yml

build: context: . args: FOO: BAR FOO1: BAR1 FOO2: BAR2

build: context: . args: FOO: BAR FOO1: BAR1 FOO2: BAR2

有关args的详细信息

如果您正在考虑将某些值从.env传递到docker-compose文件中,则只需将.env文件放置在与docker-compose.yml文件相同的位置,即可设置以下配置值;

If you are looking into passing some values into your docker-compose file from the .env then you can simply put your .env file same location as the docker-compose.yml file and you can set the configuration values as below;

ports: - "${HOST_PORT}:80"
因此,作为示例,您可以通过在.env文件中设置服务来设置服务的主机端口

ports: - "${HOST_PORT}:80"
So, as an example you can set the host port for the service by setting it in your .env file

请选中此

这篇关于Dockerfile:如何从文件内容设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆