热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Dockerfile:如何从文件内容设置环境变量

如何解决《Dockerfile:如何从文件内容设置环境变量》经验,为你挑选了2个好方法。

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

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

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

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

我遇到的问题是上面的脚本没有返回我需要的脚本。实际上,它不返回任何内容。

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

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))"'将生成正确的输出,但是我无法弄清楚如何将该输出分配给环境变量。

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



1> BMitch..:

First, the error you're seeing. I suspect there's a "not found" error message not included in the question. If that's the case, then the first issue is that you tried to run an executable that is the full string since you enclosed it in quotes. Rather than trying to run the shell command "export", it is trying to find a binary that is the full string with spaces in it and all. So to work past that error, you'd need to unquote your RUN string:

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

However, that won't solve your underlying problem. The result of a RUN command is that docker saves the changes to the filesystem as a new layer to the image. Only changes to the filesystem are saved. The shell command you are running changes the shell state, but then that shell exits, the run command returns, and the state of that shell, including environment variables, is gone.

To solve this for your application, there are two options I can think of:

选项A:为所有.env值将build args注入您的build中,并编写一个脚本,该脚本使用--build-arg每个变量的正确标志调用build 。在Dockerfile中,每个变量都有两行:

ARG FOO1=default value1
ARG FOO2=default value2
ENV FOO1=${FOO1} \
    FOO2=${FOO2}

选项B:注入.env文件,并在容器中使用入口点对其进行处理。该入口点可以在启动实际应用程序之前运行导出命令。您还需要RUN在构建中需要这些变量的每个命令中执行此操作。我用于将文件内容拉入环境变量的一种速记方式是:

set -a && . .env && set +a



2> chamindaindi..:

环境变量

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

有关env_file的更多信息


建立Args

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

ARG FOO
ARG FOO1
ARG FOO2
等等...

而且您必须build在您的键下指定这些参数docker-compose.yml

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

有关args的更多信息


访问docker-compose.yml文件中的.env值

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

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

请检查一下


推荐阅读
author-avatar
李2502933835
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有