0Pricing
Linux Networking & TCP/IP for Developers · Урок

Сетевые политики в контейнерах

Реализуйте сетевые политики в Kubernetes для управления потоками трафика между подами, повышая безопасность и изоляцию

«Сетевые политики в контейнерах» — бесплатный урок Linux Networking & TCP/IP for Developers на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Linux Networking & TCP/IP for Developers, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Linux Networking & TCP/IP for Developers содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Network Policies?

In Kubernetes, Network Policies are like firewalls for your pods. They control how groups of pods communicate with each other and with external network endpoints.

Think of them as a security layer that defines which connections are allowed or denied, enhancing isolation and security.

Why Use Network Policies?

Without Network Policies, all pods in a Kubernetes cluster can communicate with each other by default. This can be a significant security risk!

  • Isolation: Prevent unauthorized access between different application tiers (e.g., frontend talking directly to a sensitive database).
  • Security: Reduce the attack surface by only allowing necessary connections.
  • Compliance: Help meet regulatory requirements for network segmentation.

How Network Policies Function

Network Policies work by selecting specific pods and then defining rules for allowed inbound (ingress) and outbound (egress) traffic for those pods.

They are enforced by the cluster's Container Network Interface (CNI) plugin (like Calico or Cilium). If no policy selects a pod, all traffic to/from it is allowed by default.

Policy Structure: The Basics

A Network Policy is a Kubernetes resource defined in YAML. It specifies:

  • podSelector: Which pods the policy applies to.
  • policyTypes: Whether the policy affects ingress, egress, or both.
  • ingress/egress rules: The specific allowed connections.

Here's the basic YAML structure:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-policy
  namespace: default
spec:
  # ... rules go here ...

Targeting Pods with Selectors

The podSelector is crucial. It uses labels to identify the pods that this policy will apply to.

If podSelector is empty {}, the policy applies to ALL pods in its namespace. If omitted, the policy applies to no pods.

The policyTypes field specifies if the policy governs `Ingress`, `Egress`, or both. This helps the network plugin know which traffic directions to enforce.

spec:
  podSelector:
    matchLabels:
      app: my-app
      tier: backend
  policyTypes:
    - Ingress
    - Egress

Controlling Inbound Traffic (Ingress)

Ingress rules define what traffic is allowed to enter the selected pods. If an ingress rule is present, only traffic matching that rule is permitted; all other ingress traffic is denied.

You can specify allowed traffic based on:

  • from: The source of the traffic (e.g., IP block, namespace, or other pods).
  • ports: Specific destination ports on the selected pods.
ingress:
  - from:
      - podSelector:
          matchLabels:
            app: frontend
    ports:
      - protocol: TCP
        port: 80

Controlling Outbound Traffic (Egress)

Egress rules define what traffic is allowed to leave the selected pods. Similar to ingress, if an egress rule is present, only traffic matching that rule is permitted; all other egress traffic is denied.

You can specify allowed traffic based on:

  • to: The destination of the traffic (e.g., IP block, namespace, or other pods).
  • ports: Specific source ports on the selected pods.
egress:
  - to:
      - ipBlock:
          cidr: 10.0.0.0/24
    ports:
      - protocol: TCP
        port: 5432

Example: Default Deny Ingress

A common security practice is to implement a "default deny" policy. This means no traffic is allowed to a pod unless explicitly permitted.

To achieve this for ingress traffic, create a policy that selects the desired pods but has an empty ingress rule list. This explicitly denies all incoming traffic.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-ingress
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: sensitive-app
  policyTypes:
    - Ingress
  ingress: [] # An empty list means no ingress is allowed

Example: Allow Specific Ingress

After a default deny, you can add more specific policies to allow necessary traffic. Here, we allow backend pods to receive traffic on port 80 from frontend pods.

This policy targets pods with app: backend and permits ingress from pods labeled app: frontend on TCP port 80.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 80

Policy Check

Consider a pod with label app: database. You want to block all incoming traffic to it, except from pods with label app: backend.

Recap: Network Policies

You've learned about Kubernetes Network Policies!

  • They provide firewall-like rules for pods.
  • They use podSelector to target pods and define ingress/egress rules.
  • By default, all pods can communicate; policies enforce restrictions.
  • They are essential for securing and isolating containerized applications.

Keep practicing with different policy rules to master container security!

Часто задаваемые вопросы

Урок «Сетевые политики в контейнерах» бесплатный?

Да — полный текст урока «Сетевые политики в контейнерах» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Linux Networking & TCP/IP for Developers, подпишись на CoddyKit PRO. Курс Linux Networking & TCP/IP for Developers содержит 4 уроков всего.

Чему я научусь в уроке «Сетевые политики в контейнерах»?

Реализуйте сетевые политики в Kubernetes для управления потоками трафика между подами, повышая безопасность и изоляцию Ты практикуешь Linux Networking & TCP/IP for Developers с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Linux Networking & TCP/IP for Developers?

Предыдущий опыт не требуется. Linux Networking & TCP/IP for Developers на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Сетевые политики в контейнерах»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Linux Networking & TCP/IP for Developers?

Да. Каждый урок Linux Networking & TCP/IP for Developers включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Сетевые режимы Docker
  2. Основы сетевого взаимодействия в Kubernetes
  3. Сетевые политики в контейнерах
  4. Обнаружение сервисов и DNS в Kubernetes
← Назад к Linux Networking & TCP/IP for Developers