How to define a multiline environment variable in docker-compose

AuthorDaniel Veihelmann
published January 21, 2024

If you want to define an environment variable in your docker-compose.yml, you can use the environment section (docs):

docker-compose.yml

# ... your service definition ...
# ...
environment:
  MY_ENV_VARIABLE: 'foo'

But what if the value of the variable spans multiple lines, for example an RSA key?

After trying a lot of solutions that didn't work, the key (no pun intended) was to use the |- character in the first line (source).

This example works with multiline keys:

docker-compose.yml

# ... your service definition ...
# ...
environment:
  MY_ENV_VARIABLE: 'foo'
  AUTH_KEY: |-
    -----BEGIN RSA PRIVATE KEY-----
    A345XQIBAAKBgQD272jYrLm8Ph5QpMWFcWUO9Ua1EviykalP+tkMIg12yZ3GvefA
    b8aayxdztB5vu68jqMeg6mOJlscWqFUhmAxj4mDknYenVzVX2CKzCgHlGninTKxB
    v1rXDaDZVpSZ+XIESJkaB0z9HHYtrSLr0coKmq4cT5TRptOnkpDlJxIRaQIDAQAB
    xoGATcTYoGTFmiN2KK+66WrRCQT2X9C5woNdb3LxKIEQ/HhC2HS4PRMQWW/c0vPH
    1ilZ30EoneUztAFochpRtWLNg4lJoLy04X/eNjEiC/imp0KSwWXmnuLhDcWcb0+M
    2lddvzHAAfK1jzIk8zEvcFnhuRoR/L3yWLQp3dIkG07h5IECQQD7xdyhfYMKiYZ7
    4Iq9mU0oNaC7UvxHTw3HB4rT3yvqVZXW15JvR64qCe+sOn9xJEesGDkUUxghV+dd
    xGFOODPb2trQ1NGyKzus72JvO61pVpIhT6kVQo3xC543/+1FvU+albjtmqKe1MjZ
    j2B6VtNdlgA4VzMC7qrZXwU+oD83WbG6s1GKQa/rX87wo9moOGcNPP7PmXovDr6F
    lIVbekIj0YuTQdo31aKPNmrTVqd+iOk0LGaUC5zMi0OgDaKKDuP1Ou6ANVTcBXcF
    hnJRQ7XYtjs0oSmvA7bgbTfN4IMJxJ4hYybF1pURh/o4QW4FUytLaF8zghuTc0aP
    yKIsFLzi5ZT34KLVNGAEA44FsG71hOajFkA4c2I/Wx9+
    -----END RSA PRIVATE KEY-----

And no, this is not a real key 😉

Notably, there is also a way to specify a env_file attribute in Docker Compose if you would rather use that.

That's it already, happy coding! 💻️


Need to review a complex merge request?

Let's get you some help! Simply paste your URL below:

Works with gitlab github