Apuntes sobre Kubernetes (1)

Algunos apuntes de cosas que he aprendido sobre k8s

Trabajo con los componentes (objetos) del Cluster Kubernetes

  • Configuración imperativa
    • Vamos modificando la configuración de los objetos del Cluster para cubrir nuestro requerimientos.
  • Configuración declarativa
    • Definimos cómo queremos que estén desplegados los objetos en el Cluster
      • manifest (Ficheros que describen los objetos)
      • fichero yaml o json
      • kubectl apply -f file

Comandos kubectl

  • kubectl api-resources [--api-groups=apps]
    • Listado de recursos que pueden ser usados en el Cluster
  • kubectl explain pods
    • Indica los campos que se tienen que usar para definir un pod
  • kubectl explain pods.metadata
    • Indica los campos que podemos o debemos usar en la definición de un Pod
  • kubectl api-versions
    • Indica las versiones de la API disponibles en el Cluster 

Grupos de la API

  • Core (Legacy)
    • Pod
    • Node
    • Namespace
    • PersistentVolume
    • PersistentVolumeClaim
  • Con nombre
    • apps
    • storage.k8s.io
    • rbac.authoeization.k8s.io

 API versionada

Los objetos de la API están versionados y se usa el campo "Version" del objeto para establecerlo. Siguen un ciclo (Alpha (V1Alpha1) --> Beta (v1Beta1) --> Stable (v1))

➜  ~ kubectl explain deployments --api-version apps/v1beta2
KIND:     Deployment
VERSION:  apps/v1beta2

DESCRIPTION:
     DEPRECATED - This group version of Deployment is deprecated by
     apps/v1/Deployment. See the release notes for more information. Deployment
     enables declarative updates for Pods and ReplicaSets.

FIELDS:
   apiVersion <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds

   metadata <Object>
     Standard object metadata.

   spec <Object>
     Specification of the desired behavior of the Deployment.

   status <Object>
     Most recently observed status of the Deployment.

➜  ~ kubectl explain deployments --api-version apps/v1
KIND:     Deployment
VERSION:  apps/v1

DESCRIPTION:
     Deployment enables declarative updates for Pods and ReplicaSets.

FIELDS:
   apiVersion <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds

   metadata <Object>
     Standard object metadata.

   spec <Object>
     Specification of the desired behavior of the Deployment.

   status <Object>
     Most recently observed status of the Deployment.

Llamadas a la API

Core API (Legacy)

http://apiserver:port/api/$VERSION/$RESOURCE_TYPE
http://apiserver:port/api/$VERSION/namespaces/$NAMESPACE/$RESOURCE_TYPE/$RESOURCE_NAME

API Groups

http://apiserver:port/apis/$GROUPNAME/$VERSION/$RESOURCE_TYPE
http://apiserver:port/apis/$GROUPNAME/$VERSION/namespaces/$NAMESPACE/$RESOURCE_TYPE/$RESOURCE_NAME

API Request

Conexión --> Autenticación --> Autorización --> Admission Control

➜  ~ kubectl get pod ms-ui-deployment-5cb6dc96-mqnmf -v 6
I0406 16:59:26.977590   57524 loader.go:359] Config loaded from file:  /Users/sgonzalez/.kube/config
I0406 16:59:27.201778   57524 round_trippers.go:438] GET https://35.241.235.145/api/v1/namespaces/default/pods/ms-ui-deployment-5cb6dc96-mqnmf 200 OK in 218 milliseconds
I0406 16:59:27.204143   57524 get.go:564] no kind "Table" is registered for version "meta.k8s.io/v1beta1" in scheme "k8s.io/kubernetes/pkg/api/legacyscheme/scheme.go:30"
NAME                              READY   STATUS    RESTARTS   AGE
ms-ui-deployment-5cb6dc96-mqnmf   2/2     Running   0          31h



➜  ~ kubectl get pod ms-ui-deployment-5cb6dc96-mqnmf -v 7
I0406 16:59:32.453072   57534 loader.go:359] Config loaded from file:  /Users/sgonzalez/.kube/config
I0406 16:59:32.459789   57534 round_trippers.go:416] GET https://35.241.235.145/api/v1/namespaces/default/pods/ms-ui-deployment-5cb6dc96-mqnmf
I0406 16:59:32.459811   57534 round_trippers.go:423] Request Headers:
I0406 16:59:32.459816   57534 round_trippers.go:426]     Accept: application/json;as=Table;v=v1beta1;g=meta.k8s.io, application/json
I0406 16:59:32.459854   57534 round_trippers.go:426]     User-Agent: kubectl/v1.15.9 (darwin/amd64) kubernetes/2e808b7
I0406 16:59:32.681013   57534 round_trippers.go:441] Response Status: 200 OK in 221 milliseconds
I0406 16:59:32.682067   57534 get.go:564] no kind "Table" is registered for version "meta.k8s.io/v1beta1" in scheme "k8s.io/kubernetes/pkg/api/legacyscheme/scheme.go:30"
NAME                              READY   STATUS    RESTARTS   AGE
ms-ui-deployment-5cb6dc96-mqnmf   2/2     Running   0          31h


➜  ~ kubectl get pod ms-ui-deployment-5cb6dc96-mqnmf -v 8
I0406 17:03:14.917362   57545 loader.go:359] Config loaded from file:  /Users/sgonzalez/.kube/config
I0406 17:03:14.927968   57545 round_trippers.go:416] GET https://35.241.235.145/api/v1/namespaces/default/pods/ms-ui-deployment-5cb6dc96-mqnmf
I0406 17:03:14.928025   57545 round_trippers.go:423] Request Headers:
I0406 17:03:14.928034   57545 round_trippers.go:426]     Accept: application/json;as=Table;v=v1beta1;g=meta.k8s.io, application/json
I0406 17:03:14.928042   57545 round_trippers.go:426]     User-Agent: kubectl/v1.15.9 (darwin/amd64) kubernetes/2e808b7
I0406 17:03:15.184295   57545 round_trippers.go:441] Response Status: 200 OK in 256 milliseconds
I0406 17:03:15.184342   57545 round_trippers.go:444] Response Headers:
I0406 17:03:15.184355   57545 round_trippers.go:447]     Audit-Id: 672754c9-782b-448f-8771-19f138b94712
I0406 17:03:15.184365   57545 round_trippers.go:447]     Content-Type: application/json
I0406 17:03:15.184374   57545 round_trippers.go:447]     Content-Length: 3769
I0406 17:03:15.184383   57545 round_trippers.go:447]     Date: Mon, 06 Apr 2020 16:03:15 GMT
I0406 17:03:15.184500   57545 request.go:947] Response Body: {"kind":"Table","apiVersion":"meta.k8s.io/v1beta1","metadata":{"selfLink":"/api/v1/namespaces/default/pods/ms-ui-deployment-5cb6dc96-mqnmf","resourceVersion":"65563140"},"columnDefinitions":[{"name":"Name","type":"string","format":"name","description":"Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names","priority":0},{"name":"Ready","type":"string","format":"","description":"The aggregate readiness state of this pod for accepting traffic.","priority":0},{"name":"Status","type":"string","format":"","description":"The aggregate status of the containers in this pod.","priority":0},{"name":"Restarts","type":"integer","format":"","description":"The number of times the containers in this pod have been restarted.","priori [truncated 2745 chars]
I0406 17:03:15.186784   57545 get.go:564] no kind "Table" is registered for version "meta.k8s.io/v1beta1" in scheme "k8s.io/kubernetes/pkg/api/legacyscheme/scheme.go:30"
NAME                              READY   STATUS    RESTARTS   AGE

ms-ui-deployment-5cb6dc96-mqnmf   2/2     Running   0          32h


Labels (Etiquetas)

  • Keys --> Pueden tener hasta 63 caracteres
  • Values --> Pueden tener hasta 253 caracteres
uso:
  • kubectl label pod xxxxx stage=pre app=alfresco
  • kubectl label pod xxxxx stage=pro app=alfresco --overwrite
  • kubectl label pod xxxxx stage- (eliminar etiqueta)
  • kubectl get pod --selector stage=pre
  • kubectl get pod -l 'stage in (pre, pro)'
  • kubectl get pod -l 'stage notin (pre, pro)'
Annotations (Anotaciones) - Añadir información adicional a los recursos. No se pueden usar para seleccionar objetos.
  • kubectl annotate pod xxxx prueba=true
  • kubectl annotate pod xxxxx stage=pro --overwrite
  • kubectl annotate pod xxxxx stage- (eliminar etiqueta)

Almacenamiento

Hay mucha documentación sobre cómo usar el almacenamiento en la página oficial de Kubernetes. Aquí sólo hago referencia a los que no sabía o no usaba debidamente.

Provisionamiento dinámico

Hay que definir una "StorageClass" > "PersistentVolumeClaim" > "Volume en un Pod". En este caso no tenemos que aprovisionar el almacenamiento, por ejemplo como discos gcePersistentDisk dado que le solicitamos al Cluster que lo genere para usarlo. 

Si la política de retención se fija como "Delete", al destruir el PVC se destruye el almacenamiento asociado automáticamente. Esto es perfecto para los volúmenes donde hacemos las tareas de backup como por ejemplo generar ficheros tar o algo parecido. Para estos casos también es muy útil hacer uso de los emptyDir como volúmenes.

Planificación (Scheduling)


Nombre
Función
nodeSelector Para asignar pods a nodos en base a las etiquetas asignadas a los nodos
nodeAffinity / AntiAffinity Igual que usar etiquetas pero en base a una expresión (operator: In, etc)
Taint Le indica al scheduler que evite poner pods en algunos nodos.
NoSchedule
PreferNoSchedule
NoExecute
Toleration Le indica al planificador que ignore un taint puesto en un nodo
nodeName Al usar el nodeName en la definición del pod, el pod se ejecutará en el nodo seleccionado


Ejemplo:

kubectl tain node nodo-1 key=SampleTain:NoSchedule
tolerations:
- key: "SampleTain"
  operator: "Exists"
  effect: "NoSchedule"

Drain

Este comando elimina los pods del nodo para hacer un reboot o mantenimiento. Se debe combinar con el comando cordon.

kubectl cordon node1 
kubectl drain node1 --ignore-daemonsets

Comentarios

Entradas populares