white_gecko
white_gecko

Reputation: 5086

Docker share environment variables using volumes

How can I share environment variables since the --link feature was deprecated? The Docker documentation (https://docs.docker.com/network/links/) states

Warning: The --link flag is a legacy feature of Docker. It may eventually be removed. Unless you absolutely need to continue using it, we recommend that you use user-defined networks to facilitate communication between two containers instead of using --link. One feature that user-defined networks do not support that you can do with --link is sharing environment variables between containers. However, you can use other mechanisms such as volumes to share environment variables between containers in a more controlled way.

But how do I share environment variable by using volumes? I did not find anything about environment variables in the volumes section.

The problem that I have is that I want to set a database password as environment variable when I start the container. Some other container loads data into the database and for that needs to connect to it and provide the credentials. So far the loading container discovered the password on its own by reading the environment variable. How do I do that now without --link?

Upvotes: 1

Views: 1249

Answers (1)

larsks
larsks

Reputation: 312098

Generally, you do it by explicitly providing the same environment variable to other containers. This is easy if you're using a docker-compose.yml to manage your containers, because then you can do this:

version: 3

services:
  database:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD

  frontend:
    image: webserver
    environment:
      MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD

Then if you set MYSQL_ROOT_PASSWORD in your .env file, the same value will be provided to both the database and frontend container. If you're not using docker-compose, you can still simplify things by using an environment file. Create a file named, e.g., database.env that contains:

MYSQL_ROOT_PASSWORD=secret

Then point your containers at that using docker run --env-file database.env ....


You can't share environment variables using volumes, but you can of course share files. So another option would be to have your database container write a file containing the password to a shared volume, and then read that in your other containers.

Upvotes: 1

Related Questions