如何为另一个 docker 服务交换 env 文件

How to swap env file for another docker service

我有一个docker-compose.yml

services:
  nextjs:
    container_name: next_app
    build:
      context: ./
    restart: on-failure
    command: npm run dev
    volumes:
      - ./:/app
      - /app/node_modules
      - /app/.next
    ports:
      - "3000:3000"
  cypress:
    image: "cypress/included:9.4.1"
    depends_on:
      - next_app
    environment:
      - CYPRESS_baseUrl=http://nextjs:3000
    working_dir: /e2e
    volumes:
      - ./e2e:/e2e

我想从 cypress 服务中为 next_app 更改 env_file。我找到了这样的解决方案

cypress:
    image: "cypress/included:9.4.1"
    depends_on:
      - next_app
    environment:
      - CYPRESS_baseUrl=http://nextjs:3000
    working_dir: /e2e
    volumes:
      - ./e2e:/e2e
    next_app:
      env_file: .env.test

但是这个解决方案不起作用。有可能吗?

拉杰什·库斯罗帕利,您好!试试 cp .env #docker/.env

没有。在 Compose(或 Docker,或更普遍的 Linux/Unix)中,一个容器(进程)无法为另一个容器(进程)指定环境变量。

您可以将 docker-compose.yml 文件视为一组仅适用于 运行ning 容器的指令。如果您需要针对特定​​上下文的一组特定容器——您通常不需要 运行 Cypress 在生产环境中,但这是一个 integration-test 设置——编写一个单独的 Compose 文件就可以了该设置。

# docker-compose.cypress.yml
# Used only for integration testing
version: '3.8'
services:
  nextjs:
    build: .
    restart: on-failure
    ports:
      - "3000:3000"
    env_file: .env.test # <-- specific to this test-oriented Compose file
  cypress:
    build: ./e2e
    depends_on:
      - nextjs
    environment:
      - CYPRESS_baseUrl=http://nextjs:3000
docker-compose -f docker-compose.cypress.yml up --build

在这种情况下,使用 multiple Compose files together 也是一个合理的选择。您可以定义一个仅定义主要服务的“标准”Compose 设置,然后定义一个添加 Cypress 容器和环境设置的 e2e-test Compose 文件。

# docker-compose.yml
version: '3.8'
services:
  nextjs:
    image: registry.example.com/nextjs:${NEXTJS_TAG:-latest}
    restart: on-failure
    ports:
      - '3000:3000'
# docker-compose.e2e.yaml
version: '3.8'
services:
  nextjs:
    # These add to the definitions in the base `docker-compose.yml`
    build: .
    env_file: .env.test
  cypress:
    # This is a brand new container for this specific setup
    depends_on: [nextjs]
    et: cetera # copy from question or previous Compose setup
docker-compose \
  -f docker-compose.yml \
  -f docker-compose.e2e.yml \
  up --build