Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass environment variables to docker-compose's applications

I want to pass environment variables that is readable by applications spin up by docker-compose up.

What is the proper way of using docker-compose up with varying configuration settings?

I don't want to use .env & environment: config as the environment variables are changing frequently & it is insecure to save tokens in a file.

docker-compose run -e does work a bit, but loses many. It does not map the ports that defined in docker-compose.yml services. Also multiple services are defined in docker-compose.yml and I don't want to use depends_on just because docker-compose up doesn't work.

Let's say I define service in docker-compose.yml

    service-a:
        build:
          context: .
          dockerfile: DockerfileA
        command: node serviceA.js

In my serviceA.js, I simply use the environment variable:

console.log("This is ", process.env.KEY, "running in service A");

When I run docker-compose run -e KEY=DockerComposeRun service-a I do get the environment variable KEY read by serviceA.js

This is  DockerComposeRun running in service A

However I could only get one single service running.


I could have use environment: in docker-compose.yml

environment:
  - KEY=DockerComposeUp

But in my use case, each docker compose would have different environment variable values, meaning I would need to edit the file each time before I do docker-compose.

Also, not only single service would use the same environment variable, .env even done a better job, but it is not desired.


There doesn't seem to be a way to do the same for docker-compose up I have tried KEY=DockerComposeUp docker-compose up, but what I get is undefined .

Export doesn't work for me as well, it seems they are all about using environment variable for docker-compose.yml instead of for the applications in container

like image 278
ShiraishiMai Avatar asked Jan 25 '19 06:01

ShiraishiMai


2 Answers

To safely pass sensitive configuration data to your containers you can use Docker secrets. Everything passed through Secrets is encrypted.

You can create and manage secrets using the commands below:

docker secret create
docker secret inspect
docker secret ls
docker secret rm

And use them in your docker-compose file, either referring to existing secrets (external) or use a file:

secrets:
  my_first_secret:
    file: ./secret_data
  my_second_secret:
    external: true
like image 81
Georgios Mathioudakis Avatar answered Oct 12 '22 10:10

Georgios Mathioudakis


You can use environment like this:

    service-a:
        build:
          context: .
          dockerfile: DockerfileA
        command: node serviceA.js
        environment:
            KEY=DockerComposeRun

Refer at: https://docs.docker.com/compose/environment-variables/

like image 36
Chien Nguyen Avatar answered Oct 12 '22 11:10

Chien Nguyen