Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Cloud Container Engine/ User Guide/ Network/ Container Network/ Pod Network Settings/ Configuring Network Policies to Restrict Pod Access

Configuring Network Policies to Restrict Pod Access

Updated on 2025-02-18 GMT+08:00

Network policies are designed by Kubernetes to restrict pod access. It is equivalent to a firewall at the application layer to enhance network security. The capabilities supported by network policies depend on the capabilities of the network add-ons of the cluster.

By default, if a namespace does not have any policy, pods in the namespace accept traffic from any source and send traffic to any destination.

The following selectors are available for network policies:

  • namespaceSelector: selects particular namespaces for which all pods should be allowed as ingress sources or egress destinations.
  • podSelector: selects particular pods in the same namespace as the network policy which should be allowed as ingress sources or egress destinations.
  • IPBlock: selects particular IP blocks to allow as ingress sources or egress destinations.

Relationships Between Network Policies and Cluster Types

Cluster Type

CCE Standard Cluster

CCE Turbo Cluster

Network Model

Tunnel

Cloud Native Network 2.0

NetworkPolicy

Enabled by default

Disabled by default (To use network policies, enable DataPlane V2 when creating a cluster.)

Data plane implementation

OpenvSwitch

eBPF

Cluster version for inbound rules

All versions

v1.27.16-r10, v1.28.15-r0, v1.29.10-r0, v1.30.6-r0, or later

Cluster version for outbound rules

v1.23 and later

Selector for inbound rules

namespaceSelector

podSelector

namespaceSelector

podSelector

IPBlock

Selector for outbound rules

namespaceSelector

podSelector

IPBlock

Supported OS

EulerOS

CentOS

HCE 2.0

HCE 2.0

IPv6 network policies

Not supported

Supported

Secure containers

Not supported

Not supported

IPBlock scope

Not limited

Only IP blocks outside the cluster (The configuration for container CIDR blocks and node IP addresses does not take effect.)

Limit ClusterIP access through workload labels

Not supported

Supported

Limit the internal cloud server CIDR block of 100.125.0.0/16

Supported

Not supported

SCTP

Not supported

Not supported

Always allow access to pods on a node from other nodes

Supported

Supported

Configure EndPort in network policies

Not supported

Not supported

NOTE:
  • Secure containers (such as Kata as the container runtime) are not supported by network policies.
  • If you upgrade a CCE standard cluster with a tunnel network to a version that supports egress rules in in-place mode, the rules will not work because the node OS is not upgraded. In this case, reset the node.
  • When a network policy is enabled for a cluster that uses a tunnel network, the source IP address of a pod accessing the CIDR block of a Service will be recorded in the optional field of the reported IP address data. This enables the configuration of network policy rules on the destination pod, taking into account the source IP address of the pod.

Using Ingress Rules Through YAML

  • Scenario 1: Use a network policy to limit access to a pod to only pods with specific labels.
    Figure 1 podSelector

    The pod labeled with role=db only permits access to its port 6379 from pods labeled with role=frontend. To do so, perform the following operations:

    1. Create the access-demo1.yaml file.
      vim access-demo1.yaml

      File content:

      apiVersion: networking.k8s.io/v1
      kind: NetworkPolicy
      metadata:
        name: access-demo1
        namespace: default
      spec:
        podSelector:                  # The rule takes effect for pods with the role=db label.
          matchLabels:
            role: db
        ingress:                      # This is an ingress rule.
        - from:
          - podSelector:              # Only allow the access of the pods labeled with role=frontend.
              matchLabels:
                role: frontend
          ports:                      # Only TCP can be used to access port 6379.
          - protocol: TCP
            port: 6379
    2. Run the following command to create the network policy based on the access-demo1.yaml file:
      kubectl apply -f access-demo1.yaml

      Expected output:

      networkpolicy.networking.k8s.io/access-demo1 created
  • Scenario 2: Use a network policy to limit access to a pod to only pods in a specific namespace.
    Figure 2 namespaceSelector

    The pod labeled with role=db only permits access to its port 6379 from pods in the namespace labeled with project=myproject. To do so, perform the following operations:

    1. Create the access-demo2.yaml file.
      vim access-demo2.yaml

      File content:

      apiVersion: networking.k8s.io/v1
      kind: NetworkPolicy
      metadata:
        name: access-demo2
      spec:
        podSelector:                  # The rule takes effect for pods with the role=db label.
          matchLabels:
            role: db
        ingress:                      # This is an ingress rule.
        - from:
          - namespaceSelector:        # Only allow the access of the pods in the namespace labeled with project=myproject.
              matchLabels:
                project: myproject
          ports:                      # Only TCP can be used to access port 6379.
          - protocol: TCP
            port: 6379
    2. Run the following command to create the network policy based on the access-demo2.yaml file:
      kubectl apply -f access-demo2.yaml

      Expected output:

      networkpolicy.networking.k8s.io/access-demo2 created

Using Egress Rules Through YAML

NOTE:

The clusters of v1.23 or later using a tunnel network support egress rules.

  • Scenario 1: Use a network policy to limit a pod's access to specific addresses.
    Figure 3 IPBlock

    The pod labeled with role=db only permits access to the 172.16.0.16/16 CIDR block, excluding 172.16.0.40/32 within it. To do so, perform the following operations:

    1. Create the access-demo3.yaml file.
      vim access-demo2.yaml

      File content:

      apiVersion: networking.k8s.io/v1
      kind: NetworkPolicy
      metadata:
        name: access-demo3
        namespace: default
      spec:
        policyTypes:                  # Must be specified for an egress rule.
          - Egress
        podSelector:                  # The rule takes effect for pods with the role=db label.
          matchLabels:
            role: db
        egress:                       # Egress rule
        - to:
          - ipBlock:
              cidr: 172.16.0.16/16    # Allow access to this CIDR block in the outbound direction.
              except:
              - 172.16.0.40/32        # Block access to this address in the CIDR block.
    2. Run the following command to create the network policy based on the access-demo3.yaml file:
      kubectl apply -f access-demo3.yaml

      Expected output:

      networkpolicy.networking.k8s.io/access-demo3 created
  • Scenario 2: Use a network policy to limit access to a pod to only pods with specific labels and this pod can only access specific pods.
    Figure 4 Using both ingress and egress

    The pod labeled with role=db only permits access to its port 6379 from pods labeled with role=frontend, and this pod can only access the pods labeled with role=web. You can use the same rule to configure both ingress and egress in a network policy. To do so, perform the following operations:

    1. Create the access-demo4.yaml file.
      vim access-demo2.yaml

      File content:

      apiVersion: networking.k8s.io/v1
      kind: NetworkPolicy
      metadata:
        name: access-demo4
        namespace: default
      spec:
        policyTypes:
        - Ingress
        - Egress
        podSelector:                  # The rule takes effect for pods with the role=db label.
          matchLabels:
            role: db
        ingress:                      # This is an ingress rule.
        - from:
          - podSelector:              # Only allow the access of the pods labeled with role=frontend.
              matchLabels:
                role: frontend
          ports:                      # Only TCP can be used to access port 6379.
          - protocol: TCP
            port: 6379
        egress:                       # Egress rule
        - to:
          - podSelector:              # Only pods with the role=web label can be accessed.
              matchLabels:
                role: web
    2. Run the following command to create the network policy based on the access-demo4.yaml file:
      kubectl apply -f access-demo4.yaml

      Expected output:

      networkpolicy.networking.k8s.io/access-demo4 created

Creating a Network Policy on the Console

  1. Log in to the CCE console and click the cluster name to access the cluster console.
  2. Choose Policies in the navigation pane, click the Network Policies tab, and click Create Network Policy in the upper right corner.

    • Policy Name: Specify a network policy name.
    • Namespace: Select a namespace in which the network policy is applied.
    • Selector: Enter a label, select the pod to be associated, and click Add. You can also click Reference Workload Label to use the label of an existing workload.
    • Inbound Rule: Click to add an inbound rule. For details about parameter settings, see Table 1.

      Table 1 Adding an inbound rule

      Parameter

      Description

      Protocol & Port

      Select the protocol type and port. Currently, TCP and UDP are supported.

      Source Namespace

      Select a namespace whose objects can be accessed. If this parameter is not specified, the object belongs to the same namespace as the current policy.

      Source Pod Label

      Allow accessing the pods with this label. If this parameter is not specified, all pods in the namespace can be accessed.

    • Outbound Rule: Click to add an outbound rule. For details about parameter settings, see Table 2.

      Table 2 Adding an outbound rule

      Parameter

      Description

      Protocol & Port

      Select the protocol type and port. Currently, TCP and UDP are supported. If this parameter is not specified, the protocol type is not limited.

      Destination CIDR Block

      Allows requests to be routed to a specified CIDR block (and not to the exception CIDR blocks). Separate the destination and exception CIDR blocks using a vertical bar (|). If there are multiple exception CIDR blocks, separate them using commas (,). For example, 172.17.0.0/16|172.17.1.0/24,172.17.2.0/24 indicates that 172.17.0.0/16 is accessible, but not for 172.17.1.0/24 and 172.17.2.0/24.

      Destination Namespace

      Select a namespace whose objects can be accessed. If this parameter is not specified, the object belongs to the same namespace as the current policy.

      Destination Pod Label

      Allow accessing the pods with this label. If this parameter is not specified, all pods in the namespace can be accessed.

  3. Click OK.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback