Шпаргалка по kubectl

How Pods with resource requests are scheduled

When you create a Pod, the Kubernetes scheduler selects a node for the Pod to
run on. Each node has a maximum capacity for each of the resource types: the
amount of CPU and memory it can provide for Pods. The scheduler ensures that,
for each resource type, the sum of the resource requests of the scheduled
Containers is less than the capacity of the node. Note that although actual memory
or CPU resource usage on nodes is very low, the scheduler still refuses to place
a Pod on a node if the capacity check fails. This protects against a resource
shortage on a node when resource usage later increases, for example, during a
daily peak in request rate.

Примеры: распространенные операции

Посмотрите следующие примеры, чтобы ознакомиться с часто используемыми операциями :

— Внести изменения или обновить ресурс из файла или потока stdin.

— Вывести один или несколько ресурсов.

— Показать подробное состояние одного или нескольких ресурсов, по умолчанию также включаются неинициализированные ресурсы.

Заметка: Как правило, команда используется для получения одного или нескольких ресурсов одного и того же типа. Она поддерживает большой набор флагов, с помощью которых можно настроить формат вывода, например, с помощью флага или .
Вы можете указать флаг или , чтобы отслеживать изменения в конкретном объекте. Команда в основном сфокусирована на описание многих взаимосвязанных аспектов указанного ресурса. При генерации вывода для пользователя она может обращаться к API-серверу. К примеру, команда выдает не только информацию об узле, но и краткий обзор запущенных на нем подов, генерируемых событий и т.д.

— Удалить ресурсы из файла, потока stdin или с помощью селекторов меток, имена, селекторов ресурсов или имен ресурсов.

— Выполнить команду в контейнера пода.

— Вывести логи контейнера в поде.

Exposing the Service

For some parts of your applications you may want to expose a Service onto an
external IP address. Kubernetes supports two ways of doing this: NodePorts and
LoadBalancers. The Service created in the last section already used ,
so your nginx HTTPS replica is ready to serve traffic on the internet if your
node has a public IP.

Let’s now recreate the Service to use a cloud load balancer. Change the of Service from to :

The IP address in the column is the one that is available on the public internet. The is only available inside your
cluster/private cloud network.

Note that on AWS, type creates an ELB, which uses a (long)
hostname, not an IP. It’s too long to fit in the standard
output, in fact, so you’ll need to do to
see it. You’ll see something like this:

Как работает Kubernetes

Согласно концепции контейнеризации, контейнеры содержат выполняемые сервисы, библиотеки и прочие ресурсы, необходимые для работы этих приложений. Доступ к контейнеру извне реализуется через индивидуально назначаемый ему IP-адрес. Таким образом, в Kubernetes контейнер – это программный компонент самого низкого уровня абстракции. Для межпроцессного взаимодействия нескольких контейнеров они инкапсулируются в поды.

Задачей Kubernetes является динамическое распределение ресурсов узла между подами, которые на нем выполняются. Для этого на каждом узле с помощью встроенного агента внутреннего мониторинга Kubernetes cAdvisor ведется непрерывный сбор данных о производительности и использовании ресурсов (время работы центрального процессора, оперативной памяти, нагрузок на файловую и сетевую системы).

Что особенно важно для Big Data проектов, Kubelet – компонент Kubernetes, работающий на узлах, автоматически обеспечивает запуск, остановку и управление контейнерами приложений, организованными в поды. При обнаружении проблем с каким-то подом Kubelet пытается повторно развернуть и перезапустить его на узле

Аналогично HDFS, наиболее популярной распределенной файловой системе для Big Data-решений, реализованной в Apache Hadoop, в кластере Kubernetes каждый узел постоянно отправляет на master диагностические сообщения (heartbeat message). Если по содержанию этих сообщений или в случае их отсутствия мастер обнаруживает сбой какого-либо узла, процесс подсистемы управления Replication Controller пытается перезапустить необходимые поды на другом узле, работающем корректно .


Принципы работы Kubernetes

Примеры использования кубернетис

Поскольку K8s предназначен для управления множеством контейнеризированных микросервисов, неудивительно, что эта технология приносит максимальную выгоду именно в Big Data проектах. Например, кубернетис используют популярный сервис знакомств Tinder , телекоммуникационная компания Huawei , крупнейший в мире онлайн-сервисом поиска автомобильных попутчиков BlaBlaCar , Европейский Центр ядерных исследований (CERN) и множество других компаний, работающих с большими данными и нуждающимися в инструментах быстрого и отказоустойчивого развертывания приложений .

В связи с цифровизацией предприятий и распространением DevOps-подхода, спрос на владение Kubernetes растет и в отечественных компаниях. Как показал обзор вакансий с рекрутинговой площадки HeadHunter, в 2019 году для современного DevOps-инженера и Big Data разработчика данная технология является практически обязательной.


Kubernetes – настоящий must have для современного DevOps-инженера

Источники

  1. https://ru.wikipedia.org/wiki/Kubernetes
  2. https://ru.wikipedia.org/wiki/Docker
  3. https://habr.com/ru/company/flant/blog/327338/
  4. https://habr.com/ru/company/flant/blog/440278/
  5. https://habr.com/ru/company/flant/blog/349940/
  6. https://habr.com/ru/company/flant/blog/345780/
  7. https://habr.com/ru/company/flant/blog/412571/

CustomResourceDefinitions

The CustomResourceDefinition
API resource allows you to define custom resources.
Defining a CRD object creates a new custom resource with a name and schema that you specify.
The Kubernetes API serves and handles the storage of your custom resource.
The name of a CRD object must be a valid
.

This frees you from writing your own API server to handle the custom resource,
but the generic nature of the implementation means you have less flexibility than with
.

Refer to the custom controller example
for an example of how to register a new custom resource, work with instances of your new resource type,
and use a controller to handle events.

Проблема с сертификатами

Сразу обращаю внимание на очень важный момент. Необходимо тем или иным способом настроить мониторинг сертификатов, которые установил и настроил kubespray для обмена информацией мастеров

Сертификатов много и у них срок действия 1 год. Пока сертификаты не просрочились, их относительно легко обновлять. Если упустить этот момент, то все становится сложнее.

Я до конца не понял и не проработал вопрос обновления сертификатов, но это нужно будет сделать. Пока просто покажу, как за ними можно следить.

Сертификат api-server, порт 6443

# echo -n | openssl s_client -connect localhost:6443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not
            Not Before: Sep 18 19:32:42 2019 GMT
            Not After : Sep 17 19:32:42 2020 GMT

Сертификат controller manager, порт 10257.

# echo -n | openssl s_client -connect localhost:10257 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not
            Not Before: Sep 18 18:35:36 2019 GMT
            Not After : Sep 17 18:35:36 2020 GMT

Сертификат scheduler, порт 10259.

# echo -n | openssl s_client -connect localhost:10259 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not
            Not Before: Sep 18 18:35:35 2019 GMT
            Not After : Sep 17 18:35:35 2020 GMT

Это все разные сертификаты и они выпущены на год. Их надо будет не забыть обновить. А вот сертификат для etcd. Он выпущен на 100 лет.

# echo -n | openssl s_client -connect localhost:2379 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not
            Not Before: Sep 18 19:28:50 2019 GMT
            Not After : Aug 25 19:28:50 2119 GMT

Я не понял, почему этого не сделали для всех сервисов, а оставили такой головняк на потом. Если у кого-то есть информация о том, как корректно и безпроблемно обновлять сертификаты, прошу поделиться. Я пока видел только вариант с полуручным обновлением и раскидыванием этих сертификатов по мастерам.

Компоненты узла

Компоненты узла работают на каждом узле, поддерживая работу подов и среды выполнения Kubernetes.

kubelet

Агент, работающий на каждом узле в кластере. Он следит за тем, чтобы контейнеры были запущены в поде.

Утилита kubelet принимает набор PodSpecs, и гарантирует работоспособность и исправность определённых в них контейнеров. Агент kubelet не отвечает за контейнеры, не созданные Kubernetes.

kube-proxy

kube-proxy — сетевой прокси, работающий на каждом узле в кластере, и реализующий часть концепции сервис.

kube-proxy конфигурирует правила сети на узлах. При помощи них разрешаются сетевые подключения к вашими подам изнутри и снаружи кластера.

kube-proxy использует уровень фильтрации пакетов в операционной системы, если он доступен. В противном случае, kube-proxy сам обрабатывает передачу сетевого трафика.

Среда выполнения контейнера

Среда выполнения контейнера — это программа, предназначенная для выполнения контейнеров.

Kubernetes поддерживает несколько сред для запуска контейнеров: Docker,
containerd, ,
и любая реализация Kubernetes CRI (Container Runtime
Interface).

Работа с кластером

Kubectl

Команда создает под именем «minikube».
Этот контекст содержит конфигурацию для взаимодействия с кластером Minikube.

Minikube автоматически устанавливает этот контекст, но если вам потребуется явно использовать его в будущем, выполните команду ниже:

Либо передайте контекст при выполнении команды следующим образом: .

Панель управления

Чтобы получить доступ к веб-панели управления Kubernetes, запустите эту команду в командной оболочке после запуска Minikube, чтобы получить адрес:

Сервисы

Чтобы получить доступ к сервису, открытой через порт узла, выполните команду в командной оболочке после запуска Minikube, чтобы получить адрес:

Configuring DNS for Endpoints

Because the Endpoints service name for the API is in the
domain, you can
use it as the fully qualified domain name (FQDN) by making a small
configuration change in your file. This way, you can
send requests to the sample API by using

instead of the IP address.

To configure Endpoints DNS:

  1. Open your OpenAPI configuration file, , and add the
    property at the top level of the file
    (not indented or nested) as shown in the following snippet:

    host: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog"
    x-google-endpoints:
    - name: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog"
      target: "IP_ADDRESS"
    
  2. In the property, replace
    YOUR_PROJECT_ID with your project ID.
  3. In the property, replace
    IP_ADDRESS with
    the IP address that you used when you sent a request to the sample API.
  4. Deploy your updated OpenAPI configuration file to Service Management:
    gcloud endpoints services deploy openapi.yaml
    

For example, assume the file has the following
configured:

host: "echo-api.endpoints.example-project-12345.cloud.goog"
x-google-endpoints:
- name: "echo-api.endpoints.example-project-12345.cloud.goog"
  target: "192.0.2.1"

When you deploy the file by using the preceding
command, Service Management creates a DNS A-record,
, which resolves to the
target IP address, . It might take a few minutes for the
new DNS configuration to propagate.

Clean up

If you used disposable servers for your cluster, for testing, you can
switch those off and do no further clean up. You can use
to delete your local references to the
cluster.

However, if you want to deprovision your cluster more cleanly, you should
first
and make sure that the node is empty, then deconfigure the node.

Remove the node

Talking to the control-plane node with the appropriate credentials, run:

Before removing the node, reset the state installed by :

The reset process does not reset or clean up iptables rules or IPVS tables. If you wish to reset iptables, you must do so manually:

If you want to reset the IPVS tables, you must run the following command:

Now remove the node:

If you wish to start over, run or with the
appropriate arguments.

Clean up the control plane

You can use on the control plane host to trigger a best-effort
clean up.

See the
reference documentation for more information about this subcommand and its
options.

External etcd nodes

Setting up a cluster with external etcd nodes is similar to the procedure used for stacked etcd
with the exception that you should setup etcd first, and you should pass the etcd information
in the kubeadm config file.

Set up the etcd cluster

  1. Follow these instructions to set up the etcd cluster.

  2. Setup SSH as described .

  3. Copy the following files from any etcd node in the cluster to the first control plane node:

    Replace the value of CONTROL_PLANE with the user@host of the first control-plane node.

Set up the first control plane node

  1. Create a file called with the following contents:

Note: The difference between stacked etcd and external etcd here is that the external etcd setup requires
a configuration file with the etcd endpoints under the object for .
In the case of the stacked etcd topology this is managed automatically.

Replace the following variables in the config template with the appropriate values for your cluster:

The following steps are similar to the stacked etcd setup:

  1. Run on this node.

  2. Write the output join commands that are returned to a text file for later use.

  3. Apply the CNI plugin of your choice. The given example is for Weave Net:

Steps for the rest of the control plane nodes

The steps are the same as for the stacked etcd setup:

  • Make sure the first control plane node is fully initialized.
  • Join each control plane node with the join command you saved to a text file. It’s recommended
    to join the control plane nodes one at a time.
  • Don’t forget that the decryption key from expires after two hours, by default.

OpenAPI specification

Complete API details are documented using OpenAPI.

OpenAPI V2

The Kubernetes API server serves an aggregated OpenAPI v2 spec via the
endpoint. You can request the response format using
request headers as follows:

Header Possible values Notes
not supplying this header is also acceptable
mainly for intra-cluster use
default
serves

Kubernetes implements an alternative Protobuf based serialization format that
is primarily intended for intra-cluster communication. For more information
about this format, see the Kubernetes Protobuf serialization design proposal and the
Interface Definition Language (IDL) files for each schema located in the Go
packages that define the API objects.

OpenAPI V3

FEATURE STATE:

Kubernetes v1.23 offers initial support for publishing its APIs as OpenAPI v3; this is an
alpha feature that is disabled by default.
You can enable the alpha feature by turning on the
feature gate named
for the kube-apiserver component.

With the feature enabled, the Kubernetes API server serves an
aggregated OpenAPI v3 spec per Kubernetes group version at the
endpoint. Please refer to the
table below for accepted request headers.

Header Possible values Notes
not supplying this header is also acceptable
mainly for intra-cluster use
default
serves

A discovery endpoint is provided to see a list of all
group/versions available. This endpoint only returns JSON.

Configuring Endpoints

The sample code includes the OpenAPI configuration file, , which
is based on
.

To configure Endpoints:

  1. In the sample code directory, open the configuration file.

    k8s/openapi.yaml

    View on GitHub

    Note the following:

    • The configuration sample displays the lines near the
      field, which you need to modify. To deploy the file
      to Endpoints, the complete OpenAPI document is required.
    • The example file contains a section for configuring
      authentication that isn’t needed for this tutorial. You don’t need to
      configure the lines with YOUR-SERVICE-ACCOUNT-EMAIL and YOUR-CLIENT-ID.
    • OpenAPI is a language-agnostic specification. The same file is in the sample in each language GitHub
      repository for convenience.
  2. In the field, replace the text with the
    Endpoints service name, which should be in the following format:

    host: "echo-api.endpoints.YOUR_PROJECT_ID.cloud.goog"
    

    Replace YOUR_PROJECT_ID with your Google Cloud project ID. For example:

    host: "echo-api.endpoints.example-project-12345.cloud.goog"
    

Note that
is the Endpoints service name. It isn’t the fully qualified
domain name (FQDN) that you use for sending requests to the API.

For information about the fields in the OpenAPI document that
Endpoints requires, see Configuring
Endpoints.

After you finish all the following configuration steps, and you can
successfully send requests to the sample API using an IP address, see

for information on how to configure
to be the FQDN.

Objectives

Use the following high-level task list as you work through the tutorial. All
tasks in Part 1 are required to successfully send requests to the API.

Part 1

  1. Set up a Google Cloud project. See
    .
  2. Install and configure software used in the tutorial. See
    .
  3. Optionally, download the sample code. See
    .
  4. Download the Kubernetes configuration file. See
    .
  5. Configure the file, which is used to configure
    Endpoints. See
    .
  6. Deploy the Endpoints configuration to create a
    Cloud Endpoints service. See
    .
  7. Create credentials for your Endpoints service. See
    .
  8. Deploy the API and ESP to the cluster. See
    .
  9. Get the service’s external IP address. See
    .
  10. Send a request to the API by using an IP address. See
    .
  11. Track API activity. See
    .

Part 2

  1. Configure a DNS record for the sample API. See
    .
  2. Send a request to the API by using the domain name. See
    .

Cleanup

Endpoints – In Action

Let’s take a look at some endpoints that we’ve used in our previous manifests. Lets deploy this manifest as we did in our previous posts and take a look to see what our endpoints are doing.

We can deploy this manifest running:

Now that its done we should be able to see the endpoints that were automatically created when our service selector matched our pod label. To see this we can query our endpoints through kubectl.

Your results will likely have different addresses than mine, but for reference, here are the endpoints that were returned.

The ingress-nginx endpoint is the one we’re focusing on and you can see it has two endpoints listed, both on port 80.

Now those endpoints should be the IP addresses of our pods that we deployed in our manifest. To test this, lets use the get pods command with the -o wide switch to show more output.

You can see that the IP addresses associated with the pods matches the endpoints. So we proved that the endpoints are matching under the hood.

How about if we want to manually edit our endpoints if we don’t have a selector? Maybe we’re trying to have a resource to access an external service that doesn’t live within our Kubernetes cluster? We could create our own endpoint to do this for us. A great example might be an external database service for our web or app containers.

Let’s look at an example where we’re using an endpoint to access an external resource from a container. In this case we’ll access a really simple web page just for a test. For reference, I accessed this service from my laptop first to prove that it’s working. If you’re doing this in your lab, you’ll need to spin up a web server and modify the IP Addresses accordingly.

I know that it’s not very exciting, but it’ll get the job done. Next up we’ll deploy our Endpoint and a service with no selector. The following manifest should do the trick. Notice the ports used and the IP Address specified in the endpoint.

Then we’ll deploy the manifest file to get our service and endpoint built.

Let’s check the endpoint just to make sure it looks correct.

Once the service and endpoint are deployed, we’ll deploy a quick container into our cluster so we can use it to curl our web page as a test. We’ll use the imperative commands instead of a manifest file this time.

The curl command worked when performing a request against the “external-web” service, so we know it’s working!

Использование Minikube с помощью HTTP-прокси

Minikube создаёт виртуальную машину, включающая в себя Kubernetes и демон Docker.
Когда Kubernetes планирует выполнение контейнеров с использованием Docker, демону Docker может потребоваться доступ к внешней сети для получения контейнеров.

Если вы работаете через HTTP-прокси, вам нужно сконфигурировать настройки прокси для Docker.
Для этого нужно передать необходимые переменные окружения в флаги перед выполнением команды .

Например:

Если адрес вашей виртуальной машины 192.168.99.100, то, скорее всего, настройки прокси помешают обратиться к ней.
Чтобы прокси игнорировал этот IP-адрес, нужно скорректировать настройки no_proxy следующим образом:

Краткое руководство

Эта простая демонстрация поможет запустить, использовать и удалить Minikube на локальной машине. Следуйте перечисленным ниже шагам, чтобы начать знакомство с Minikube.

  1. Запустите Minikube и создайте кластер:

    Вывод будет примерно следующим:

    Дополнительную информацию о запуске кластера в определенной версии Kubernetes, виртуальной машине или среде выполнения контейнера смотрите в разделе .

  2. Теперь вы можете работать со своим кластером через CLI-инструмент kubectl. Для получения дополнительной информации смотрите раздел .

    Давайте создадим развёртывание (Deployment) в Kubernetes, используя существующий образ , представляющий простой HTTP-сервер, и сделаем его доступным на порту 8080 с помощью .

    Вывод будет примерно следующим:

  3. Чтобы получить доступ к объекту Deployment извне, создайте объект сервиса (Service):

    Опция определяет тип сервиса.

    Вывод будет примерно следующим:

  4. Под (Pod) теперь запущен, но нужно подождать, пока он начнёт функционировать, прежде чем обращаться к нему.

    Проверьте, что под работает:

    Если в столбце вывода выводится , значит под все еще создается:

    Если в столбце указано , то под теперь в рабочем состоянии:

  5. Узнайте URL-адрес открытого (exposed) сервиса, чтобы просмотреть подробные сведения о сервисе:

  6. Чтобы ознакомиться с подробной информацией о локальном кластере, скопируйте и откройте полученный из вывода команды на предыдущем шаге URL-адрес в браузере.

    Вывод будет примерно следующим:

    Если сервис и кластер вам больше не нужны, их можно удалить.

  7. Удалите сервис :

    Вывод будет примерно следующим:

  8. Удалите развёртывание :

    Вывод будет примерно следующим:

  9. Остановите локальный кластер Minikube:

    Вывод будет примерно следующим:

    Подробности смотрите в разделе .

  10. Удалите локальный кластер Minikube:

    Вывод будет примерно следующим:

    Подробности смотрите в разделе .

Terminology

For clarity, this guide defines the following terms:

  • Node: A worker machine in Kubernetes, part of a cluster.
  • Cluster: A set of Nodes that run containerized applications managed by Kubernetes. For this example, and in most common Kubernetes deployments, nodes in the cluster are not part of the public internet.
  • Edge router: A router that enforces the firewall policy for your cluster. This could be a gateway managed by a cloud provider or a physical piece of hardware.
  • Cluster network: A set of links, logical or physical, that facilitate communication within a cluster according to the Kubernetes networking model.
  • Service: A Kubernetes Service that identifies a set of Pods using label selectors. Unless mentioned otherwise, Services are assumed to have virtual IPs only routable within the cluster network.

Exposing pods to the cluster

We did this in a previous example, but let’s do it once again and focus on the networking perspective.
Create an nginx Pod, and note that it has a container port specification:

This makes it accessible from any node in your cluster. Check the nodes the Pod is running on:

Check your pods’ IPs:

You should be able to ssh into any node in your cluster and curl both IPs. Note that the containers are not using port 80 on the node, nor are there any special NAT rules to route traffic to the pod. This means you can run multiple nginx pods on the same node all using the same containerPort and access them from any other pod or node in your cluster using IP. Like Docker, ports can still be published to the host node’s interfaces, but the need for this is radically diminished because of the networking model.

You can read more about the if you’re curious.

Deploying the API backend

So far you have deployed the service configuration to Service Management,
but you have not yet deployed the code that serves the API backend. This section
walks you through deploying prebuilt containers for the sample API and
ESP to Kubernetes.

Providing ESP with the service credentials

ESP, which runs inside a container, needs access to the
credentials stored locally in the file. To provide
ESP with access to the credentials, you create a
Kubernetes secret
and mount the Kubernetes secret as a
Kubernetes volume.

To create the Kubernetes secret and mount the volume:

  1. If you used the Cloud Console to create the service account, rename
    the JSON file to . Move it to the same directory
    where the and files are located.

  2. Create a
    Kubernetes secret
    with the service account credentials:

     kubectl create secret generic service-account-creds
          --from-file=service-account-creds.json

    On success, you see the message, .

The deployment manifest file that you use to deploy the API
and ESP to Kubernetes already contains the
,
as shown in the following two sections of the file:

endpoints/kubernetes/k8s-grpc-bookstore.yaml

View on GitHub

Configuring the service name and starting the service

ESP needs to know the name of your service to find the
configuration that you deployed previously by using the
command.

To configure the service name and start the service:

  1. Save a copy of the deployment manifest file,
    ,
    to the same directory as .

  2. Open and replace SERVICE_NAME with the name of
    your Endpoints service. This is the same name that you
    configured in the field of the file.

    endpoints/kubernetes/k8s-grpc-bookstore.yaml

    View on GitHub

    The option
    configures ESP to use the latest deployed service configuration. When you
    specify this option, up to 5 minutes after you deploy a new service
    configuration, ESP detects the change and automatically begins using it. We
    recommend that you specify this option instead of a specific configuration ID
    for ESP to use.

    For more details on the ESP arguments, see
    ESP startup options.

  3. Start the service to deploy the service on Kubernetes:

    kubectl create -f k8s-grpc-bookstore.yaml

    If you see an error message similar to the following:

    The connection to the server localhost:8080 was refused - did you specify the right host or port?

    This indicates that isn’t properly configured. See

    for more information.

Если лимит памяти не задан

Если вы не задали ограничение памяти для контейнера, возможны следующие варианты:

  • У контейнера отсутствует верхняя граница для памяти, которую он может использовать.
    Такой контейнер может занять всю память, доступную на ноде, где он запущен, что, в свою очередь, может вызвать OOM Killer.
    Также контейнеры без ограничений по ресурсам имеют более высокие шансы быть убитыми в случае вызова OOM Kill.

  • Контейнер запущен в пространстве имён, в котором настроена величина ограничений по умолчанию.
    Тогда контейнеру автоматически присваивается это стандартное значение лимита.
    Администраторы кластера могут использовать

    для задания стандартной величины ограничений по памяти.

Resource units in Kubernetes

Meaning of CPU

Limits and requests for CPU resources are measured in cpu units.
One cpu, in Kubernetes, is equivalent to 1 vCPU/Core for cloud providers and 1 hyperthread on bare-metal Intel processors.

Fractional requests are allowed. When you define a container with
set to , you are requesting half
as much CPU time compared to if you asked for CPU.
For CPU resource units, the expression is equivalent to the
expression , which can be read as «one hundred millicpu». Some people say
«one hundred millicores», and this is understood to mean the same thing. A
request with a decimal point, like , is converted to by the API, and
precision finer than is not allowed. For this reason, the form might
be preferred.

CPU is always requested as an absolute quantity, never as a relative quantity;
0.1 is the same amount of CPU on a single-core, dual-core, or 48-core machine.

Meaning of memory

Limits and requests for are measured in bytes. You can express memory as
a plain integer or as a fixed-point number using one of these suffixes:
E, P, T, G, M, k, m (millis). You can also use the power-of-two equivalents: Ei, Pi, Ti, Gi,
Mi, Ki. For example, the following represent roughly the same value:

Here’s an example.
The following Pod has two Containers. Each Container has a request of 0.25 cpu
and 64MiB (226 bytes) of memory. Each Container has a limit of 0.5
cpu and 128MiB of memory. You can say the Pod has a request of 0.5 cpu and 128
MiB of memory, and a limit of 1 cpu and 256MiB of memory.

Подготовка к установке

Кластер Kubernetes я буду разворачивать на виртуальных машинах Centos 7. На них она установлена в минимальной конфигурации. Напоминаю, что установка будет проходить с помощью Kubespray. Я рекомендую склонировать к себе репозиторий, чтобы у вас сохранилась версия kubespray, с которой вы устанавливали кластер. Это позволит без проблем создавать копию кластера для тестов, дебага, обновления и т.д. Я для этого использую свой сервер Gitlab. Рекомендую озаботиться его наличием. Он нам очень пригодится и дальше в процессе знакомства и изучения кластера.

На виртуальных машинах нужно отключить следующие сущности:

  1. SELinux (привет любителям безопасности, считающим, что selinux отключают только дилетанты).
  2. Swap.
  3. FirewallD, либо любой другой firewall.

На все сервера должен быть разрешен доступ пользователя root по ssh с одним и тем же паролем.

Putting all things together :

Now in our main function we will get all the things together.

Now if we run our code then our custom resource definition will get created in the Kubernetes cluster and also an object of its type will be there just like with the cli. The docker image akash125/crdblog is build using the code discussed above it can be directly pulled from docker hub and run in a Kubernetes cluster. After the image is run successfully, the CRD definition that we discussed above will get created in the cluster along with an object of its type. We can verify the same using the CLI the way we did earlier, we can also check the logs of the pod running the docker image to verify it. The complete code is available here.

Conclusion and future work:

We learned how to create a custom resource definition and objects using the Kubernetes command-line interface as well as the Golang client. We also learned how to programmatically access a Kubernetes cluster, using which we can build some really cool stuff on Kubernetes, we can now also create custom controllers for our resources that continuously watches the cluster for various life cycle events of our object and takes desired action accordingly. To read more about CRD refer to the following links:

  • https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/
  • https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/
  • https://blog.openshift.com/kubernetes-custom-resources-grow-up-in-v1-10/
  • https://medium.com/@trstringer/create-kubernetes-controllers-for-core-and-custom-resources-62fc35ad64a3

Причины использования

Метки позволяют пользователям гибко сопоставить их организационные структуры с системными объектами, не требуя от клиентов хранить эти соответствия.

Развертывания сервисов и процессы пакетной обработки часто являются многомерными сущностями (например, множество разделов или развертываний, несколько групп выпусков, несколько уровней приложения, несколько микросервисов на каждый уровень приложения). Для управления часто требуются сквозные операции, которые нарушают инкапсуляцию строго иерархических представлений, особенно жестких иерархий, определяемых инфраструктурой, а не пользователями.

Примеры меток:

  • ,
  • , ,
  • , ,
  • ,
  • ,

Это всего лишь примеры часто используемых меток; конечно, вы можете использовать свои собственные. Помните о том, что ключ метки должна быть уникальной в пределах одного объекта.

Опции вывода

В следующих разделах рассматривается форматирование и сортировка вывода определенных команд. Дополнительные сведения о том, какие команды поддерживают разные варианты вывода, смотрите в справочной документации kubectl.

Форматирование вывода

Стандартный формат вывода всех команд представлен в человекочитаемом текстовом формате. Чтобы вывести подробности в определенном формате можно добавить флаги или к команде .

В зависимости от операции поддерживаются следующие форматы вывода:

Выходной формат Описание
Вывести таблицу с использованием списка , разделённого запятыми.
Вывести таблицу с использованием шаблона с в файле .
Вывести API-объект в формате JSON.
Вывести поля, определенные в выражении jsonpath.
Вывести поля, определённые в выражении jsonpath из файла .
Вывести только имя ресурса.
Вывести в текстовом формате с дополнительной информацией. Для подов отображается имя узла.
Вывести API-объект в формате YAML

В данном примере следующая команда выводит подробную информацию по указанному поду в виде объекта в YAML-формате:

Примечание: подробную информацию о доступных форматах вывода в определенной команде смотрите в справочной документации kubectl.

Пользовательские столбцы

Для определения пользовательских столбцов и вывода в таблицу только нужных данных, можно использовать опцию . Вы можете определить пользовательские столбцы в самой опции, либо сделать это в файле шаблона: или .

Столбцы указаны в самой команде:

Столбцы указаны в файле шаблона:

где файл содержит следующее:

Результат выполнения любой из показанной выше команды:

Получение вывода с сервера

может получать информацию об объектах с сервера.
Это означает, что для любого указанного ресурса сервер вернет столбцы и строки по этому ресурсу, которые отобразит клиент.
Благодаря тому, что сервер инкапсулирует реализацию вывода, гарантируется единообразный и человекочитаемый вывод на всех клиентах, использующих один и тот же кластер.

Эта функциональность включена по умолчанию, начиная с 1.11 и выше. Чтобы отключить ее, добавьте флаг в команду .

Для вывода информации о состоянии пода, используйте следующую команду:

Вывод будет выглядеть следующим образом:

Сортировка списка объектов

Для вывода объектов в виде отсортированного списка в терминал используется флаг к команде . Для сортировки объектов нужно указать любое числовое или строковое поле в флаге . Для определения поля используйте выражение jsonpath.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: