@@ -188,6 +188,24 @@ func newContainerHandler(
188188 return nil , fmt .Errorf ("failed to inspect container %q: %v" , id , err )
189189 }
190190
191+ // Obtain the IP address for the container.
192+ var ipAddress string
193+ if ctnr .NetworkSettings != nil && ctnr .HostConfig != nil {
194+ c := ctnr
195+ if ctnr .HostConfig .NetworkMode .IsContainer () {
196+ // If the NetworkMode starts with 'container:' then we need to use the IP address of the container specified.
197+ // 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
198+ containerID := ctnr .HostConfig .NetworkMode .ConnectedContainer ()
199+ c , err = client .ContainerInspect (context .Background (), containerID )
200+ if err != nil {
201+ return nil , fmt .Errorf ("failed to inspect container %q: %v" , containerID , err )
202+ }
203+ }
204+ if nw , ok := c .NetworkSettings .Networks [c .HostConfig .NetworkMode .NetworkName ()]; ok {
205+ ipAddress = nw .IPAddress
206+ }
207+ }
208+
191209 // Do not report network metrics for containers that share netns with another container.
192210 includedMetrics := common .RemoveNetMetrics (metrics , ctnr .HostConfig .NetworkMode .IsContainer ())
193211
@@ -197,6 +215,7 @@ func newContainerHandler(
197215 storageDriver : storageDriver ,
198216 fsInfo : fsInfo ,
199217 rootfsStorageDir : rootfsStorageDir ,
218+ ipAddress : ipAddress ,
200219 envs : make (map [string ]string ),
201220 labels : ctnr .Config .Labels ,
202221 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