0
0
DockerHow-ToBeginner · 4 min read

How to Use Multiple Compose Files in Docker

Use the -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.
bash
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.

yaml
### 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.

bash
### 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 up
📊

Quick Reference

OptionDescription
-f Specify a Compose file to use; can be repeated to merge multiple files
upCreate and start containers
--buildBuild images before starting containers
-dRun containers in detached mode (in background)

Key Takeaways

Use multiple -f options to combine Compose files in order.
Later Compose files override or extend settings from earlier ones.
Always specify all Compose files explicitly to avoid using defaults only.
Check Compose file versions and structure for compatibility.
Use docker-compose -f file1.yml -f file2.yml up to start merged services.