@@ -186,6 +186,26 @@ 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+ for n , nw := range c .NetworkSettings .Networks {
203+ if n == c .HostConfig .NetworkMode .NetworkName () {
204+ ipAddress = nw .IPAddress
205+ }
206+ }
207+ }
208+
189209 // Do not report network metrics for containers that share netns with another container.
190210 includedMetrics := common .RemoveNetMetrics (metrics , ctnr .HostConfig .NetworkMode .IsContainer ())
191211
@@ -195,6 +215,7 @@ func newContainerHandler(
195215 storageDriver : storageDriver ,
196216 fsInfo : fsInfo ,
197217 rootfsStorageDir : rootfsStorageDir ,
218+ ipAddress : ipAddress ,
198219 envs : make (map [string ]string ),
199220 labels : ctnr .Config .Labels ,
200221 image : ctnr .Config .Image ,
@@ -224,21 +245,6 @@ func newContainerHandler(
224245 handler .labels ["restartcount" ] = strconv .Itoa (ctnr .RestartCount )
225246 }
226247
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-
242248 if includedMetrics .Has (container .DiskUsageMetrics ) {
243249 handler .fsHandler = & FsHandler {
244250 FsHandler : common .NewFsHandler (common .DefaultPeriod , rootfsStorageDir , otherStorageDir , fsInfo ),
0 commit comments