We can use variables in our docker-compose.yml
files!
The syntax is: ${SOME_VAR_NAME}
.
These specifically are environment variables.
First, let's set our docker-compose.yml
file to read two variables:
version: '3'
services:
app:
build:
context: ./docker/app
dockerfile: Dockerfile
image: shippingdocker/app:latest
networks:
- appnet
volumes:
- .:/var/www/html
ports:
- ${APP_PORT}:80
working_dir: /var/www/html
cache:
image: redis:alpine
networks:
- appnet
volumes:
- cachedata:/data
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: homestead
MYSQL_USER: homestead
MYSQL_PASSWORD: secret
ports:
- ${DB_PORT}:3306
networks:
- appnet
volumes:
- dbdata:/var/lib/mysql
node:
build:
context: ./docker/node
dockerfile: Dockerfile
image: shippingdocker/node:latest
networks:
- appnet
volumes:
- .:/opt
working_dir: /opt
command: echo hi
networks:
appnet:
driver: bridge
volumes:
dbdata:
driver: local
cachedata:
driver: local
We have APP_PORT
and DB_PORT
.
We can set those in two ways:
First: We can export the variables so they're available to sub-processes:
export APP_PORT=8080
export DB_PORT=33060
# Our `docker-compose.yml` file will use the above variables
docker-compose up -d
Second: We can set them inline as we run the docker-compose
command.
APP_PORT=8080 DB_PORT=33060 docker-compose up -d
.env File
We have another option too! Docker Compose will read a .env
file and import variables from it!
Here's an example .env
file:
APP_PORT=8080
DB_PORT=33060
If that's in the same directory as the docker-compose.yml
file, then we can just run docker-compose
commands, knowing it will pick up those variables:
docker-compose up -d