How to Use Multiple Compose Files in Docker
-f option with docker-compose to specify multiple Compose files. Docker merges these files in order, allowing you to override or extend services by running docker-compose -f docker-compose.yml -f docker-compose.override.yml up.Syntax
The basic syntax to use multiple Docker Compose files is by adding multiple -f flags followed by the file names. Docker Compose merges these files in the order they are listed, where later files override or add to the earlier ones.
docker-compose: The command to run Docker Compose.-f file1.yml: Specifies the first Compose file.-f file2.yml: Specifies the second Compose file to merge.up: Starts the containers as defined.
docker-compose -f docker-compose.yml -f docker-compose.override.yml up
Example
This example shows how to use a base Compose file and an override file to add an environment variable and change the port mapping.
### docker-compose.yml version: '3.8' services: web: image: nginx:alpine ports: - "80:80" ### docker-compose.override.yml version: '3.8' services: web: environment: NGINX_HOST: localhost ports: - "8080:80"
Common Pitfalls
One common mistake is not specifying the -f option for all Compose files, which causes Docker Compose to use only the default docker-compose.yml. Another issue is the order of files: the last file overrides previous settings, so putting files in the wrong order can lead to unexpected configurations.
Also, ensure that the Compose files are compatible in version and structure to avoid merge errors.
### Wrong usage (only default file used)
docker-compose up
### Correct usage (multiple files merged)
docker-compose -f docker-compose.yml -f docker-compose.override.yml upQuick Reference
| Option | Description |
|---|---|
| -f | Specify a Compose file to use; can be repeated to merge multiple files |
| up | Create and start containers |
| --build | Build images before starting containers |
| -d | Run containers in detached mode (in background) |
Key Takeaways
-f options to combine Compose files in order.docker-compose -f file1.yml -f file2.yml up to start merged services.