How can I completely override Docker Compose service ports using a separate file?

0
24
Asked By CuriousDolphin42 On

I'm trying to manage Docker Compose services, and I have a `compose.yml` file for a service that defines some ports:

services:
some-service:
ports:
- 80:80
- 443:443

Now, I want to override this configuration with a `compose.override.yml` to only include:

services:
some-service:
ports:
- 8080:80

However, when I do this, Docker seems to merge the configurations instead of replacing, and I end up with:

services:
some-service:
ports:
- 80:80
- 443:443
- 8080:80

I've also tried using different syntaxes, like:

services:
some-service:
ports: ["8080:80"]

and even:

services:
some-service:
ports: !reset ["8080:80"]

but none of these methods work. The reason I'm using an override file is that I'm not the original author of the `compose.yml` file; it gets updated frequently. What should I do to achieve my desired port configuration? Thanks!

4 Answers

Answered By DockerMaster On

Check out the documentation on merging values in Docker Compose. If you follow this link, you can see some examples about how to properly replace values: https://docs.docker.com/reference/compose-file/merge/#replace-value.

Answered By QuickFixer On

To completely override the ports, you can try setting them explicitly to an empty array or null in your override file like this:

```
ports: []
```

or

```
ports: Null
```
"Does this approach not work for you? It seems like a straightforward fix.

Answered By SyntaxSavant On

If you want to control the ports, editing the files directly is often the most effective method. While using override files is common, sometimes dynamic editing is required. You can use a variable or even a command like `sed` to update the ports in your main file, but honestly, manually setting the configuration is much simpler.

@OP: You might want to try this syntax in your override file:

```
services:
some-service:
ports: !override
- "8080:80"
```

This is valid as per the documentation: https://docs.docker.com/reference/compose-file/merge/#replace-value

HelpfulUser7 -

Just to add, using override files is definitely a widely accepted practice. You should follow the syntax from the docs to ensure proper merging.

Answered By TechWizard88 On

When merging lists in Docker Compose, it can be tricky because by default it appends rather than replaces. If you want to replace the entire list of ports in the override, you'll need to use a specific command. One tool that can help is `yq`. Here's a command you could use to replace your ports:

```
yq -i '.someList = ["8080:80"]' path/to/compose/file.yml
```

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.