How to provide an environment variable to a composed container?

The mysql image requires a MYSQL_ROOT PASSWORD. With docker run, this is simple:

docker run -d -e 'MYSQL_ROOT_PASSWORD=whatever' mysql

However, I am creating the mysql container with a docker-compose.yml file. That said, I still want to enable the user to specify their MYSQL_ROOT_PASSWORD when they run:

docker-compose up

e.g., some equivalent of this (which doesn’t work):

docker-compose up -e 'MYSQL_ROOT_PASSWORD=whatever'

Anybody know how to do this?

The way I like to do it is this:

echo 'MYSQL_ROOT_PASSWORD=whatever' > .env

and then in the docker-compose.yml:

    image: mysql
    env_file: .env
1 Like

I was thinking about using the env_file functionality, but using it in combination with echo is a lot better than what I had in mind :slight_smile: I think this might be a suitable solution, even if it does result in the MySQL root password being housed in a plaintext file on the docker host.

The dirty secret about secrets is that if they have to be readable somewhere. You could always remove the .env file immediately after calling the docker-compose command.

Seems like that’d be an issue for future recreation of the containers with docker-compose up, though. You’d have to remember to make that .env file every time before you run it, or the mysql run would fail.