gpt4 book ai didi

node.js - 如何正确处理 docker 中的 .env 文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:25 26 4
gpt4 key购买 nike

我有一个 Node 应用程序使用 dotenv 来跟踪环境变量。它使用根文件夹中的 .env 文件来获取运行时的变量。问题是当我使用 docker 构建 Node 图像时,下面的行也为构建复制了 .env 文件

FROM node:latest

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8000

如果我从 dockerhub 构建并拉取镜像。该文件已包含我在开发中使用的 .env 文件。理想情况下,我想为生产指定一个不同的 .env 文件。 (也许在生产服务器中手动创建一个新的 .env 文件)

我尝试在 dockerignore 中指定 .env 文件。但是 COPY 行。/usr/src/app 似乎仍然复制 env 文件。

我不需要这样使用 dotenv。我试着像下面这样指定它

version: '2'

services:
node:
container_name: node
build: .
env_file: .env
volumes:
- .:/usr/src/app
- /usr/src/app/node_modules
command: npm start

所以我真的不需要在构建中指定 .env 文件夹。但这也行不通。

如何阻止 COPY 命令复制 .env 文件?

最佳答案

有一个文件!

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

在您的情况下,您只需要在与 Dockerfile 相同的目录中echo .env >> .dockerignore

关于node.js - 如何正确处理 docker 中的 .env 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39103412/

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