Unable to set an environment variable with a docker container, Error: poorly formatted environment variable, Contains whitespaces

84 views Asked by At

Im trying to run a docker container and load environment variables from my .env file which is in the same root directory as the rest of the project. For context, my .env file looks something like this:

SERVICE_KEY = `{
  "type": "anything",
  "project_id": "anything",
  "private_key_id": "anything",
  "private_key": "anything",
  "client_email": "anything",
  "client_id": "anything",
  "auth_uri": "anything",
  "token_uri": "anything",
  "auth_provider_x509_cert_url": "anything",
  "client_x509_cert_url": "anything"
}`   

It is a JSON string that has back ticks `` with spaces around it to allow for parsing. It is part of a NodeJs application and I am using the dotenv package to find and initialize the environment variable. The app runs fine on my machine

When I run a command like this: $ docker run -p 3000:3000 -d --env-file ./.env image-name im getting an error: docker: poorly formatted environment: variable '"project_id": "my-image",' contains whitespaces. I know there are similar questions that have been asked here but none of those solutions help, I was wondering if anyone could point me in the right direction.

1

There are 1 answers

1
David Maze On

The docker run --env-file format

... file should use the syntax <variable>=value (which sets the variable to the given value) [...] and # for comments. Lines beginning with # are treated as line comments and are ignored ....

That is, it accepts one variable setting to a line, and has no provision for multi-line variables. Compose has a slightly different format, but again

Each line represents a key-value pair.

and there is no provision for multi-line variables or backticks as any sort of quoting.

If the value is intended to be parseable JSON, you can just remove all of the interior whitespace. This is a little harder to edit, but it works with standard tools.

SERVICE_KEY={"type": "anything", "project_id": "anything", ...}

There are potentially other approaches, such as reading the environment variable from a file

SERVICE_KEY=$(cat service-key.json) docker run -e SERVICE_KEY ...

but the file in the format you have it can't be read by most tools, only the specific library you're using.