向容器公开Docker映像环境变量

向容器公开Docker映像环境变量,docker,docker-compose,environment-variables,Docker,Docker Compose,Environment Variables,我有一个使用docker compose构建的docker映像,并提供了一个环境文件,如: version: '3' services: postgres: ... redis: image: redis:4.0 api: build: ./src/api env_file: ./integrationtests.env tests_integration: build: ./tests/Integration env_file:

我有一个使用docker compose构建的docker映像,并提供了一个环境文件,如:

version: '3'
services:
  postgres:
    ...
  redis:
    image: redis:4.0
  api:
    build: ./src/api
    env_file: ./integrationtests.env
  tests_integration:
    build: ./tests/Integration
    env_file:
      - ./integrationtests.env
    depends_on:
      - postgres
      - redis
      - api
环境文件有几个定义,但我最关心的定义如下
ApiUrl=http:\\api

我有一个用于集成测试的docker文件,定义如下:

FROM apline
WORKDIR /app

ENV ApiUrl $ApiUrl
COPY ./scripts ./scripts

ENTRYPOINT [ "printenv" ]
当我运行
docker compose up
时,它会正确打印出构建阶段可用的所有环境变量。但是当我运行docker时--entrypoint printenv mycontainerenv var
apirl
是空的


如何确保特定变量在构建和运行阶段都可用?

构建Docker映像发生在Docker Compose过程的早期;像
环境:
这样的设置对于在
Dockerfile
中运行的代码永远不可见(类似于网络设置和卷装载)

映像应该可以跨环境重用。我的建议是尽可能地将环境变量的默认值设置为通用值,但希望它被覆盖

FROM alpine
ENV API_URL /
CMD printenv
如果您想使用
docker compose.yml
中的环境和音量设置运行映像,可以使用


如果您确实需要在图像中硬编码该值,并且该值对于任何可能拥有图像副本的潜在用户在所有环境中都非常有用,a和相应的是更好的匹配。

尝试使用args而不是env_文件这里有一个很好的参考您的docker compose文件应该类似于以下示例:

  version: '3'

    services:
      somename:
        build:
          context: ./app
          dockerfile: Dockerfile
          args:
            some_variable_name: a_value
  version: '3'

    services:
      somename:
        build:
          context: ./app
          dockerfile: Dockerfile
          args:
            some_variable_name: a_value