Skip to content

Instantly share code, notes, and snippets.

@icleitoncosta
Last active June 17, 2023 00:08
Show Gist options
  • Save icleitoncosta/a32fbdeb7517314b22ba5e49a0e1fb1e to your computer and use it in GitHub Desktop.
Save icleitoncosta/a32fbdeb7517314b22ba5e49a0e1fb1e to your computer and use it in GitHub Desktop.
Como configurar um kubernete Cluster e expor em seu domínio

Depois de tantas vezes tentar instalar o kubernetes e ter erro, resolvi criar um tutorial completo, em português, completamente funcional. Nesse tutorial, irei instalar o Kubernetes, os complementos necessários (Ingress, CertManager e Calico), e no final vamos deixar configurado e exposto em um domínio.

  • Vamos preparar nosso VPS:
sudo apt update && sudo apt -y full-upgrade
[ -f /var/run/reboot-required ] && sudo reboot -f
  • Instale kubelet, kubeadm and kubectl
  1. Adicione os repositórios Kubernetes
sudo apt -y install curl apt-transport-https
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list
  1. Instale-os
sudo apt update
sudo apt -y install vim git curl wget kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl
  1. Desabilite o Swap
sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab
sudo swapoff -a
sudo mount -a
free -h
  1. Enable Kernel modules
# Enable kernel modules
sudo modprobe overlay
sudo modprobe br_netfilter

# Add some settings to sysctl
sudo tee /etc/sysctl.d/kubernetes.conf<<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF

# Reload sysctl
sudo sysctl --system
  • Instalando Container Runtime
# Configure persistent loading of modules
sudo tee /etc/modules-load.d/containerd.conf <<EOF
overlay
br_netfilter
EOF

# Load at runtime
sudo modprobe overlay
sudo modprobe br_netfilter

# Ensure sysctl params are set
sudo tee /etc/sysctl.d/kubernetes.conf<<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF

# Reload configs
sudo sysctl --system

# Instalar pacotes obrigatórios
sudo apt install -y curl gnupg2 software-properties-common apt-transport-https ca-certificates

# Add Docker repo
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

# Instale containerd
sudo apt update
sudo apt install -y containerd.io

# Configure containerd e inicie o serviço
sudo su -
mkdir -p /etc/containerd
containerd config default>/etc/containerd/config.toml

# restart containerd
sudo systemctl restart containerd
sudo systemctl enable containerd
systemctl status  containerd
  • Verifique se está tudo carregado, o resultado será como:
$ lsmod | grep br_netfilter
br_netfilter           22256  0 
bridge                151336  2 br_netfilter,ebtable_broute

Habilite o serviço Kubernetes sudo systemctl enable kubelet

  • Configure as imagens do Kubernetes sudo kubeadm config images pull --cri-socket unix:///run/containerd/containerd.sock

  • Inicie e instale de fato o Kubernetes, nesse caso, não irei utilizar um DNS, irei apontar para o própio dominio da maquina, se voce deseja utilizar um DNS, busque por um novo tutorial. sudo sysctl -p sudo kubeadm init --pod-network-cidr=172.24.0.0/16 --cri-socket unix:///run/containerd/containerd.sock

  • Configure através das informações recebidas no seu console, meu exemplo:

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
  • Network Plugin (Calico) Precisamos instalar o Projeto Calico, para que ele gerencie os IPs em nosso Cluster kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.25.1/manifests/tigera-operator.yaml

  • Baixe o arquivo de configuração: curl https://raw.githubusercontent.com/projectcalico/calico/v3.25.1/manifests/custom-resources.yaml -O

  • Edite o arquivo de configuração: vi custom-resources.yaml

Altere a linha do CIDR para que fique dessa forma:

# This section includes base Calico installation configuration.
# For more information, see: https://projectcalico.docs.tigera.io/master/reference/installation/api#operator.tigera.io/v1.Installation
apiVersion: operator.tigera.io/v1
kind: Installation
metadata:
  name: default
spec:
  # Configures Calico networking.
  calicoNetwork:
    # Note: The ipPools section cannot be modified post-install.
    ipPools:
    - blockSize: 26
      cidr: 172.24.0.0/16
      encapsulation: VXLANCrossSubnet
      natOutgoing: Enabled
      nodeSelector: all()

---

# This section configures the Calico API server.
# For more information, see: https://projectcalico.docs.tigera.io/master/reference/installation/api#operator.tigera.io/v1.APIServer
apiVersion: operator.tigera.io/v1
kind: APIServer 
metadata: 
  name: default 
spec: {}
  1. Confirme se está tudo rodando:
kubectl get pods --all-namespaces -w
  • Agora untaint os seus nodes: kubectl taint nodes --all node-role.kubernetes.io/master- kubectl taint nodes --all node-role.kubernetes.io/control-plane-

  • Verifique se o status do node está como Ready Nesse caso, tudo a partir daqui já deve estar funcional. kubectl get nodes -o wide

  • Instale o Cert Manager kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.12.0/cert-manager.yaml

  1. Agora iremos configurar o NGINX Ingress Controller Nesse caso iremos expor apenas o nosso IP para um dominio especifico, e esse dominio deve estar apontado diretamente para o IP do servidor, uma alternativa diferente é necessário usar o MetalLB, mas que não abordarei aqui.
  • Instale o NGINX Ingress controller_tag=$(curl -s https://api.github.com/repos/kubernetes/ingress-nginx/releases/latest | grep tag_name | cut -d '"' -f 4) wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/${controller_tag}/deploy/static/provider/baremetal/deploy.yaml mv deploy.yaml nginx-ingress-controller-deploy.yaml kubectl apply -f nginx-ingress-controller-deploy.yaml

  • Se preferir, atualize o contexto do Kubernetes kubectl config set-context --current --namespace=ingress-nginx

  • Cheque se os controllers forão instalados corretamente. $ kubectl get pods -n ingress-nginx -l app.kubernetes.io/name=ingress-nginx --watch NAME READY STATUS RESTARTS AGE ingress-nginx-admission-create--1-hpkzp 0/1 Completed 0 43s ingress-nginx-admission-patch--1-qnjlj 0/1 Completed 1 43s ingress-nginx-controller-644555766d-snvqf 1/1 Running 0 44s

  1. Configure o NGINX Ingress Controller

Lembrando que essa não é a forma recomendada, só faça se for uma rede privada de Kubernetes. Perceba que nosso Cluster está como NodePort, e não tem um IP externo.

$ kubectl get svc -n ingress-nginx ingress-nginx-controller NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingress-nginx-controller NodePort 10.101.4.21 <none> 80:30248/TCP,443:30773/TCP 3m53s

Crie e edit o IP externo, nesse caso, precisa que seja o mesmo IP onde foi instalado o Kubernetes.

$ vim external-ips.yaml
spec:
  externalIPs:
  - 192.168.42.245

Agora, aplique o path para o serviço kubectl -n ingress-nginx patch svc ingress-nginx-controller --patch "$(cat external-ips.yaml)"

Verifique se foi aplicado o patch com os IP's, corretamente: $ kubectl get svc ingress-nginx-controller -n ingress-nginx NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingress-nginx-controller NodePort 10.101.4.21 192.168.42.245 80:30248/TCP,443:30773/TCP 8m31

Anote o nome dos seus nodes:

$ kubectl get nodes -l node-role.kubernetes.io/control-plane
NAME                         STATUS   ROLES                  AGE   VERSION
k8smaster01.example.com      Ready    control-plane,master   16d   v1.23.5
k8smaster02.example.com      Ready    control-plane,master   16d   v1.23.5

Agora coloque as etiquetas em todos os seus nodes.

kubectl label node k8smaster01.example.com runingress=nginx
kubectl label node k8smaster02.example.com runingress=nginx

Crie um patch para rodar os nodes que tenham a etiqueta:

$ vim node-selector-patch.yaml
spec:
  template:
    spec:
      nodeSelector:
        runingress: nginx

#Aplique o patch
$ kubectl get deploy  -n ingress-nginx
NAME                       READY   UP-TO-DATE   AVAILABLE   AGE
ingress-nginx-controller   1/1     1            1           20m

$ kubectl -n ingress-nginx patch deployment/ingress-nginx-controller --patch "$(cat node-selector-patch.yaml)"
deployment.apps/ingress-nginx-controller patched

No Kubernetes, a configuração padrão é desativar a execução de pods nos nós mestres. Para permitir que os pods de Ingress sejam executados nos nós mestres, você precisará adicionar tolerâncias.

Vamos criar um arquivo de patch para aplicar tolerâncias no deployment do Ingress.

$ vim master-node-tolerations.yaml
spec:
  template:
    spec:
      tolerations:
        - key: node-role.kubernetes.io/master
          operator: Equal
          value: "true"
          effect: NoSchedule
        - key: node-role.kubernetes.io/master
          operator: Equal
          effect: NoSchedule
        - key: node-role.kubernetes.io/control-plane
          operator: Equal
          value: "true"
          effect: NoSchedule
        - key: node-role.kubernetes.io/control-plane
          operator: Equal
          effect: NoSchedule

Aplique o patch kubectl -n ingress-nginx patch deployment/ingress-nginx-controller --patch "$(cat master-node-tolerations.yaml)"

Verifique se foi criado o novo patch kubectl get pods -n ingress-nginx

Pronto, tudo instalado. Agora, só precisa de configurações extras no CertManager, e nas configurações do Ingress, que fica mais fácil de encontrar.

Referências: https://cert-manager.io/docs/installation/ https://computingforgeeks.com/deploy-nginx-ingress-controller-on-kubernetes-using-helm-chart/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment