32

I want to set a multiline environment variable in my Dockerfile.

Works through command line

If I pass in the environment variable through docker run everything works.

CONFIG="port: 4466
databases:
  prod:
    connector: mysql
    active: true
    host: 33.333.333.333
    port: 3306
    user: root
    password: pass"
docker run --env CONFIG="$CONFIG" ubuntu:latest env | grep 'CONFIG'

Output (its only a single line because its interpreted as multiline variable)

CONFIG=port: 4466

Doesnt Work through dockerfile

Dockerfile

FROM ubuntu:latest
ENV CONFIG 'port: 4466\ndatabases:\n  prod:\n    connector: mysql\n    active: true\n    host: host\n    port: 3306\n    user: root\n    password: pass'

Build and run the docker image

docker build -t multilinetest .
docker run multilinetest env | grep 'CONFIG'

Output

CONFIG=port: 4466\ndatabases:\n  prod:\n    connector: mysql\n    active: true\n    host: host\n    port: 3306\n    user: root\n    password: pass

Expected

Both scenarios should store the same environment variable (I'm passing this environment variable into a 3rd party image that requires a multiline string)

4 Answers 4

28

I was able to get this working by passing the multiline environment variable as a build arg to docker build.

Dockerfile

FROM ubuntu:latest
ARG CONFIG
ENV CONFIG $CONFIG

Build Command

CONFIG="port: 4466
databases:
  prod:
    connector: mysql
    active: true
    host: 33.333.333.333
    port: 3306
    user: root
    password: pass"
docker build --build-arg CONFIG="$CONFIG" ubuntu:latest env | grep 'CONFIG'
Sign up to request clarification or add additional context in comments.

Comments

11

Escaping newline characters work fine.

Dockerfile

ENV BUILD_DEPENDENCIES apt-utils \
  curl \
  libc-dev \
  gcc \
  gnupg2

Output

Step 8/48 : ENV BUILD_DEPENDENCIES apt-utils   curl   libc-dev   gcc   gnupg2
 ---> Running in 65b0ad105af4

1 Comment

This is not actually the solution because this turns newlines into nothing,
2

You can do it like this:

ENV CONFIG="port: 4466\n"\
"databases:\n"\
"  prod:\n"\
"    connector: mysql\n"\
"    active: true\n"\
"    host: 33.333.333.333\n"\
"    port: 3306\n"\
"    user: root\n"\
"    password: pass\n"

Comments

0

Unfortunately, Docker does not support multiline by default. You can use dotenvx if you need multiline support with Docker. Just put dotenvx run -- out in front of your docker command.

$ docker run -- docker ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.