如何在多组合Docker Compose文件中覆盖端口配置取消暴露?
As you noted in the Docker Compose documentation:
For the multi-value options ports, expose, external_links, dns, dns_search, and tmpfs, Compose concatenates both sets of values
This is exactly why setting ports: [] in your docker-compose.prod.yml didn't work—it just appended an empty list to the existing 3306:3306 mapping from docker-compose.staging.yml, rather than removing it. Here are two clean ways to solve this without duplicating configuration:
Option 1: Use null to Reset the ports Property (Simplest Fix)
Starting with Docker Compose v2+, you can set a multi-value property to null in an override file to completely clear all previous values from earlier compose files. Update your docker-compose.prod.yml to this:
version: "3.4" services: mysql: ports: null
Now when you run your production command:
docker-compose -f docker-compose.yml -f docker-compose.staging.yml -f docker-compose.prod.yml up -d
The ports: null entry will erase the port mapping from docker-compose.staging.yml, while preserving the build: target: prod configuration you want to reuse from staging.
Option 2: Refactor Configs for Explicit Reuse
If you prefer a more explicit setup that avoids "undoing" settings, split your staging configuration into two separate files to separate shared prod build settings from staging-specific ports:
Create
docker-compose.prod-build.yml(shared between staging and production):version: "3.4" services: mysql: build: target: prodUpdate
docker-compose.staging.ymlto only contain staging-specific settings:version: "3.4" services: mysql: ports: - 3306:3306
Now you can launch each environment without overlapping settings:
- Staging:
docker-compose -f docker-compose.yml -f docker-compose.prod-build.yml -f docker-compose.staging.yml up -d - Production:
docker-compose -f docker-compose.yml -f docker-compose.prod-build.yml up -d
This approach makes your configuration easier to maintain, as each file handles a clear, distinct part of your setup.
内容的提问来源于stack exchange,提问作者Jim Panse

