How to read environment variable in Nodejs?

I am trying to read a environment file through docker compose.

My problem is my code only read the first line of the variable value.

  • Running atop in a docker stack
  • Dockerfile replicate the host user UID and GID to the image
  • Can't run sonar-scanner inside docker container: Permission denied
  • Failing to delete Docker's images after terminating the container
  • “Error response from daemon: Cannot start container … no such file or directory” on Oracle Linux running hello-world
  • ADD Command for Docker Toolbox on Mac
  • My test.env

    ## Not the actual key ##
    -----END PUBLIC KEY-----

    My docker-compose

        build: .   
          - test.env

    I was able to read NODE_ENV in my app.js file with

    console.log(process.env.NODE_ENV) ==> output development

    but console.log(process.env.RSA_PUBLIC) ==> only output -----BEGIN PUBLIC KEY-----

    which is the first line of the key.

    and make my jwt token validation failed with

    PEM_read_bio_PUBKEY failed

    I am not sure how to fix this. Can anyone help me about it? Thanks a lot!

  • Getting User name + password to docker container
  • Docker: Unable to run shell script stored in a mounted volume
  • How to run protractor on docker?
  • How do I wait for a pull?
  • issue with exposing ports using docker compose
  • Docker: change folder where to store docker volumes
  • 2 Solutions collect form web for “How to read environment variable in Nodejs?”

    The solution for this might differ by linebreak style of your OS, but I solved this issue by replacing linebreak with \n(which makes your key a single line string), and then read it on server by replacing \n with \n

    process.env.RSA_PUBLIC.replace(/\\n/g, '\n')

    Two thoughts:

    1. How do you store the variable? Do you use the process.env directly, or something like dotenv?

    2. Did you try storing without the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" lines?

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.