编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

如何通过带有运行docker run中传递的动态值的Dockerfile创建属性文件?:How to create a properties file via Dockerfile with dynamic values passed in docker run?

MHIdea 云计算 2022-5-11 10:26 8人围观

腾讯云服务器
如何通过带有运行docker run中传递的动态值的Dockerfile创建属性文件?的处理方法

我对Docker比较陌生.也许这是一个愚蠢的问题.

I am relatively new to Docker. Maybe this is a silly question.

我的目标是创建一个具有 system.properties 文件的图像,顾名思义,该文件是具有键值对的属性文件.我想动态填充此文件中的值.因此,我认为这些值需要作为环境变量传递给Docker run命令.

My goal is to create an image which has a system.properties file, which as the name says, is a properties file with key value pairs. I want to fill the values in this file dynamically. So I think the values need to be passed as environment variables to the Docker run command.

例如,如果这是我想要的 system.properties 文件中的内容:

For example, if this is what i want in my system.properties file:

buildMode=true source=/path1 

我想为该文件动态提供值,例如:

I want to provide the values to this file dynamically, something like:

$ docker run -e BUILD_MODE=true -e SOURCE='/path1' my_image 

但是我对如何将值复制到文件中感到困惑.任何帮助将不胜感激.

But I'm stuck at how I can copy the values into the file. Any help will be appreciated.

注意:基本映像是linux centos.

Note: Base image is linux centos.

问题解答

您怀疑,您需要在运行时创建实际文件.在Docker中有用的一种模式是编写一个专用的入口点脚本,该脚本执行所有必需的设置,然后启动main容器命令.

As you suspect, you need to create the actual file at runtime. One pattern that’s useful in Docker is to write a dedicated entrypoint script that does any required setup, then launches the main container command.

如果您使用的是更大"的Linux发行版,请

If you’re using a "bigger" Linux distribution base, envsubst is a useful tool for this. (It’s part of the GNU toolset and isn’t available by default on Alpine base images, but on CentOS it should be.) You might write a template file:

buildMode=${BUILD_MODE} source=${SOURCE} 

然后您可以将该模板复制到图像中

Then you can copy that template into your image:

... WORKDIR /app COPY ... COPY system.properties.tmpl ./ COPY entrypoint.sh / ENTRYPOINT ["/entrypoint.sh"] CMD ["java", "-jar", "app.jar"] 

入口点脚本需要运行envsubst,然后继续运行命令:

The entrypoint script needs to run envsubst, then go on to run the command:

#!/bin/sh envsubst <system.properties.tmpl >system.properties exec "$@" 

您可以仅使用 sed (1)做类似的技巧,该工具更通用,但可能需要更复杂的正则表达式.

You can do similar tricks just using sed(1), which is more universally available, but requires potentially trickier regular expressions.

这篇关于如何通过带有运行docker run中传递的动态值的Dockerfile创建属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^