如何通过 docker-compose.yml 中的 env_file 将 ENV 变量插入到 Dockerfile 中?

问题描述 投票:0回答:1

我想将 ENV 变量从 docker-compose.yml 插入/传递到 Dockerfile

docker-compose.yml

version: '3.8'

services:
  app:
    container_name: app-container
    image: app:latest
    build:
      context: ./
      dockerfile: Dockerfile
    env_file: # Interpolation source files
      - ./env 

.env

PORT=3000

Dockerfile

FROM node:16

RUN echo ${PORT} # Output should be '3000'

我有办法完成这项工作吗?我正在尝试找到一种专门传递

.env
文件的方法,以便更好地组织。我也想避免使用 ARG

docker docker-compose dockerfile environment-variables interpolation
1个回答
0
投票

默认情况下,如果 .env 文件位于同一目录中,则 docker compose 会读取该文件。变量可以由 ${key} 在撰写预处理(=撰写文件)中使用。它不应该与移交给 docker run 的 env 文件混淆。这应该以其他方式命名。在我看来,混合两者是一个常见的错误。

构建时间变量可以通过 compose 中的 args、dockerfile 中的 ARG 和 docker build --build-arg 给出,运行时变量可以通过环境 (docker run - e) 或 compose 中的 env_file 给出(与 docker run --env-file 相同)。您需要一个构建时间变量(args)。因此:

build:
  args:
    PORT: ${PORT}

如果您也想在运行时使用这些值,请添加到 Dockerfile 中

ARG PORT 
ENV PORT="${PORT}"

我建议不要在环境中存储凭据,也不要将所有构建时变量自动传递给运行时(即使有解决方案这样做)。

© www.soinside.com 2019 - 2024. All rights reserved.