Exclude containerId from service network aliases

When getting the service from the docker container, remove the
containerId from the list of aliases (which gets added by docker). This
will make it easier to use the current service state as a target.

This will help us remove the `safeStateClone` function in the API in a
future commit

Change-type: patch
This commit is contained in:
Felipe Lalanne 2023-04-07 16:02:54 -04:00
parent f2ca7dbb6a
commit cb98133717
3 changed files with 10 additions and 2 deletions

View File

@ -515,6 +515,7 @@ export class Service {
if (_.get(container, 'NetworkSettings.Networks', null) != null) {
networks = ComposeUtils.dockerNetworkToServiceNetwork(
container.NetworkSettings.Networks,
svc.containerId,
);
}

View File

@ -496,6 +496,7 @@ export function serviceNetworksToDockerNetworks(
export function dockerNetworkToServiceNetwork(
dockerNetworks: Dockerode.ContainerInspectInfo['NetworkSettings']['Networks'],
containerId: string,
): ServiceConfig['networks'] {
// Take the input network object, filter out any nullish fields, extract things to
// the correct level and return
@ -504,7 +505,12 @@ export function dockerNetworkToServiceNetwork(
_.each(dockerNetworks, (net, name) => {
networks[name] = {};
if (net.Aliases != null && !_.isEmpty(net.Aliases)) {
networks[name].aliases = net.Aliases;
networks[name].aliases = net.Aliases.filter(
// Docker adds the container alias with the container id to the
// list. We don't want that alias to be part of the service config
// in case we want to re-use this service as target
(alias: string) => !containerId.startsWith(alias),
);
}
if (net.IPAMConfig != null) {
const ipam = net.IPAMConfig;

View File

@ -895,7 +895,7 @@ describe('compose/service: unit tests', () => {
IPv6Address: '5.6.7.8',
LinkLocalIps: ['123.123.123'],
},
Aliases: ['test', '1123'],
Aliases: ['test', '1123', 'deadbeef'],
},
}).config.networks,
).to.deep.equal({
@ -903,6 +903,7 @@ describe('compose/service: unit tests', () => {
ipv4Address: '1.2.3.4',
ipv6Address: '5.6.7.8',
linkLocalIps: ['123.123.123'],
// The container id got removed from the alias list
aliases: ['test', '1123'],
},
});