You should use .env
file where you'd put your global environments to be read by compose.
See: https://docs.docker.com/compose/environment-variables/#the-env-file for more information on how to use the file.
Another possible solution would be template.yml
file called with docker-compose
, e.g.:
- Create a
template.yml
, which is your docker-compose.yml
with environment variable.
- Suppose your environment variables are in a file '
env.sh
'
- Put the below piece of code in a sh file and run it.
source env.sh; rm -rf docker-compose.yml; envsubst < "template.yml" > "docker-compose.yml";
A new file docker-compose.yml
will be generated with the correct values of environment variables.
Sample template.yml file:
SampleContainer:
image: myImage:latest
container_name: sample
depends_on:
- mysql-server
restart: always
volumes:
- /opt/docker/myapplication/bootstrap.properties:/opt/myserver/${SERVER_NAME}/bootstrap.properties
Sample env.sh
file:
#!/bin/bash
export SERVER_NAME=jingool
Another options would include:
docker-compose
1.5+ has enabled variables substitution: https://github.com/docker/compose/releases
The latest Docker Compose allows you to access environment variables from your compose file. So you can source your environment variables, then run Compose like so:
set -a
source .my-env
docker-compose up -d
Then you can reference the variables in docker-compose.yml
using ${VARIABLE}
, like so:
/opt/docker/myapplication/bootstrap.properties:/opt/myserver/${SERVER_NAME}/bootstrap.properties
And here is more info from the docs, taken here: https://docs.docker.com/compose/compose-file/#variable-substitution
The BASH way:
Here is a more flexible method using a bash script and a .env
file.
An example .env
file:
EXAMPLE_URL=http://example.com
# Note that the variable below is commented out and will not be used:
# EXAMPLE_URL=http://example2.com
SECRET_KEY=ABDFWEDFSADFWWEFSFSDFM
# You can even define the compose file in an env variable like so:
COMPOSE_CONFIG=my-compose-file.yml
# You can define other compose files, and just comment them out
# when not needed:
# COMPOSE_CONFIG=another-compose-file.yml
then run this bash script in the same directory, which should deploy everything properly:
#!/bin/bash
docker rm -f `docker ps -aq -f name=myproject_*`
set -a
source .env
cat ${COMPOSE_CONFIG} | envsubst | docker-compose -f - -p "myproject" up -d
There's also an interesting read here: https://modulitos.com/2016/03/lets-deploy-part-1/