From cb98133717b1c4c8f9e46c95ec7df996deae60e6 Mon Sep 17 00:00:00 2001 From: Felipe Lalanne <1822826+pipex@users.noreply.github.com> Date: Fri, 7 Apr 2023 16:02:54 -0400 Subject: [PATCH] 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 --- src/compose/service.ts | 1 + src/compose/utils.ts | 8 +++++++- test/unit/compose/service.spec.ts | 3 ++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/compose/service.ts b/src/compose/service.ts index 174880ec..f24acb6c 100644 --- a/src/compose/service.ts +++ b/src/compose/service.ts @@ -515,6 +515,7 @@ export class Service { if (_.get(container, 'NetworkSettings.Networks', null) != null) { networks = ComposeUtils.dockerNetworkToServiceNetwork( container.NetworkSettings.Networks, + svc.containerId, ); } diff --git a/src/compose/utils.ts b/src/compose/utils.ts index 1b3fa38f..1b5d89f4 100644 --- a/src/compose/utils.ts +++ b/src/compose/utils.ts @@ -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; diff --git a/test/unit/compose/service.spec.ts b/test/unit/compose/service.spec.ts index 5c4783c1..2d766d14 100644 --- a/test/unit/compose/service.spec.ts +++ b/test/unit/compose/service.spec.ts @@ -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'], }, });