Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

docker-compose - how to escape environment variables

With docker-compose v2 environment variables can be set by simply:

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

The full docker-compose.yml file being:

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
  [...]

However, how can I escape environment variables that are not a plain string?

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

I tried:

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" }}}'

ERROR: yaml.parser.ParserError: while parsing a block mapping in "./docker-compose.yml", line 6, column 9 expected , but found '}' in "./docker-compose.yml", line 6, column 92

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Environment variables (including their name), have to be fully wrapped inside single or double quotes: "" or ''

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

And using double quotes:

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

It is remarkable to note that using double quotes "", like bash, will allow placing variables inside the environment variable.

"MY_HOME_ENV_VARIABLE=${HOME}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...