Review whether workload host_port is needed

Configure node port mappings and access scope only when host_port is required.

Description

host_port maps a container port to a port on the node. Omitting it is valid for ordinary pods, and declaring container_port does not expose an arbitrary host port. This is a different feature from a Service’s NodePort.

Use it only when direct node-port binding is needed, and review port conflicts, scheduling constraints and actual network exposure.

Potential impact

  • Adding an unnecessary host_port can increase node service exposure and port conflicts.
  • A function requiring direct node access can fail when mappings or firewalls are incorrect.

Remediation

  • Use the required Service or Ingress exposure path without host_port for ordinary services. Specify host_port and its protocol only when direct node-port mapping is necessary.
  • Verify the application’s actual listening port, node networking and firewalls, and scheduling conflicts. Declaring container_port does not change the application’s listening port.

Examples

These examples require separate nginx configuration to listen on 8080. The declaration alone does not change the default image’s listening port. The after example illustrates a required node mapping, not a general security improvement. Use a maintained image.

Before

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "app"
  }

  spec {
    container {
      name  = "web"
      image = "nginx:1.7.9"

      port {
        container_port = 8080
      }
    }
  }
}

After

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "app"
  }

  spec {
    container {
      name  = "web"
      image = "nginx:1.7.9"

      port {
        container_port = 8080
        host_port      = 8080
      }
    }
  }
}

Explanation:

  • Before: Only the container port is declared; no host_port mapping is requested. This can be an ordinary valid configuration.
  • After: Node port 8080 is mapped to container port 8080. Use this only when direct node access is required.

References