Políticas de Rede em Contêineres
Implemente políticas de rede no Kubernetes para controlar o fluxo de tráfego entre pods, reforçando a segurança e o isolamento.
Políticas de Rede em Contêineres é uma aula grátis de Linux Networking & TCP/IP for Developers no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Linux Networking & TCP/IP for Developers, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Linux Networking & TCP/IP for Developers inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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/egressrules: 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
- EgressControlling 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: 80Controlling 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: 5432Example: 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 allowedExample: 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: 80Policy 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
podSelectorto target pods and defineingress/egressrules. - 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!
Perguntas Frequentes
A aula “Políticas de Rede em Contêineres” é grátis?
Sim — o texto completo de “Políticas de Rede em Contêineres” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Linux Networking & TCP/IP for Developers, atualize para CoddyKit PRO. O curso de Linux Networking & TCP/IP for Developers inclui 4 aulas no total.
O que vou aprender em “Políticas de Rede em Contêineres”?
Implemente políticas de rede no Kubernetes para controlar o fluxo de tráfego entre pods, reforçando a segurança e o isolamento. Você pratica Linux Networking & TCP/IP for Developers com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Linux Networking & TCP/IP for Developers?
Nenhuma experiência prévia é necessária. Linux Networking & TCP/IP for Developers no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Políticas de Rede em Contêineres”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Linux Networking & TCP/IP for Developers?
Sim. Cada aula de Linux Networking & TCP/IP for Developers inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Modos de Rede do Docker
- Fundamentos de Redes do Kubernetes
- Políticas de Rede em Contêineres
- Descoberta de serviços e DNS no Kubernetes