Herramientas de usuario

Herramientas del sitio


proyectos:linuxservidor-virt-kubernetes

Instalación

Todos los nodos

En vez de docker usadmos containerd siguiendo esta guia

 modprobe overlay
modprobe br_netfilter
 
cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF
 
cat /proc/sys/net/bridge/bridge-nf-call-iptables 
 
cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward                 = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
 
sysctl --system
 
nano /etc/fstab
#Comentamos la linea de montado de swap
swapoff  -a
 
 
apt-get install -y apt-transport-https ca-certificates curl sudo 
 
 
sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg
 echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" |  tee /etc/apt/sources.list.d/kubernetes.list
 
 
sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl
systemctl  status kubelet
systemctl  enable kubelet
systemctl  start kubelet
systemctl  status kubelet
 
root@kubadmin:~# kubeadm version
kubeadm version: &version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.0", GitCommit:"ab69524f795c42094a6630298ff53f3c3ebab7f4", GitTreeState:"clean", BuildDate:"2021-12-07T18:15:11Z", GoVersion:"go1.17.3", Compiler:"gc", Platform:"linux/amd64"}
 
root@kubadmin:~# kubectl  version
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.0", GitCommit:"ab69524f795c42094a6630298ff53f3c3ebab7f4", GitTreeState:"clean", BuildDate:"2021-12-07T18:16:20Z", GoVersion:"go1.17.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.0", GitCommit:"ab69524f795c42094a6630298ff53f3c3ebab7f4", GitTreeState:"clean", BuildDate:"2021-12-07T18:09:57Z", GoVersion:"go1.17.3", Compiler:"gc", Platform:"linux/amd64"}
 
 
 
root@kubadmin:~# dpkg -l|grep kube
hi  kubeadm                       1.23.0-00                      amd64        Kubernetes Cluster Bootstrapping Tool
hi  kubectl                       1.23.0-00                      amd64        Kubernetes Command Line Tool
hi  kubelet                       1.23.0-00                      amd64        Kubernetes Node Agent
ii  kubernetes-cni                0.8.7-00                       amd64        Kubernetes CNI
 
 
kubectl  get pods --all-namespaces -o wide
 
free -m

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.

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

  1. autoscaling/v1 solo soporta metrica de CPU
  2. autoscaling/v2xx Agrega soporte memoria y metricas personalizadas

Componentes

Redes

Kubernetes tiene 3 tipos de redes:

  1. Pod network: 10.0.0.0/16 usa CNI plugins conlas premisas
    1. Todos los nodos tienen que poder hablarse entre ellas
    2. No debe existir ningún tipo de NAT
  2. Node network : 192.168.0.0/16 no es implementado por k8s
  3. 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:

  1. PersistentVolume (PV) : Ejemplo SSD de 20GB.
  2. PersistentVolumeClaim (PVC) : Ticket de aplicacion para usarlo.
  3. 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

proyectos/linuxservidor-virt-kubernetes.txt · Última modificación: por manuel.floresv