====== Instalación ====== ===== Todos los nodos ===== En vez de docker usadmos containerd siguiendo esta guia * [[https://web.archive.org/web/20211022163033/https://www.nocentino.com/posts/2021-02-14-installing-and-configuring-containerd-as-a-kubernetes-container-runtime/|https://www.nocentino.com/posts/2021-02-14-installing-and-configuring-containerd-as-a-kubernetes-container-runtime/]] modprobe overlay modprobe br_netfilter cat < ===== Master Node ===== root@kubmaster:~# kubeadm init --pod-network-cidr=10.244.0.0/16 Devuleve algo como [init] Using Kubernetes version: v1.22.3 [preflight] Running pre-flight checks error execution phase preflight: [preflight] Some fatal errors occurred: [ERROR NumCPU]: the number of available CPUs 1 is less than the required 2 [ERROR Mem]: the system RAM (976 MB) is less than the minimum 1700 MB [ERROR Swap]: running with swap on is not supported. Please disable swap [preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...` To see the stack trace of this error execute with --v=5 or higher Entonces se debe asignar al menos 2GB de RAM y 2CPU al nodo master y deshbilitar la swap como se muestra anteriormente. En los nodos cliente 1GB y 1CPU es suficiente. root@kubmaster:~# kubeadm init --pod-network-cidr=10.244.0.0/16 Devuelve algo como . . . [addons] Applied essential addon: kube-proxy Your Kubernetes control-plane has initialized successfully! To start using your cluster, you need to run the following as a regular user: mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config Alternatively, if you are the root user, you can run: export KUBECONFIG=/etc/kubernetes/admin.conf You should now deploy a pod network to the cluster. Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at: https://kubernetes.io/docs/concepts/cluster-administration/addons/ Then you can join any number of worker nodes by running the following on each as root: kubeadm join 192.168.1.241:6443 --token iecdfv.lpvqmxgst4r0j8zh \ --discovery-token-ca-cert-hash sha256:12de3106dffd8bb6ea12d62f5a2fb012e294f39fc0159706491cc555cbbe5617 Ahora se carga todas las variables de nuestro kubernetes con el export o a travez de la creación de el archivo de configuración. Luego creamos el nodo que administrará la red a travez del modulo de flannel que no tiene politicas ni reglas. * https://blog.laputa.io/kubernetes-flannel-networking-6a1cb1f8ec7c * https://github.com/flannel-io/flannel export KUBECONFIG=/etc/kubernetes/admin.conf kubectl get pods --all-namespaces kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml kubectl get nodes kubectl get pods --all-namespaces -o wide kubectl get namespaces kubectl describe node kub3 ===== Nodos ===== Se agregar los nodos al cluster de kubernetes con: kubeadm join 192.168.1.241:6443 --token iecdfv.lpvqmxgst4r0j8zh \ --discovery-token-ca-cert-hash sha256:12de3106dffd8bb6ea12d62f5a2fb012e294f39fc0159706491cc555cbbe5617 ====== Administrando Kubernetes ====== En el master node se administra la infraestructura ===== Creando el primer Pod ===== export KUBECONFIG=/etc/kubernetes/admin.conf kubectl get pods --all-namespaces kubectl get nodes kubectl get pods --all-namespaces -o wide kubectl get namespaces Creamos el primer namespace kubectl create namespace podexample kubectl get namespaces Luego creamos nuestro primer pod usando YAML cat << EOF >> pd.yml apiVersion: v1 kind: Pod metadata: name: examplepod namespace: podexaple spec: volumes: - name: html emptyDir: {} containers: - name: webcontainer image: nginx volumeMounts: - name: html mountPath: /usr/share/nginx/html - name: filecontainer image: debian volumeMounts: - name: html mountPath: /html command: ["/bin/sh", "-c"] args: - while true; do date >> /html/index.html; sleep 1; done EOF kubectl create -f pd.yaml kubectl --namespace=podexample get pods Y verificamos que lo podamos alcanzar curl 10.244.1.6:80 kubectl --namespace=podexample get pods -o wide curl 10.244.3.2:80 Dónde nos tiene que dar la fecha que sirve nuestro pod. Ahora podemos ejecutar un comando dentro de un pod con: kubectl exec -it --namespace=podexample examplepod /bin/bash kubectl exec --namespace=podexaple examplepod -- /bin/bash Y podemos ver el contenido del archivo /etc/resolv.conf /etc/hosts Pj. kubectl exec -it --namespace=podexaple examplepod -- /bin/bash Defaulted container "webcontainer" out of: webcontainer, filecontainer root@examplepod:/# cat /etc/resolv.conf search podexaple.svc.cluster.local svc.cluster.local cluster.local attlocal.net nameserver 10.96.0.10 options ndots:5 ===== Creando el primer ReplicaSet ===== cat << EOF >> replica-example.yaml apiVersion: apps/v1 kind: ReplicaSet metadata: name: frontend labels: app: nginx tier: frontend spec: replicas: 2 selector: matchLabels: tier: frontend matchExpressions: - {key: tier, operator: In, values: [frontend]} template: metadata: labels: app: nginx tier: frontend spec: containers: - name: nginx image: darealmc/nginx-k8s:v1 ports: - containerPort: 80 EOF kubectl create -f replica-example.yaml kubectl get pods kubectl get pods -o wide kubectl describe rs/frontend kubectl get pods kubectl describe pods frontend-asdafe curl 10.244.3.3 kubectl scale rs/frontend --replicas=4 kubectl get pods kubectl get pods -o wide kubectl describe rs/frontend kubectl delete rs/frontend ===== Creando el primer Service ===== Creamos un pods que sea un //Kube-proxy// cat << EOF >> service-example.yaml kind: Service apiVersion: v1 metadata: name: my-awesome-service spec: selector: app: nginx ports: - protocol: TCP port: 32768 targetPort: 80 EOF kubectl create -f service-example.yaml kubectl describe service my-awesome-service curl 10.244.3.3:32678 kubectl scale rs/frontend --replicas=4 kubectl describe service my-awesome-service Tambien se puede crear un servicio type: * **ClusterIP** (default): Obtiene su propia IP y solo es accesible desde el cluster. * **NodePort** : Obtiene un puerto accesible desde cluster y también desde afuera del cluster. Numero de puertos por defecto 30000-32767. * **LoadBalancer** : Se integra con la plataforma de nube publica (amazon, google, azure) ===== Creando el primer Deploy ===== cat << EOF >> deploy-example.yaml apiVersion: apps/v1 kind: Deployment metadata: name: example-deployment labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: darealmc/nginx-k8s:v1 ports: - containerPort: 80 EOF kubectl create -f deploy-example.yaml kubectl get pods kubectl describe service my-awesome-service curl 10.110.89.103:32768 kubectl describe deployment example-deployment kubectl set image deployments.v1.apps/example-deployment nginx=darealmc/nginx-k8s:v2 kubectl describe deployment example-deployment kubectl get services curl 10.110.89.103:32768 ===== Autoscaling ===== * **Horizontal Pod Autoscaling**: Verifica metricas cada 30 segundos * **Vertical Pod Autoscaling**: Producto en etapa Alpha * **Cluster Autoscaling**: Autoscala nodos verifica nodos pending cada 10 segundos Utilizar SIEMPRE resource requests - autoscaling/v1 solo soporta metrica de CPU - autoscaling/v2xx Agrega soporte memoria y metricas personalizadas ====== Componentes ====== ===== Redes ===== Kubernetes tiene 3 tipos de redes: - **Pod network**: 10.0.0.0/16 usa CNI plugins conlas premisas - Todos los nodos tienen que poder hablarse entre ellas - No debe existir ningún tipo de NAT - **Node network** : 192.168.0.0/16 no es implementado por k8s - **Service network** : 172.11.11.0/24 administrada por el kube-proxy via reglas de ipvs(k8s 1.11)/iptables(k8s 1.2 y no esta diseñado para balanceo) y proveen IP y nombre estables y proveen algun tipo de balanceo ===== Almacenamiento ===== Requerimientos de almacenamiento fundamentales: * Velocidad * Replicado * Resistencia * .... Uno puede traer su propio arreglo y k8s solo lo consume a travez del Container Storage Interface (CSI). Componentes de almacenamiento en k8s: - PersistentVolume (PV) : Ejemplo SSD de 20GB. - PersistentVolumeClaim (PVC) : Ticket de aplicacion para usarlo. - StorageClass (SV) : Implementar todo de forma dinámica. ===== Implementación ===== Se pueden utilizar tres objetos de implementación: * Deployment (deploy) * Demon Set (dc) * StatefulSet (sts) Los cuales tienen cualidades de auto escalado de los nodos, etc. ===== Adicionales ===== * https://rancher.com/ Sistema web de kubernetes