干 docker-撰写

DRY docker-compose

我正在尝试找到一种更干的方式来使用 docker-compose env。

docker-撰写-base.yml

base:
    image: reactjs_web
    volumes:
        - src:/reactjs/src
        - bin/server:/reactjs/bin/server
        - config:/reactjs/config

docker-撰写-prod.yml

svr:
  extends:
    file: docker-compose-base.yml
    service: base
  command: npm run prod:deploy
  ports:
    - "8081:8081"
  environment:
    NODE_ENV: production
    PORT: "8081"
    CLTPORT: "8082"

clt:
  extends:
    file: docker-compose-base.yml
    service: base
  command: npm run prod:deploy:clientside
  ports:
    - "8082:8082"
  environment:
    NODE_ENV: production
    PORT: "8082"

你可以引用一个环境变量来解决这个问题 https://github.com/docker/compose/issues/1377

Docker 环境文件

使用 .env 文件并在两个容器中引用它。这将确保您只需将这些设置存储在一个位置。

Compose supports declaring default environment variables in an environment file named .env placed in the folder docker-compose command is executed from (current working directory).

Compose expects each line in an env file to be in VAR=VAL format. Lines beginning with # (i.e. comments) are ignored, as are blank lines.

撰写文件集成:

env_file: .env

env_file: 
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

Docker Compose File Reference - env_file

Docker Compose Environment File Documentation

您可以在 docker-compose.

中使用环境变量
  svr:
    extends:
      file: docker-compose-base.yml
      service: base
    command: npm run prod:deploy
    ports:
      - ${CLTPORT}:${PORT}
    environment:
      NODE_ENV: production

  clt:
    extends:
      file: docker-compose-base.yml
      service: base
    command: npm run prod:deploy:clientside
    ports:
      - ${CLTPORT2}:${PORT2}
    environment:
      NODE_ENV: production

运行 docker-写成:

  CLTPORT=8082 PORT=8081 CLTPORT2=8081 PORT2=8082 docker-compose -f docker-compose-prod.yml up

当然可以根据需要更改端口变量。