📖 Tempo estimado de leitura: 9 min
Extended Berkeley Packet Filter: Fornece funcionalidades avançadas de rede, segurança e observabilidade em ambientes Kubernetes.
Diferente das soluções tradicionais, que dependem de regras de iptables
ou outros métodos menos eficientes, o Cilium opera diretamente no kernel do Linux, proporcionando maior desempenho e flexibilidade.
A importância do Cilium na comunidade Kubernetes foi reforçada com sua recente graduação na Cloud Native Computing Foundation (CNCF) em outubro de 2023. Isso demonstra sua maturidade e crescente adoção em ambientes de produção.
O eBPF é uma tecnologia que permite a execução segura de programas no kernel do Linux sem a necessidade de modificar seu código-fonte ou carregar módulos adicionais. No contexto do Kubernetes, ele possibilita:
*
Gerenciamento eficiente de redes sem depender de iptables
.
*
Monitoramento avançado de tráfego e aplicações.
*
Implementação de políticas de segurança diretamente no kernel.
O Cilium atua como um CNI (Container Network Interface), permitindo:
*
Comunicação entre pods com menor latência.
*
Suporte a balanceamento de carga em camada 4 e 7.
*
Integração nativa com serviços mesh como Istio.
*
Controle de acesso baseado em identidade (Identity-Aware Security Policies).
*
Regras de firewall aplicadas no kernel, reduzindo o overhead de regras tradicionais.
*
Monitoramento detalhado de conexões para evitar tráfego suspeito.
*
Ferramentas integradas para inspeção de tráfego.
*
Exportação de métricas para Prometheus e Grafana.
*
Visão detalhada do comportamento das aplicações em tempo real.
Para instalar o Cilium no seu cluster Kubernetes, siga os passos abaixo.
*
Um cluster Kubernetes funcional (minikube, kind, ou um cluster gerenciado como AKS, EKS, GKE).
*
kubectl
instalado e configurado.
🔶 Dica: Se você está rodando minikube em uma VM, recomendo que tenha pelo menos 4 vCPU e 8GB RAM.
Instalando o kubectl
:
$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
$ sudo install kubectl /usr/local/bin/
Consulte a documentação do cilium para mais informações.
Neste laboratório, usaremos o Minikube. Clique no link para aprender como instalá-lo.
$ cilium install --version 1.17.2
$ kubectl get pods -n kube-system | grep cilium
cilium-ckzz2 1/1 Running 0 86s
cilium-envoy-mxhsl 1/1 Running 0 86s
cilium-operator-799f498c8-lp8rw 1/1 Running 0 86s
Pode demorar uns minutos até os pods inicializarem.
$ kubectl get DaemonSet -n=kube-system
NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
cilium 1 1 1 1 1 kubernetes.io/os=linux 77m
cilium-envoy 1 1 1 1 1 kubernetes.io/os=linux 77m
kube-proxy 1 1 1 1 1 kubernetes.io/os=linux 77m
$ kubectl describe DaemonSet cilium -n=kube-system | grep Status
Pods Status: 1 Running / 0 Waiting / 0 Succeeded / 0 Failed
Verifique os logs:
$ kubectl logs -n kube-system -l k8s-app=cilium
Olhe também os eventos:
$ kubectl get events --sort-by=.metadata.creationTimestamp
Em caso de erros, tente reiniciar o Cilium:
$ kubectl rollout restart ds cilium -n kube-system
Instalar as CLIs do Cilium:
$ CILIUM_CLI_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/cilium-cli/main/stable.txt)
$ CLI_ARCH=amd64
$ if [ "$(uname -m)" = "aarch64" ]; then CLI_ARCH=arm64; fi
$ curl -L --fail --remote-name-all https://github.com/cilium/cilium-cli/releases/download/${CILIUM_CLI_VERSION}/cilium-linux-${CLI_ARCH}.tar.gz{,.sha256sum}
$ sha256sum --check cilium-linux-${CLI_ARCH}.tar.gz.sha256sum
$ sudo tar xzvfC cilium-linux-${CLI_ARCH}.tar.gz /usr/local/bin
$ rm cilium-linux-${CLI_ARCH}.tar.gz{,.sha256sum}
Se tudo estiver correto, você verá os pods do Cilium rodando normalmente.
$ cilium status --wait
Execute o seguinte comando para validar se o cluster tem conectividade de rede adequada:
$ cilium connectivity test
Após alguns minutos, o teste deverá estar concluído.
O Hubble é a camada de observabilidade do Cilium, e pode ser usado para obter visibilidade de todo o cluster Kubernetes nas camadas de rede e segurança.
$ cilium hubble enable
Execute cilium status
para validar se o Hubble está ativado e em execução:
Para acessar os dados de observabilidade coletados pelo Hubble, você deve primeiro instalar o Hubble CLI.
$ HUBBLE_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/hubble/master/stable.txt)
$ HUBBLE_ARCH=amd64
$ if [ "$(uname -m)" = "aarch64" ]; then HUBBLE_ARCH=arm64; fi
$ curl -L --fail --remote-name-all https://github.com/cilium/hubble/releases/download/$HUBBLE_VERSION/hubble-linux-${HUBBLE_ARCH}.tar.gz{,.sha256sum}
$ sha256sum --check hubble-linux-${HUBBLE_ARCH}.tar.gz.sha256sum
$ sudo tar xzvfC hubble-linux-${HUBBLE_ARCH}.tar.gz /usr/local/bin
$ rm hubble-linux-${HUBBLE_ARCH}.tar.gz{,.sha256sum}
$ cilium hubble port-forward &
[1] 47502
$ ℹ️ Hubble Relay is available at 127.0.0.1:4245
$ hubble status
Healthcheck (via localhost:4245): Ok
Current/Max Flows: 4,095/4,095 (100.00%)
Flows/s: 18.82
Connected Nodes: 1/1
Você também pode consultar a API
de fluxo:
$ hubble observe
Instale a aplicação Star Wars Demo para poder executar os próximos testes.
- May the Force be with you.
Vamos emitir algumas solicitações para emular algum tráfego novamente. Essa primeira solicitação é permitida pela política.
Instale apenas a Star Wars Demo, sem criar as políticas, e rode os comandos a seguir.
$ kubectl exec tiefighter -- curl -s -XPOST deathstar.default.svc.cluster.local/v1/request-landing
Ship landed
$ kubectl exec tiefighter -- curl -s -XPUT deathstar.default.svc.cluster.local/v1/exhaust-port
Panic: deathstar exploded
Agora, crie as políticas conforme descrito no link acima, e verifique que alguns acessos serão negados.
$ kubectl exec tiefighter -- curl -s -XPUT deathstar.default.svc.cluster.local/v1/exhaust-port
Access denied
Também podemos ver todos os endpoints gerenciados pelo Cilium (cada pod é representado por um endpoint no Cilium):
$ kubectl get cep --all-namespaces
NAMESPACE NAME SECURITY IDENTITY ENDPOINT STATE IPV4 IPV6
cilium-test-1 client-645b68dcf7-7cxfq 14824 ready 10.0.0.62
cilium-test-1 client2-66475877c6-2f8r5 36115 ready 10.0.0.124
cilium-test-1 echo-same-node-6c98489c8d-62k7b 28856 ready 10.0.0.54
default deathstar-8c4c77fb7-qh765 3898 ready 10.0.0.26
default deathstar-8c4c77fb7-r8hlf 3898 ready 10.0.0.243
default tiefighter 31334 ready 10.0.0.103
default xwing 24825 ready 10.0.0.22
kube-system coredns-668d6bf9bc-dn2v9 54688 ready 10.0.0.71
kube-system hubble-relay-59cc4d545b-wtjdq 2611 ready 10.0.0.142
kube-system hubble-ui-76d4965bb6-x4ng5 8275 ready 10.0.0.38
Habilite a interface do usuário do Hubble executando o seguinte comando:
$ cilium hubble enable --ui
$ cilium hubble ui
ℹ️ Opening "http://localhost:12000" in your browser...
⚠️ IMPORTANTE ⚠️
O Minikube deve ter sido iniciado com a opção --listen-address=0.0.0.0
ou --static-ip <IP>
para que você possa acessar o Huble UI através da rede.
✅ Uma alternativa é utilizar o socat
:
$ sudo apt install socat
$ nohup socat TCP-LISTEN:12001,fork TCP:127.0.0.1:12000 &
Aposto que você não sabia dessa! 😆
Como você já sabe, o Hubble é a ferramenta de observabilidade do Cilium.
Abra o browser na porta http://<IP>:12001/
Rode o teste de conectividade outra vez, e observe o Hubble GUI.
Criando um Pod de Teste:
Use o YAML abaixo para subir um pod de teste.
$ cat cilium-test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
namespace: linuxelite
name: cilium-test-pod
labels:
app: cilium-test
spec:
containers:
- name: busybox
image: busybox
command: ["sleep", "3600"]
restartPolicy: Never
Crie o pod:
$ kubectl create namespace linuxelite
$ kubectl apply -f cilium-test-pod.yaml
$ kubectl -n linuxelite get pods
NAME READY STATUS RESTARTS AGE
cilium-test-pod 1/1 Running 0 18s
Agora, verificamos o tráfego pelo Hubble:
$ kubectl -n linuxelite exec -it cilium-test-pod -- ping google.com
PING google.com (142.251.135.142): 56 data bytes
64 bytes from 142.251.135.142: seq=0 ttl=56 time=9.831 ms
64 bytes from 142.251.135.142: seq=1 ttl=56 time=9.050 ms
64 bytes from 142.251.135.142: seq=2 ttl=56 time=11.945 ms
64 bytes from 142.251.135.142: seq=3 ttl=56 time=6.733 ms
64 bytes from 142.251.135.142: seq=4 ttl=56 time=37.642 ms
Em outra aba do terminal, usamos o Hubble para inspecionar o tráfego:
$ kubectl exec -n kube-system ds/cilium -- cilium monitor --type trace
Defaulted container "cilium-agent" out of: cilium-agent, config (init), mount-cgroup (init), apply-sysctl-overwrites (init), mount-bpf-fs (init), clean-cilium-state (init), install-cni-binaries (init)
Listening for events on 4 CPUs with 64x4096 of shared memory
Press Ctrl-C to quit
time="2025-03-16T23:27:42.731883377Z" level=info msg="Initializing dissection cache..." subsys=monitor
-> endpoint 532 flow 0xcc30b1be , identity host->8275 state new ifindex lxc143c320db00c orig-ip 10.0.0.77: 10.0.0.77:47350 -> 10.0.0.38:8081 tcp SYN
-> stack flow 0x636c3669 , identity 8275->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.38:8081 -> 10.0.0.77:47350 tcp SYN, ACK
-> endpoint 532 flow 0xcc30b1be , identity host->8275 state established ifindex lxc143c320db00c orig-ip 10.0.0.77: 10.0.0.77:47350 -> 10.0.0.38:8081 tcp ACK
-> endpoint 532 flow 0xcc30b1be , identity host->8275 state established ifindex lxc143c320db00c orig-ip 10.0.0.77: 10.0.0.77:47350 -> 10.0.0.38:8081 tcp ACK
-> stack flow 0x636c3669 , identity 8275->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.38:8081 -> 10.0.0.77:47350 tcp ACK
-> stack flow 0x636c3669 , identity 8275->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.38:8081 -> 10.0.0.77:47350 tcp ACK, FIN
-> endpoint 532 flow 0xcc30b1be , identity host->8275 state established ifindex lxc143c320db00c orig-ip 10.0.0.77: 10.0.0.77:47350 -> 10.0.0.38:8081 tcp ACK, FIN
-> endpoint 3213 flow 0x8c0cf16d , identity host->28856 state new ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:38522 -> 10.0.0.54:8181 tcp SYN
-> stack flow 0xbcfe676b , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8181 -> 10.0.0.77:38522 tcp SYN, ACK
-> endpoint 3213 flow 0x8c0cf16d , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:38522 -> 10.0.0.54:8181 tcp ACK
-> endpoint 3213 flow 0x8c0cf16d , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:38522 -> 10.0.0.54:8181 tcp ACK
-> stack flow 0xbcfe676b , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8181 -> 10.0.0.77:38522 tcp ACK
-> endpoint 3213 flow 0x61c76007 , identity host->28856 state new ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:42912 -> 10.0.0.54:8080 tcp SYN
-> stack flow 0xf409f8b1 , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8080 -> 10.0.0.77:42912 tcp SYN, ACK
-> endpoint 3213 flow 0x61c76007 , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:42912 -> 10.0.0.54:8080 tcp ACK
-> stack flow 0xbcfe676b , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8181 -> 10.0.0.77:38522 tcp ACK, FIN
-> endpoint 3213 flow 0x61c76007 , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:42912 -> 10.0.0.54:8080 tcp ACK
-> endpoint 3213 flow 0x8c0cf16d , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:38522 -> 10.0.0.54:8181 tcp ACK, FIN
-> stack flow 0xf409f8b1 , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8080 -> 10.0.0.77:42912 tcp ACK
-> stack flow 0xf409f8b1 , identity 28856->host state reply ifindex 0 orig-ip 0.0.0.0: 10.0.0.54:8080 -> 10.0.0.77:42912 tcp ACK, FIN
-> endpoint 3213 flow 0x61c76007 , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:42912 -> 10.0.0.54:8080 tcp ACK
-> endpoint 3213 flow 0x61c76007 , identity host->28856 state established ifindex lxc40ece8a8f974 orig-ip 10.0.0.77: 10.0.0.77:42912 -> 10.0.0.54:8080 tcp ACK, FIN
Se o Cilium estiver gerenciando a rede corretamente, você verá as conexões do pod de teste sendo registradas no monitor do Cilium.
O Cilium é uma solução poderosa que melhora significativamente a segurança de rede no Kubernetes, em relação as limitações das abordagens tradicionais.
Com suporte ao eBPF e integração com ferramentas de monitoramento, ele se torna uma escolha ideal para clusters modernos.
Se você deseja elevar a segurança e performance do seu ambiente Kubernetes, experimentar o Cilium pode ser um ótimo próximo passo!
Veja também o Cheat Sheet.
Para saber mais, visite a página oficial do Cilium.
Compartilhe este post e continue acompanhando nosso site para mais novidades sobre Kubernetes e tecnologias open-source!
Dê uma olhada nestes outros artigos interessantes! 🔥
Gostou do que encontrou aqui? A cada clique em um banner, você ajuda a manter este site vivo e gratuito. Seu apoio faz toda a diferença para que possamos continuar trazendo conteúdos que você adora. Muito obrigado! 😊