How to Use Newlines in an Environment Variable File for Docker
source link: https://www.dannyguo.com/blog/how-to-use-newlines-in-an-environment-variable-file-for-docker/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Use Newlines in an Environment Variable File for Docker
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.
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.
You can encrypt messsages with my GPG key if you'd like.
© 2022 Danny Guo
This content is licensed under CC BY-NC-SA 4.0 and hosted on GitHub.
As an Amazon Associate I earn from qualifying purchases.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK