[英]How can I pass docker environment variables to an npm script?
As the title says...As a noobie I've given this a good attempt but can't seem to figure it out.正如标题所说......作为一个菜鸟,我已经做了一个很好的尝试,但似乎无法弄清楚。
I have a dockerfile我有一个 dockerfile
FROM node:12
WORKDIR /app
COPY . /app
RUN npm config set registry https://registry.npmjs.org/
RUN npm install
EXPOSE 8080
ENTRYPOINT ["npm", "start",]
CMD [ "--", "-e=$ENVIRONMENT", "-t=$TESTS" ]
and a script in my package.json like so:和我的 package.json 中的脚本,如下所示:
"scripts": {
"start": "node main.js"
}
Main.js is expecting two arguments. Main.js 需要两个参数。 e & t.
E&T。 I am struggling to pass these in to the container to then give to the script to run main.js (note there is a reason why im running it through a script ive just made this example simple)
我正在努力将这些传递给容器,然后让脚本运行 main.js(注意,我通过脚本运行它是有原因的,我只是让这个例子变得简单)
To run my npm script I can do this:要运行我的 npm 脚本,我可以这样做:
npm start -- -e=abc -t=xyz
So I have tried this but no joy:所以我试过这个,但没有快乐:
docker run -e ENVIRONMENT=abc -e TESTS=xyz myimage
Thanks谢谢
When you use the JSON form of CMD
(or ENTRYPOINT
or RUN
), there is no interpolation at all;当您使用 JSON 形式的
CMD
(或ENTRYPOINT
或RUN
)时,根本没有插值; your script should literally see the string -e=$ENVIRONMENT
as the argument.您的脚本应该将字符串
-e=$ENVIRONMENT
视为参数。 Instead you need to use the shell form, which will wrap this in a shell that expands environment variables.相反,您需要使用 shell 形式,它将把它包装在一个扩展环境变量的 shell 中。 You can't do this with this particular split of
ENTRYPOINT
and CMD
, but at the same time, it's not really necessary;你不能用这个特殊的
ENTRYPOINT
和CMD
拆分来做到这一点,但同时,这并不是真正必要的; just put the whole thing in CMD
.只需将整个内容放在
CMD
。
# No ENTRYPOINT
# No quoting; Docker wraps this in `sh -c ...`
CMD npm start -- -e="$ENVIRONMENT" -t="$TESTS"
You can also handle these directly in your application.您也可以直接在您的应用程序中处理这些。 The
yargs
library for example has a .env()
function that allows environment variables to be used directly as options.例如,
yargs
库有一个.env()
函数,它允许将环境变量直接用作选项。 You could also make process.env.TESTS
be the default value for the option if it's not provided directly.如果没有直接提供,您还可以将
process.env.TESTS
设为该选项的默认值。 This approach gets around the trouble of constructing (and possibly extending) a valid command line with the combination of arguments you need.这种方法解决了使用您需要的参数组合构建(并可能扩展)有效命令行的麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.