docker-compose - 如何转义环境变量

时间:2017-02-01 20:11:23

标签: docker environment-variables docker-compose

使用docker-compose v2环境变量可以简单地设置:

enviroment:
  - MONGO_PATH=mongodb://db-mongo:27017

完整的docker-compose.yml文件:

version: '2'
services:
  web:
    build: .
    environment:
      - MONGO_PATH=mongodb://db-mongo:27017
    ports:
      - "3000:3000"
    volumes:
      - .:/app
      - /app/node_modules
    depends_on: 
      - db-mongo
      - db-redis
  db-mongo:
    image: mongo
    restart: unless-stopped
    command: --smallfiles
    ports:
      - "27017:27017"
    volumes:
      - ./data:/data/db
  [...]

但是,如何转义不是普通字符串的环境变量?

{"database": {"data": {"host": "mongo"}}}

我试过了:

NODE_CONFIG=\{"database": \{"data"\: \{"host": "mongo"\}, "session": \{"host": "redis" \}\}\}
NODE_CONFIG="\{"database": \{"data"\: \{"host": "mongo"\}, "session": \{"host": "redis" \}\}\}"
NODE_CONFIG='{"database": {"data": {"host": "mongo"}, "session": {"host": "redis" }}}'
  

错误:yaml.parser.ParserError:在解析块映射时   " ./ docker-compose.yml",第6行,第9列预期,但是   发现'}' in" ./ docker-compose.yml",第6行,第92栏

1 个答案:

答案 0 :(得分:38)

环境变量(包括其名称),必须完全包含在单引号或双引号内""''

environment:
  - 'NODE_CONFIG={"database": {"data": {"host": "mongo"}, "session": {"host": "redis" }}}'

使用双引号:

environment:
  - 'PORT=3000'
  - "NODE_CONFIG={\"database\": {\"data\": {\"host\": \"mongo\"}, \"session\": {\"host\": \"redis\" }}}"

值得注意的是,使用双引号""(如bash)将允许将变量放在环境变量中。

"MY_HOME_ENV_VARIABLE=${HOME}"