Udacity: нативные основы SUSE Cloud (10 частей)
Это девятая статья в серии, Udacity: Suse Cloud Native Foundation Анкет Это расширение предыдущего раздела на Kubernetes. Большинство обсуждаемых до сих пор развертываются через императивный подход Анкет Мы рассмотрим другой вид в этом разделе.
📌 Декларативный путь
Есть два способа следовать развертыванию кластеров Kubernetes. Первый — это то, что мы делали до сих пор, императивный подход.
императивный подход Позволяет управлять ресурсами, используя команды Kubectl непосредственно в живом кластере. Этот метод лучше всего подходит только для этапов разработки, так как он представляет собой полосу низкого уровня начального уровня для взаимодействия с кластером.
декларативный подход Использует манифесты, которые хранятся локально для создания и управления объектами Kubertenest. Этот подход рекомендуется для производственных выпусков, так как мы можем контролировать версию состояния развернутых ресурсов.
Тем не менее, существует гораздо более высокая кривая обучения в выполнении декларативного подхода, поскольку необходимо надежное понимание шаблона YAML.
📑 Ямль манифестная структура
Манифест Kubernetes содержит полную конфигурацию для объекта Kubernetes и находится в Yaml Формат, который является стандартом сериализации данных.
В файле манифеста YAML есть 4 секции
- Apiversion — версия API, используемая для создания объекта Kubernetes
- добрый — Тип объекта, который будет создан или настроен
- Метаданные — хранит данные, которые делают объект идентифицируемым
- Spec — Определяет желаемое состояние конфигурации ресурса
Чтобы получить манифест YAML любого ресурса в кластере, используйте kubectl Get
команда, связанная с -О yaml
Флаг, который запрашивает выход в формате YAML.
📗 Развертывание YAML Manifest
В дополнение к необходимым разделам манифеста YAML, ресурс развертывания охватывает конфигурацию Replicaset, стратегия обмотации, и контейнеры Анкет См. Ниже пример,
## Set the API endpoint used to create the Deployment resource. apiVersion: apps/v1 ## Define the type of the resource. kind: Deployment ## Set the parameters that make the object identifiable, such as its name, namespace, and labels. metadata: annotations: labels: app: go-helloworld name: go-helloworld namespace: default ## Define the desired configuration for the Deployment resource. spec: ## Set the number of replicas. ## This will create a ReplicaSet that will manage 3 pods of the Go hello-world application. replicas: 3 ## Identify the pods managed by this Deployment using the following selectors. ## In this case, all pods with the label `go-helloworld`. selector: matchLabels: app: go-helloworld ## Set the RollingOut strategy for the Deployment. ## For example, roll out only 25% of the new pods at a time. strategy: rollingUpdate: maxSurge: 25% maxUnavailable: 25% type: RollingUpdate ## Set the configuration for the pods. template: ## Define the identifiable metadata for the pods. ## For example, all pods should have the label `go-helloworld` metadata: labels: app: go-helloworld ## Define the desired state of the pod configuration. spec: containers: ## Set the image to be executed inside the container and image pull policy ## In this case, run the `go-helloworld` application in version v2.0.0 and ## only pull the image if it's not available on the current host. - image: pixelpotato/go-helloworld:v2.0.0 imagePullPolicy: IfNotPresent name: go-helloworld ## Expose the port the container is listening on. ## For example, exposing the application port 6112 via TCP. ports: - containerPort: 6112 protocol: TCP ## Define the rules for the liveness probes. ## For example, verify the application on the main route `/`, ## on application port 6112. If the application is not responsive, then the pod will be restarted automatically. livenessProbe: httpGet: path: / port: 6112 ## Define the rules for the readiness probes. ## For example, verify the application on the main route `/`, ## on application port 6112. If the application is responsive, then traffic will be sent to this pod. readinessProbe: httpGet: path: / port: 6112 ## Set the resource requests and limits for an application. resources: ## The resource requests guarantees that the desired amount ## CPU and memory is allocated for a pod. In this example, ## the pod will be allocated with 64 Mebibytes and 250 miliCPUs. requests: memory: "64Mi" cpu: "250m" ## The resource limits ensure that the application is not consuming ## more than the specified CPU and memory values. In this example, ## the pod will not surpass 128 Mebibytes and 500 miliCPUs. limits: memory: "128Mi" cpu: "500m"
📒 Служба ямля Manifest
В дополнение к необходимым разделам манифеста YAML, сервисный ресурс охватывает конфигурацию типа сервиса и портов, которые должен настроить службу.
## Set the API endpoint used to create the Service resource. apiVersion: v1 ## Define the type of the resource. kind: Service ## Set the parameters that make the object identifiable, such as its name, namespace, and labels. metadata: labels: app: go-helloworld name: go-helloworld namespace: default ## Define the desired configuration for the Service resource. spec: ## Define the ports that the service should serve on. ## For example, the service is exposed on port 8111, and ## directs the traffic to the pods on port 6112, using TCP. ports: - port: 8111 protocol: TCP targetPort: 6112 ## Identify the pods managed by this Service using the following selectors. ## In this case, all pods with the label `go-helloworld`. selector: app: go-helloworld ## Define the Service type, here set to ClusterIP. type: ClusterIP
🔰 Полезные команды
Чтобы создать ресурс, определенный в ямле, манифест с именем manifest.yaml
kubectl apply -f manifest.yaml
Чтобы удалить ресурс с использованием манифеста YAML,
kubectl delete -f manifest.yaml
Вы можете проверить все доступные параметры в документации Kubernetes. В дополнение к этому вы также можете построить шаблон YAML, используя команды Kubectl.
Это возможно, используя -Dry-run = клиент
и -О yaml
Флаги, которые инструктируют, что команда должна быть оценена только на стороне клиента и выводит результат в формате YAML.
Приведенная ниже команда получает шаблон YAML для ресурса.
kubectl create RESOURCE [REQUIRED FLAGS] --dry-run=client -o yaml
В качестве примера вы можете получить шаблон для ресурса развертывания, используя Создать
командовать, передайте требуемые параметры и связаны с -Dry-Run
и -О yaml
флаги. Это выводит базовый шаблон, который может быть использован далее для более расширенной конфигурации.
Вызовете приведенную ниже команду, чтобы получить базовую шаблон YAML для демонстрационного развертывания под приложением NGINX
kubectl create deploy demo --image=nginx --dry-run=client -o yaml
Далее, лабораторное время!
Если вам понравится эта статья и вы хотели бы узнать больше, обязательно нажмите на Следуйте чуть ниже и добавьте в закладки сериал. Я также буду рад связаться с вами на Twitter Анкет Увидимся там! 😃
Иден Йозефоллоу
Udacity: нативные основы SUSE Cloud (10 частей)
Оригинал: «https://dev.to/jeden/udacity-suse-orchestration-kubernetes-manifests-2i82»