Merge and output config from multiple Compose files
In this step, you will learn how to merge configurations from multiple Docker Compose files and output the final combined configuration. This is a powerful feature that allows you to define a base configuration and then override or extend it with additional files, which is useful for managing different environments (e.g., development, staging, production).
We will continue working in the ~/project directory. In the previous step, we created a docker-compose.yaml file. Now, let's create another Compose file to extend the base configuration. We'll name it docker-compose.override.yaml.
nano ~/project/docker-compose.override.yaml
Paste the following content into the docker-compose.override.yaml file:
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "8080:80"
volumes:
- ./html:/usr/share/nginx/html
This override file modifies the web service defined in docker-compose.yaml. It changes the host port mapping from 80 to 8080 and adds a volume mount to serve static HTML content from a local directory named html.
Save the file by pressing Ctrl + X, then Y, and Enter.
Now, let's create the html directory and a simple index.html file within it.
mkdir ~/project/html
nano ~/project/html/index.html
Paste the following content into ~/project/html/index.html:
<h1>Hello from Nginx!</h1>
Save the file by pressing Ctrl + X, then Y, and Enter.
By default, Docker Compose automatically looks for docker-compose.yaml and docker-compose.override.yaml in the current directory and merges them. The configurations in the override file take precedence.
To see the merged configuration, make sure you are in the ~/project directory and run the docker-compose config command again.
cd ~/project
docker-compose config
You should now see the combined configuration, where the web service has the port mapping 8080:80 and the volume mount ./html:/usr/share/nginx/html.
You can also explicitly specify which Compose files to use with the -f flag. The order in which you specify the files matters, as later files override earlier ones.
For example, to explicitly merge docker-compose.yaml and docker-compose.override.yaml, you can run:
docker-compose -f docker-compose.yaml -f docker-compose.override.yaml config
This will produce the same merged output as running docker-compose config without the -f flag in this case, because docker-compose.override.yaml is automatically detected and merged after docker-compose.yaml.