Skip to content

Instantly share code, notes, and snippets.

@warlock
Last active December 20, 2022 13:38
Show Gist options
  • Save warlock/8eca692a138a7c5070de0873ca4d4678 to your computer and use it in GitHub Desktop.
Save warlock/8eca692a138a7c5070de0873ca4d4678 to your computer and use it in GitHub Desktop.
Apunts de kubernetes
# hostname per accedir a pods desde pods de diferents namespaces
# service_name.namespace_name.svc.cluster.local
### COMANDES GENERALS
# Obtenir tots els resources del namespace seleccionat
kubectl get all
# Carregar un projecte desde un manifest *
kubectl apply -f manifest.yml
# Eliminar coses amb el manifest *
kubectl delete -f manifest.yml
# info del cluster
kubectl cluster-info
# llistat de coses que es poden demanar/crear
kubectl api-resources
# Obtenir els context
kubectl config get-contexts
# Context actual
kubectl config current-context
# crear un context
kubectl config set-context nom_del_contexte --namespace=nom_namespace --cluster=nom_del_cluster --user=kubernetes-admin
# canviar de context
kubectl config use-context nom_del_contexte
# Setejar un namespace fix ?? revisar
kubectl config set-context --current --namespace=<insert-namespace-name-here>
# Configuracio actual
kubectl config view
# Permet conectarte a zones privades del cluster desde un client
kubectl proxy
# redireccio de ports (investigar)
kubectl port-forward podtest 7000:80
# Fer un pod temporal per remanar dins i al tancar la sessio s'elimina
kubectl run --rm -ti podtest --image=nginx:alpine -- sh
### LLISTAR EINES
kubectl get nodes
kubectl get pods
kubectl get namespaces
kubectl get services
kubectl get replicaset # control de replicacions
kubectl get deployments
kubectl get limitranges # limits als pods
kubectl get resourcequota # limits de namespace
kubectl get configmaps # archius de configuracio carregats
kubectl get secrets
kubectl get pv # persistent volumes (discos durs)
kubectl get pvc # persistent volumes claim (reclamar pv)
kubectl get sc # Storage Class - Creacio de volums dinamics
kubectl get roles # Rols d'access d'usuaris
kubectl get rolebinding # Obtenir les unions de rols i usuaris
kubectl get clusterroles # Rols de control del cluster
kubectl get ing # Ingress que es els sistema de loadbalancer
kubectl get ep # Endpoints son les rutes que utilitza els services
kubectl get sa # ServiceAccount permisos perque el pod pugui preguntar coses del cluster a altres pods
### EXEMPLES DE PODS
# llistar els pods amb info extra
kubectl get pods -o wide
# veure en realtime els pods com es van creant i van fent la seva
kubectl get pods --watch
# llistar els pods amb el label escollit
kubectl get pods -l app=front
# crear un pod desde la consola (No es sol usar)
kubectl run podtest --image=nginx:alpine
# obtenir informacio de un pod
kubectl describe pod podtest
# logs de un pod *
kubectl logs podtest
# eliminar uns pod manualment
kubectl delete pod podtest2 podtest1
# obtenir el manifest de un pod
kubectl get pod podtest -o yaml
# entrar a la shell de un pod
kubectl exec -ti podtest -- sh
# exec container
kubectl exec -it alertmanager-main-0 --container alertmanager -- sh
# Optenir els labels dels pods
kubectl get pods --show-labels
# agregar manualment un label a un pod (cosa lletja)
kubectl label pods my-pod new-label:awesome
### LOGS
# logs de un pod a temps real *
kubectl logs podtest -f
# logs al tenir mes d'un contenidor en un pod (ja t'avisa dels contenidors que tens al demanar el log del pod)
kubectl logs podtest contenidortest
### EXEMPLES REPLICASET
# describe dels replicaset
kubectl describe replicaset rs-test
### EXEMPLES NAMESPACES
# Crear un namespace
kubectl create namespace espai-testing
# Aixi es pot fer un apply a un namespace concret
kubectl -n namespace-testing aply -f manifest.yml
# llistar serveis de un namespace
kubectl -n namespace-testing get services
### DEPLOYMENTS
# llistar els deployments *
kubectl get deployment
# mostar els labels dels deployments *
kubectl get deployment --show-labels
# Per veure el status del deployment o de l'actualitzacio en temps real *
kubectl rollout status deploymnet deployment-test
# Per veure que ha fet el deploment
kubectl describe deployment dp-test
### EXEMPLES ROLLOUT / ROLLBACK
# Veure les versions de deployments en el temps *
kubectl rollout history deployment
# Veure la informacio de la revisio 8 *
kubectl rollout history deployment --revision 8
# El --record guarda la comanda usada en el deploy en el CHANGE-CAUSE
kubectl apply -f mydeploy3.yml --record
# Tornar a la revisio 7 *
kubectl rollout undo deployment dp-test --to-revision=7
### EXEMPLES CONFIGMAP
# Crear ConfigMap de un archiu
kubectl create configmap nginx-config --from-file=configmaps-examples/nginx.conf
# Crear un ConfigMap de varios archius passant la carpeta
kubectl create configmap nginx-config --from-file=configmaps-examples/
# Obtenir info de un configmap
kubectl describe configmaps nginx-config
# Crear un secret generic
kubectl create secret generic name_secret --from-file=./secretfiles/text.txt
# Obtenir els secrets encriptats
kubectl get secrets my name_secret -o yaml
# Canviar politica de PV Retain Recyle Delete
kubectl edit pv pv-test
# Obtenir tipus d'autoritzacio
k cluster-info dump | grep authorization-mode
### CREACIO DE CERTIFICATS D'ACCESS DE USUARIS: CN = USUARI, O = GRUP
### TIP SECRETS: Per substituir envs als archius secrets esta be usar "envsubst"
envsubst < secure.yml > tmp.yaml
apiVersion: v1
kind: Namespace
metadata:
name: testspace
labels:
name: testspace
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: dp-test
namespace: testspace
annotations:
kubernetes.io/change-cause: 'He cambiat el port del pod'
labels:
app: front
spec:
revisionHistoryLimit: 2
replicas: 3
selector:
matchLabels:
app: front
template:
metadata:
name: mypod
labels:
app: front
spec:
containers:
- name: http1
image: python:3.6-alpine
command:
[
'sh',
'-c',
'echo "cont2" > index.html && python -m http.server 8081',
]
- name: http2
image: python:3.6-alpine
command:
[
'sh',
'-c',
'echo "cont1" > index.html && python -m http.server 8082',
]
---
apiVersion: v1
kind: Service
metadata:
name: test-service
namespace: testspace
spec:
type: NodePort
selector:
app: front
ports:
- name: front
protocol: TCP
port: 3000
targetPort: 8081
- name: back
protocol: TCP
port: 3001
targetPort: 8082
---
apiVersion: v1
kind: LimitRange
metadata:
name: mem-limit-range
namespace: testspace
spec:
limits:
- default:
memory: 512Mi
cpu: 0.5
defaultRequest:
memory: 256Mi
type: Container

Agregar certificats que permetin access desde direccions externes

Backup dels certificats

mv /etc/kubernetes/pki/apiserver.{crt,key} ~

Obtenir exemple de configuracio basat en la configuracio actual yaml

kubectl -n kube-system get configmap kubeadm-config -o jsonpath='{.data.ClusterConfiguration}' > kubeadm.yaml

Agregar direccions a certSANS

apiServer:
  certSANs:
  - "192.168.0.69"
  - "zero.servequake.com"
  extraArgs:
    authorization-mode: Node,RBAC
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns:
  type: CoreDNS
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: k8s.gcr.io
kind: ClusterConfiguration
kubernetesVersion: v1.18.2
networking:
  dnsDomain: cluster.local
  serviceSubnet: 10.96.0.0/12
scheduler: {}

Carregar nova configuracio al server per fer els nous certificats

kubeadm init phase certs apiserver --config kubeadm.yaml

instalacio dels container runtimes

https://kubernetes.io/docs/setup/production-environment/container-runtimes

instalacio kubeadm

https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/

desactivar swap per els hypervisors

swapoff -a

Recorda comentar swap a /etc/fstab perque no es monti al reiniciar

Iniciar cluster amb docker

sudo kubeadm init --cri-socket /var/run/dockershim.sock
sudo systemctl daemon-reload && sudo systemctl restart kubelet

autocomplete de terminal bash/zsh...

https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion

https://docs.aws.amazon.com/eks/latest/userguide/dashboard-tutorial.html

Minikube es un kubernetes local per apendre

Iniciar amb el driver docker. Per default es virtualbox

minikube start --vm-driver=docker

Estat del kube

minikube status

Parar el minikube

minikube stop

Activar tunnel

minikube tunnel

Els certificats de kubernetes amb kubeadm s'instalen a /etc/kubernetes/pki

openssl genrsa -out josep.key 2048
openssl req -new -key josep.key -out josep.csr  -subj "/CN=josep/O=dev"
sudo openssl x509 -req -in josep.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out josep.crt -days 500
openssl x509 -in josep.crt -noout -text

"Loguejarse"

kubectl config set-cluster kubernetes --server=https://192.168.0.69:8443 --certificate-authority=ca.crt
kubectl config set-credentials josep --client-certificate=josep.crt --client-key=josep.key
kubectl config set-context josep --cluster=kubernetes --user=josep
kubectl config use-context josep

Que es pot limitar?

  • Ram en MB GB...
  • CPU en 1 cores i se li pot donar fins a una milena part

Parametres

  • Limits: El maxim que no es pot superar
  • Rquest: Lo minim necesari per poder arrancar el pod
kubectl create secret docker-registry gitlab-auth \
--docker-server=https://registry.gitlab.com \
--docker-username=xxx \
--docker-password=xxx \
--docker-email=xxx
--namespace=espai
k patch serviceaccount default -p '{"imagePullSecrets": [{"name": "gitlab-auth"}]}' --namespace=espai
build:
only:
refs:
- master
image: docker:19.03.8
stage: build
services:
- docker:19.03.8-dind
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment