Trucs et astuces Kubernetes: modĂšles Kubectl pratiques

Au sein de l'entreprise, nous partageons activement les connaissances que nous avons acquises les uns avec les autres: non seulement sous la forme d'instructions wiki formelles, mais aussi de messages dans Slack (et pour que rien ne se perde, un systÚme de recherche intelligent est fourni, mais c'est une autre histoire ...). Nous avons déjà accumulé un grand nombre de modÚles différents pour les opérations de la console dans Kubernetes avec kubectl. Ils seront discutés dans cet article.







Certaines Ă©quipes peuvent s'avĂ©rer ĂȘtre une routine quotidienne pour certains lecteurs, mais s'il y en a qui dĂ©couvrent de nouvelles choses par elles-mĂȘmes, amĂ©liorant ainsi leur efficacitĂ©, l'objectif de l'article sera atteint.



NB : Certaines des commandes listées ci-dessous ont été compilées par nos ingénieurs, tandis que d'autres ont été trouvées sur Internet. Dans ce dernier cas, ils ont été testés et jugés utiles.



Alors allons-y!



pod'



  1. , pod' --all-namespaces . , — -A ( , Kubernetes 1.15).
  2. pod', (.. Running)?



    kubectl get pods -A --field-selector=status.phase!=Running | grep -v Complete
    






    , --field-selector (. ).
  3. :



    kubectl get no -o json | \
      jq -r '.items | sort_by(.status.capacity.memory)[]|[.metadata.name,.status.capacity.memory]| @tsv'
    


  4. pod' :



    kubectl get po -o json --all-namespaces | \
      jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)'
    


  5. , - DaemonSet - . — , - , DaemonSet':



    ns=my-namespace
    pod_template=my-pod
    kubectl get node | grep -v \"$(kubectl -n ${ns} get pod --all-namespaces -o wide | fgrep ${pod_template} | awk '{print $8}' | xargs -n 1 echo -n "\|" | sed 's/[[:space:]]*//g')\"
    
  6. kubectl top pod', :



    # cpu
    kubectl top pods -A | sort --reverse --key 3 --numeric
    # memory
    kubectl top pods -A | sort --reverse --key 4 --numeric
  7. pod' — , :



    kubectl get pods --sort-by=.status.containerStatuses[0].restartCount






    , (. PodStatus ContainerStatus).




  1. Ingress', pod' . , -o wide:



    kubectl -n jaeger get svc -o wide
    NAME                            TYPE        CLUSTER-IP        EXTERNAL-IP   PORT(S)                                  AGE   SELECTOR
    
    jaeger-cassandra                ClusterIP   None              <none>        9042/TCP                                 77d   app=cassandracluster,cassandracluster=jaeger-cassandra,cluster=jaeger-cassandra


    , , pod'.
  2. pod' limits requests:



    kubectl get pods -n my-namespace -o=custom-columns='NAME:spec.containers[*].name,MEMREQ:spec.containers[*].resources.requests.memory,MEMLIM:spec.containers[*].resources.limits.memory,CPUREQ:spec.containers[*].resources.requests.cpu,CPULIM:spec.containers[*].resources.limits.cpu'


  3. kubectl run ( create, apply, patch) — --dry-run. -o yaml, . :



    kubectl run test --image=grafana/grafana --dry-run -o yaml
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      creationTimestamp: null
      labels:
        run: test
      name: test
    spec:
      replicas: 1
      selector:
        matchLabels:
          run: test
      strategy: {}
      template:
        metadata:
          creationTimestamp: null
          labels:
            run: test
        spec:
          containers:
          - image: grafana/grafana
            name: test
            resources: {}
    status: {}
    


    , / .
  4. - :



    kubectl explain hpa
    
    KIND:     HorizontalPodAutoscaler
    VERSION:  autoscaling/v1
    
    DESCRIPTION:
         configuration of a horizontal pod autoscaler.
    
    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. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    
       spec    <Object>
         behaviour of autoscaler. More info:
         https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status.
    
       status    <Object>
         current information about the autoscaler.


    !




  1. IP- :



    kubectl get nodes -o json | \
      jq -r '.items[].status.addresses[]? | select (.type == "InternalIP") | .address' | \
      paste -sd "\n" -
    


  2. nodePort, :



    kubectl get --all-namespaces svc -o json | \
      jq -r '.items[] | [.metadata.name,([.spec.ports[].nodePort | tostring ] | join("|"))]| @tsv'
    


  3. , CNI (, Flannel), pod' . pod', :



    kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}' | tr " " "\n"
    






  1. pod' c timestamp :



    kubectl -n my-namespace logs -f my-pod --timestamps
    
    2020-07-08T14:01:59.581788788Z fail: Microsoft.EntityFrameworkCore.Query[10100]
    


    , ?
  2. , pod' — --tail:



    kubectl -n my-namespace logs -f my-pod --tail=50
    
  3. pod':



    kubectl -n my-namespace logs -f my-pod --all-containers
    
  4. pod' label':



    kubectl -n my-namespace logs -f -l app=nginx
  5. , , , :



    kubectl -n my-namespace logs my-pod --previous
    




  1. ?



    kubectl get secrets -o json --namespace namespace-old | \
      jq '.items[].metadata.namespace = "namespace-new"' | \
      kubectl create-f  -
    
  2. :



    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/CN=grafana.mysite.ru/O=MyOrganization"
    kubectl -n myapp create secret tls selfsecret --key tls.key --cert tls.crt




Au lieu d'une conclusion - une petite liste de matériaux et de collections similaires trouvés sur Internet:



  • Cheatsheet officiel de la documentation Kubernetes;
  • Une brĂšve introduction pratique et une belle tablette de 2 pages de la Linux Academy pour aider Ă  rĂ©duire le temps des ingĂ©nieurs en herbe:



  • Une trĂšs longue liste de commandes de Blue Matador, divisĂ©e en sections;
  • Une sĂ©lection de liens dans l'essentiel vers des tableaux avec des commandes, des articles sur le sujet et quelques commandes;
  • Le rĂ©fĂ©rentiel GitHub Kubernetes-Cheat-Sheet d'un autre passionnĂ© ne contient que des commandes catĂ©gorisĂ©es;
  • Le rĂ©fĂ©rentiel GitHub kubectl-aliases est un paradis pour les abrĂ©viateurs.


PS



Lisez aussi sur notre blog:



  • « Kubernetes kubectl»;
  • « Kubernetes kubectl»;
  • « Kubernetes».



All Articles