I would like to be able to use env variables inside docker-compose.yml, with values passed in at the time of docker-compose up. This is the example. I am doing this today with basic docker run command, which is wrapped around my own script. Is there a way to achieve it with compose, without any such bash wrappers?
proxy:
hostname: $hostname
volumes:
- /mnt/data/logs/$hostname:/logs
- /mnt/data/$hostname:/data
template.yml
, which is yourdocker-compose.yml
with environment variable.A new file
docker-compose.yml
will be generated with the correct values of environment variables.Sample template.yml file:
Sample env.sh file:
You cannot ... yet. But this is an alternative, think like a docker-composer.yml generator:
https://gist.github.com/Vad1mo/9ab63f28239515d4dafd
Basically a shell script that will replace your variables. Also you can use Grunt task to build your docker compose file at the end of your CI process.
add env to .env file
Such as
then save it to
deploy.sh
When using environment variables for volumes you need:
create .env file in the same folder which contains
docker-compose.yaml
filedeclare variable in the
.env
file:Change
$hostname
to${HOSTNAME}
atdocker-compose.yaml
fileOf course you can do that dynamically on each build like:
I have a simple bash script I created for this it just means running it on your file before use: https://github.com/antonosmond/subber
Basically just create your compose file using double curly braces to denote environment variables e.g:
Anything in double curly braces will be replaced with the environment variable of the same name so if I had the following environment variables set:
on running
subber docker-compose.yml
the resulting file would look like:The best way is to specify environment variables outside the
docker-compose.yml
file. You can useenv_file
setting, and define your environment file within the same line. Then doing a docker-compose up again should recreate the containers with the new environment variables.Here is how my docker-compose.yml looks like: