Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape this JSON string in Docker Compose file environment variable?

Here is my docker-compose yaml file.

version: '2.1'

services:
  myservice:
    environment:
      - MYENVVAR={"1": "Hello"}

This gives me the following parsing error when I run docker-compose

ERROR: yaml.parser.ParserError: while parsing a block mapping
  in "./my_docker_compose_.yml", line 6, column 9
expected <block end>, but found '}'
  in "./my_docker_compose_.yml", line 6, column 111

How can I escape my JSON object properly so it gets sent into the container as the value of environment variable MYENVVAR?

like image 301
Saqib Ali Avatar asked Mar 21 '20 05:03

Saqib Ali


People also ask

Can you use environment variables in Docker compose?

Configure Compose using environment variables Several environment variables are available for you to configure the Docker Compose command-line behavior.

Can we use JSON in Docker compose?

Yaml is a superset of json so any JSON file should be valid Yaml. To use a JSON file with Compose, specify the filename to use. In this lab we are going to bringup our same nginx and mysql containers using docker-compose file in json format.

Does Docker compose override environment variables?

But docker-compose does not stop at the . env and the host's current environment variables. It's cool that you can simply override values of your . env file, but this flexibility is can also be the source of nasty bugs.

Can you use environment variables in JSON?

You have to wrap the environment variable of choice into another set of quotes in order for it to be valid JSON.


Video Answer


1 Answers

You should define this variable as: 'FOOBAR={"foo": "bar"}'

In short:

version: '3.3'
services:
    nginx:
        ports:
            - '80:80'
        volumes:
            - '/var/run/docker.sock:/tmp/docker.sock:ro'
        restart: always
        logging:
            options:
                max-size: 1g
        environment:
            - 'FOOBAR={"foo": "bar"}'
            - a=test
        image: nginx

The similar question was raised on docker bug tracking system:

https://github.com/docker/compose/issues/3878

You can validate or experiment with docker-compose settings online by visiting a web page: https://composerize.com/

like image 182
Alex Konkin Avatar answered Nov 15 '22 07:11

Alex Konkin