Danny Guo | 郭亚东

How to Use Newlines in an Environment Variable File for Docker

  ·  176 words  ·  ~1 minute to read

When you run a Docker container, you can pass environment variables to the run command. However, the --env-file option has a limitation in that it doesn’t handle newline characters. See this GitHub issue and this comment on a separate issue.

This can be problematic if you need newlines for something like a public or private key for public-key cryptography. I tried adding double quotes around the value and using \n for the newlines:

FOO=bar
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nFOO\nBAR\nBAZ\n-----END PRIVATE KEY-----"

But that didn’t work, using single quotes didn’t work, and actually breaking the value across multiple lines in my .env file didn’t work either. As a workaround, I found that I could detect the situation and modify the value in code. For a Node.js server, I did this:

let PRIVATE_KEY = process.env.PRIVATE_KEY;
if (PRIVATE_KEY?.startsWith(`"`)) {
    PRIVATE_KEY =
        PRIVATE_KEY.replaceAll(`"`, ``).replaceAll(`\\n`, `\n`);
}

So I removed the double quotes and replaced every occurrence of a literal backslash (the \\ is necesssary for escaping the backslash) followed by a n with a newline character. This worked for my use case.


← How to Break and Continue in Nested Loops in JavaScript How to Disable 5G for a Samsung Galaxy S21 FE Phone →

Follow me on Twitter or subscribe to my free newsletter or RSS feed for future posts.

Found an error or typo? Feel free to open a pull request on GitHub.


comments powered by Disqus