gpt4 book ai didi

node.js - 使用 docker run 命令将参数传递给 Dockerfile 中的 CMD

转载 作者:IT老高 更新时间:2023-10-28 12:36:59 38 4
gpt4 key购买 nike

我是 Docker 新手,我很难根据需要设置 docker 容器。我有一个 nodejs 应用程序在启动时可以带两个参数。例如,我可以使用

node server.js 0 开发

node server.js 1 prod

在生产模式和开发模式之间切换并确定是否应该打开集群。现在我想创建带有参数的 docker 镜像来做类似的事情,到目前为止我唯一能做的就是调整 Dockerfile 有一行

CMD [ "node", "server.js", "0", "dev"]

docker build -t me/app. 构建 docker。

然后docker run -p 9000:9000 -d me/app 运行docker。

但是如果我想切换到 prod 模式,我需要将 Dockerfile CMD 更改为

CMD [ "node", "server.js", "1", "prod"] ,

我需要终止监听端口 9000 的旧版本并重建镜像。我希望我能有类似的东西

docker run -p 9000:9000 environment=dev cluster=0 -d me/app

创建镜像并使用“环境”和“集群”参数运行 nodejs 命令,因此我不需要更改 Dockerfile 并重新构建 docker。我怎样才能做到这一点?

最佳答案

确保您的 Dockerfile 声明了一个环境变量 with ENV :

ENV environment default_env_value
ENV cluster default_cluster_value

ENV <key> <value>表格可以是replaced inline .

那么你可以pass an environment variable with docker run .请注意,每个变量都需要特定的 -e要运行的标志。

docker run -p 9000:9000 -e environment=dev -e cluster=0 -d me/app

或者你可以set them through your compose file :

node:
environment:
- environment=dev
- cluster=0

您的 Dockerfile CMD可以使用该环境变量,但是,如 issue 5509 中所述,您需要在 sh -c 中这样做形式:

CMD ["sh", "-c", "node server.js ${cluster} ${environment}"]

The explanation is that the shell is responsible for expanding environment variables, not Docker. When you use the JSON syntax, you're explicitly requesting that your command bypass the shell and be executed directly.

Builder RUN 的想法相同(也适用于 CMD):

Unlike the shell form, the exec form does not invoke a command shell.
This means that normal shell processing does not happen.

For example, RUN [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: RUN [ "sh", "-c", "echo $HOME" ].

When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.

关于node.js - 使用 docker run 命令将参数传递给 Dockerfile 中的 CMD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873165/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com