@@ -186,6 +186,24 @@ func newContainerHandler(
186186 return nil , fmt .Errorf ("failed to inspect container %q: %v" , id , err )
187187 }
188188
189+ // Obtain the IP address for the container.
190+ var ipAddress string
191+ if ctnr .NetworkSettings != nil && ctnr .HostConfig != nil {
192+ c := ctnr
193+ if ctnr .HostConfig .NetworkMode .IsContainer () {
194+ // If the NetworkMode starts with 'container:' then we need to use the IP address of the container specified.
195+ // This happens in cases such as kubernetes where the containers doesn't have an IP address itself and we need to use the pod's address
196+ containerID := ctnr .HostConfig .NetworkMode .ConnectedContainer ()
197+ c , err = client .ContainerInspect (context .Background (), containerID )
198+ if err != nil {
199+ return nil , fmt .Errorf ("failed to inspect container %q: %v" , containerID , err )
200+ }
201+ }
202+ if nw , ok := c .NetworkSettings .Networks [c .HostConfig .NetworkMode .NetworkName ()]; ok {
203+ ipAddress = nw .IPAddress
204+ }
205+ }
206+
189207 // Do not report network metrics for containers that share netns with another container.
190208 includedMetrics := common .RemoveNetMetrics (metrics , ctnr .HostConfig .NetworkMode .IsContainer ())
191209
@@ -195,6 +213,7 @@ func newContainerHandler(
195213 storageDriver : storageDriver ,
196214 fsInfo : fsInfo ,
197215 rootfsStorageDir : rootfsStorageDir ,
216+ ipAddress : ipAddress ,
198217 envs : make (map [string ]string ),
199218 labels : ctnr .Config .Labels ,
200219 image : ctnr .Config .Image ,
@@ -224,21 +243,6 @@ func newContainerHandler(
224243 handler .labels ["restartcount" ] = strconv .Itoa (ctnr .RestartCount )
225244 }
226245
227- // Obtain the IP address for the container.
228- // If the NetworkMode starts with 'container:' then we need to use the IP address of the container specified.
229- // This happens in cases such as kubernetes where the containers doesn't have an IP address itself and we need to use the pod's address
230- ipAddress := ctnr .NetworkSettings .IPAddress
231- networkMode := string (ctnr .HostConfig .NetworkMode )
232- if ipAddress == "" && strings .HasPrefix (networkMode , "container:" ) {
233- containerID := strings .TrimPrefix (networkMode , "container:" )
234- c , err := client .ContainerInspect (context .Background (), containerID )
235- if err != nil {
236- return nil , fmt .Errorf ("failed to inspect container %q: %v" , containerID , err )
237- }
238- ipAddress = c .NetworkSettings .IPAddress
239- }
240- handler .ipAddress = ipAddress
241-
242246 if includedMetrics .Has (container .DiskUsageMetrics ) {
243247 handler .fsHandler = & FsHandler {
244248 FsHandler : common .NewFsHandler (common .DefaultPeriod , rootfsStorageDir , otherStorageDir , fsInfo ),
0 commit comments