One place for hosting & domains

      Kubeadm

      Как создать кластер Kubernetes с помощью Kubeadm в Ubuntu 18.04


      Автор выбрал фонд Free and Open Source Fund для получения пожертвования в рамках программы Write for DOnations.

      Введение

      Kubernetes — это система оркестровки контейнеров, обеспечивающая управление контейнерами в масштабе. Система Kubernetes была первоначально разработана Google на основе опыта компании в использовании контейнеров в рабочей среде. Это решение с открытым исходным кодом, и в его разработке активно участвуют представители сообщества разработчиков со всего мира.

      Примечание. В этом обучающем модуле используется версия Kubernetes 1.14, последняя официальная поддерживаемая версия на момент публикации данной статьи. Актуальную информацию о последней версии можно найти в текущих примечаниях к выпуску в официальной документации Kubernetes.

      Kubeadm автоматизирует установку и настройку компонентов Kubernetes, в том числе сервера API, Controller Manager и Kube DNS. Однако данное средство не создает пользователей и не выполняет установку зависимостей уровня операционной системы и их конфигурации. Для предварительных задач существует возможность использования инструментов управления конфигурацией, таких как Ansible и SaltStack. Использование этих инструментов упрощает создание дополнительных кластеров или воссоздание существующих кластеров, а также снижает вероятность ошибок.

      В этом обучающем модуле вы научитесь создавать кластер Kubernetes с помощью Ansible и Kubeadm, а затем развертывать в нем приложение Nginx в контейнерах.

      Цели

      Ваш кластер будет включать следующие физические ресурсы:

      • Один главный узел

      Главный узел (под узлом в Kubernetes подразумевается сервер), отвечающиой за управление состоянием кластера. На нем работает система Etcd, которая хранит данные кластера среди компонентов, распределяющих рабочие задачи по рабочим узлам.

      • Два рабочих узла

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

      После прохождения данного обучающего модуля вы получите кластер, готовый к запуску приложений в контейнерах, при условии, что серверы кластера имеют достаточные ресурсы процессорной мощности и оперативной памяти для выполнения этих приложений. Практически любые традиционные приложения Unix, в том числе веб-приложения, базы данных, демоны и инструменты командной строки, можно поместить в контейнеры и запускать в кластере. Сам кластер потребляет примерно 300-500 МБ оперативной памяти и 10% ресурсов процессора на каждом узле.

      После настройки кластера вы развернете веб-сервер Nginx для проверки правильного выполнения рабочих задач.

      Предварительные требования

      Шаг 1 — Настройка каталога рабочего пространства и файла инвентаризации Ansible

      В этом разделе вы создадите на локальном компьютере каталог, который будет выступать в качестве рабочего пространства. Вы выполните локальную настройку Ansible, чтобы обеспечить возможность связи с вашими удаленными серверами и выполнения команд на этих серверах. После этого вы создадите файл hosts с данными инвентаризации, в том числе с IP-адресами ваших серверов и данными групп, к которым принадлежит каждый сервер.

      Из трех ваших серверов один сервер будет главным сервером, и его IP-адрес будет отображаться как master_ip. Другие два сервера будут рабочими узлами и будут иметь IP-адреса worker_1_ip и worker_2_ip.

      Создайте каталог ~/kube-cluster в домашнем каталоге локального компьютера и перейдите в него с помощью команды cd:

      • mkdir ~/kube-cluster
      • cd ~/kube-cluster

      В рамках этого обучающего модуля данный каталог будет выступать в качестве рабочего пространства, и в нем будут храниться все ваши плейбуки Ansible. Также в этом каталоге вы будете запускать все локальные команды.

      Создайте файл с именем ~/kube-cluster/hosts с помощью nano или своего любимого текстового редактора:

      • nano ~/kube-cluster/hosts

      Добавьте в файл следующий текст с информацией о логической структуре вашего кластера:

      ~/kube-cluster/hosts

      [masters]
      master ansible_host=master_ip ansible_user=root
      
      [workers]
      worker1 ansible_host=worker_1_ip ansible_user=root
      worker2 ansible_host=worker_2_ip ansible_user=root
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Возможно вы помните, что файлы инвентаризации в Ansible используются для указания данных серверов, в том числе IP-адресов, удаленных пользователей и группировок серверов как единый объем для целей выполнения команд. Файл ~/kube-cluster/hosts будет вашим файлом инвентаризации, и вы добавили в него две группы Ansible (masters и workers) для определения логической структуры вашего кластера.

      В группе masters имеется запись сервера master, в которой указан IP-адрес главного узла (master_ip) и указывается, что система Ansible должна запускать удаленные команды от имени пользователя root.

      В группе workers также есть две записи для серверов рабочих узлов (worker_1_ip и worker_2_ip), где пользователь ansible_user также задается как пользователь root.

      В последней строке файла Ansible предписывается использовать для операций управления интерпретаторы Python 3 удаленных серверов.

      Сохраните и закройте файл после добавления текста.

      После настойки инвентаризации сервера с помощью групп мы переходим к установке зависимостей уровня операционной системы и создания параметров конфигурации.

      Шаг 2 — Создание пользователя без привилегий root на всех удаленных серверах

      В этом разделе вы создадите пользователя без привилегий root с привилегиями sudo на всех серверах, чтобы вы могли вручную подключаться к ним через SSH как пользователь без привилегий. Это полезно на случай, если вы захотите посмотреть информацию о системе с помощью таких команд как top/htop, просмотреть список работающих контейнеров или изменить файлы конфигурации, принадлежащие пользователю root. Данные операции обычно выполняются во время технического обслуживания кластера, и использование пользователя без привилегий root для выполнения таких задач минимизирует риск изменения или удаления важных файлов или случайного выполнения других опасных операций.

      Создайте в рабочем пространстве файл с именем ~/kube-cluster/initial.yml:

      • nano ~/kube-cluster/initial.yml

      Добавьте в файл следующую строку сценария play для создания пользователя без привилегий root с привилегиями sudo на всех серверах. Сценарий в Ansible — это набор выполняемых шагов, нацеленных на определенные серверы и группы. Следующий сценарий создаст пользователя без привилегий root с привилегиями sudo:

      ~/kube-cluster/initial.yml

      - hosts: all
        become: yes
        tasks:
          - name: create the 'ubuntu' user
            user: name=ubuntu append=yes state=present createhome=yes shell=/bin/bash
      
          - name: allow 'ubuntu' to have passwordless sudo
            lineinfile:
              dest: /etc/sudoers
              line: 'ubuntu ALL=(ALL) NOPASSWD: ALL'
              validate: 'visudo -cf %s'
      
          - name: set up authorized keys for the ubuntu user
            authorized_key: user=ubuntu key="{{item}}"
            with_file:
              - ~/.ssh/id_rsa.pub
      

      Далее приведено детальное описание операций, выполняемых этим плейбуком:

      • Создает пользователя без привилегий root с именем ubuntu.

      • Настраивает файл sudoers, чтобы пользователь ubuntu мог запускать команды sudo без ввода пароля.

      • Добавляет на локальный компьютер открытый ключ (обычно ~/.ssh/id_rsa.pub) в список авторизованных ключей удаленного пользователя ubuntu. Это позволит вам подключаться к каждому серверу через SSH под именем пользователя ubuntu.

      Сохраните и закройте файл после добавления текста.

      Затем запустите плейбук на локальном компьютере:

      • ansible-playbook -i hosts ~/kube-cluster/initial.yml

      Выполнение команды займет от двух до пяти минут. После завершения вы увидите примерно следующий результат:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [master] ok: [worker1] ok: [worker2] TASK [create the 'ubuntu' user] **** changed: [master] changed: [worker1] changed: [worker2] TASK [allow 'ubuntu' user to have passwordless sudo] **** changed: [master] changed: [worker1] changed: [worker2] TASK [set up authorized keys for the ubuntu user] **** changed: [worker1] => (item=ssh-rsa AAAAB3...) changed: [worker2] => (item=ssh-rsa AAAAB3...) changed: [master] => (item=ssh-rsa AAAAB3...) PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0 worker1 : ok=5 changed=4 unreachable=0 failed=0 worker2 : ok=5 changed=4 unreachable=0 failed=0

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

      Шаг 3 — Установка зависимостей Kubernetetes

      В этом разделе вы научитесь устанавливать требующиеся Kubernetes пакеты уровня операционной системы с помощью диспетчера пакетов Ubuntu. Вот эти пакеты:

      • Docker — среда исполнения контейнеров. Это компонент, который запускает ваши контейнеры. В настоящее время для Kubernetes активно разрабатывается поддержка других сред исполнения, в том числе rkt.

      • kubeadm — инструмент командной строки, который устанавливает и настраивает различные компоненты кластера стандартным образом.

      • kubelet — системная служба / программа, которая работает на всех узлах и обрабатывает операции на уровне узлов.

      • kubectl — инструмент командной строки, используемый для отправки команд на кластер через сервер API.

      Создайте в рабочем пространстве файл с именем ~/kube-cluster/kube-dependencies.yml:

      • nano ~/kube-cluster/kube-dependencies.yml

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

      ~/kube-cluster/kube-dependencies.yml

      - hosts: all
        become: yes
        tasks:
         - name: install Docker
           apt:
             name: docker.io
             state: present
             update_cache: true
      
         - name: install APT Transport HTTPS
           apt:
             name: apt-transport-https
             state: present
      
         - name: add Kubernetes apt-key
           apt_key:
             url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
             state: present
      
         - name: add Kubernetes' APT repository
           apt_repository:
            repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
            state: present
            filename: 'kubernetes'
      
         - name: install kubelet
           apt:
             name: kubelet=1.14.0-00
             state: present
             update_cache: true
      
         - name: install kubeadm
           apt:
             name: kubeadm=1.14.0-00
             state: present
      
      - hosts: master
        become: yes
        tasks:
         - name: install kubectl
           apt:
             name: kubectl=1.14.0-00
             state: present
             force: yes
      

      Первый сценарий в плейбуке выполняет следующие операции:

      • Устанавливает среду исполнения контейнеров Docker.

      • Устанавливает apt-transport-https, позволяя добавлять внешние источники HTTPS в список источников APT.

      • Добавляет ключ apt-key репозитория Kubernetes APT для проверки ключей.

      • Добавляет репозиторий Kubernetes APT в список источников APT ваших удаленных серверов.

      • Устанавливает kubelet и kubeadm.

      Второй сценарий состоит из одной задачи, которая устанавливает kubectl на главном узле.

      Примечание. Хотя документация по Kubernetes рекомендует использовать для вашей среды последнюю стабильную версию Kubernetes, в данном обучающем модуле используется конкретная версия. Это обеспечит успешное следование процедуре, поскольку Kubernetes быстро изменяется и последняя версия может не соответствовать этому обучающему модулю.

      Сохраните файл и закройте его после завершения.

      Затем запустите плейбук на локальном компьютере:

      • ansible-playbook -i hosts ~/kube-cluster/kube-dependencies.yml

      После завершения вы увидите примерно следующий результат:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [worker1] ok: [worker2] ok: [master] TASK [install Docker] **** changed: [master] changed: [worker1] changed: [worker2] TASK [install APT Transport HTTPS] ***** ok: [master] ok: [worker1] changed: [worker2] TASK [add Kubernetes apt-key] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [add Kubernetes' APT repository] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubelet] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubeadm] ***** changed: [master] changed: [worker1] changed: [worker2] PLAY [master] ***** TASK [Gathering Facts] ***** ok: [master] TASK [install kubectl] ****** ok: [master] PLAY RECAP **** master : ok=9 changed=5 unreachable=0 failed=0 worker1 : ok=7 changed=5 unreachable=0 failed=0 worker2 : ok=7 changed=5 unreachable=0 failed=0

      После выполнения на всех удаленных серверах будут установлены Docker, kubeadm и kubelet. kubectl не является обязательным компонентом и требуется только для выполнения команд кластера. В этом контексте имеет смысл производить установку только на главный узел, поскольку вы будете запускать команды kubectl только на главном узле. Однако следует отметить, что команды kubectl можно запускать с любых рабочих узлов и на любом компьютере, где их можно установить и настроить для указания на кластер.

      Теперь все системные зависимости установлены. Далее мы настроим главный узел и проведем инициализацию кластера.

      Шаг 4 — Настройка главного узла

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

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

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

      Эту функцию обеспечивают плагины сети подов. Для этого кластера мы используем стабильный и производительный плагин Flannel.

      Создайте на локальном компьютере плейбук Ansible с именем master.yml:

      • nano ~/kube-cluster/master.yml

      Добавьте в файл следующий сценарий для инициализации кластера и установки Flannel:

      ~/kube-cluster/master.yml

      - hosts: master
        become: yes
        tasks:
          - name: initialize the cluster
            shell: kubeadm init --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
            args:
              chdir: $HOME
              creates: cluster_initialized.txt
      
          - name: create .kube directory
            become: yes
            become_user: ubuntu
            file:
              path: $HOME/.kube
              state: directory
              mode: 0755
      
          - name: copy admin.conf to user's kube config
            copy:
              src: /etc/kubernetes/admin.conf
              dest: /home/ubuntu/.kube/config
              remote_src: yes
              owner: ubuntu
      
          - name: install Pod network
            become: yes
            become_user: ubuntu
            shell: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/a70459be0084506e4ec919aa1c114638878db11b/Documentation/kube-flannel.yml >> pod_network_setup.txt
            args:
              chdir: $HOME
              creates: pod_network_setup.txt
      

      Далее приведена детализация этого сценария:

      • Первая задача инициализирует кластер посредством запуска kubeadm init. При передаче аргумента --pod-network-cidr=10.244.0.0/16 задается частная подсеть, из которой назначаются IP-адреса подов. Flannel использует вышеуказанную подсеть по умолчанию, и мы предпишем kubeadm использовать ту же подсеть.

      • Вторая задача создает каталог .kube по адресу /home/ubuntu. В это каталоге будут храниться данные конфигурации, в том числе файлы ключа администратора, необходимые для подключения к кластеру, и адрес API кластера.

      • Третья задача копирует файл /etc/kubernetes/admin.conf, сгенерированный kubeadm init в домашнем каталоге пользователя без привилегий root. Это позволит вам использовать kubectl для доступа к новому кластеру.

      • Последняя задача запускает kubectl apply для установки Flannel. Синтаксис kubectl apply -f descriptor.[yml|json] предписывает kubectl создать объекты, описанные в файле descriptor.[yml|json]. Файл kube-flannel.yml содержит описания объектов, требуемых для настроки Flannel в кластере.

      Сохраните файл и закройте его после завершения.

      Запустите плейбук на локальной системе с помощью команды:

      • ansible-playbook -i hosts ~/kube-cluster/master.yml

      После завершения вы увидите примерно следующий результат:

      Output

      PLAY [master] **** TASK [Gathering Facts] **** ok: [master] TASK [initialize the cluster] **** changed: [master] TASK [create .kube directory] **** changed: [master] TASK [copy admin.conf to user's kube config] ***** changed: [master] TASK [install Pod network] ***** changed: [master] PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0

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

      Запустите на главном узле следующую команду:

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

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.14.0

      В результатах показано, что главный узел master завершил выполнение всех задач инициализации и находится в состоянии готовности Ready, из которого он может принимать подключения от рабочих узлов и выполнять задачи, отправленные на сервер API. Теперь вы можете добавить рабочие узлы с локального компьютера.

      Шаг 5 — Настройка рабочих узлов

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

      Вернитесь в рабочее пространство и создайте плейбук с именем workers.yml:

      • nano ~/kube-cluster/workers.yml

      Добавьте в файл следующий текст для добавления рабочих узлов в кластер:

      ~/kube-cluster/workers.yml

      - hosts: master
        become: yes
        gather_facts: false
        tasks:
          - name: get join command
            shell: kubeadm token create --print-join-command
            register: join_command_raw
      
          - name: set join command
            set_fact:
              join_command: "{{ join_command_raw.stdout_lines[0] }}"
      
      
      - hosts: workers
        become: yes
        tasks:
          - name: join cluster
            shell: "{{ hostvars['master'].join_command }} >> node_joined.txt"
            args:
              chdir: $HOME
              creates: node_joined.txt
      

      Вот что делает этот плейбук:

      • Первый сценарий получает команду join, которую нужно запустить на рабочих узлах. Эта команда имеет следующий форматt: kubeadm join --token <token> <master-ip>:<master-port> --discovery-token-ca-cert-hash sha256:<hash>. После получения фактической команды с правильными значениями token и hash задача задает их как фактические, чтобы следующий сценарий имел доступ к этой информации.

      • Второй сценарий содержит одну задачу, которая запускает команду join на всех рабочих узлах. После завершения этой задачи два рабочих узла становятся частью кластера.

      Сохраните файл и закройте его после завершения.

      Запустите плейбук на локальном компьютере:

      • ansible-playbook -i hosts ~/kube-cluster/workers.yml

      После завершения вы увидите примерно следующий результат:

      Output

      PLAY [master] **** TASK [get join command] **** changed: [master] TASK [set join command] ***** ok: [master] PLAY [workers] ***** TASK [Gathering Facts] ***** ok: [worker1] ok: [worker2] TASK [join cluster] ***** changed: [worker1] changed: [worker2] PLAY RECAP ***** master : ok=2 changed=1 unreachable=0 failed=0 worker1 : ok=2 changed=1 unreachable=0 failed=0 worker2 : ok=2 changed=1 unreachable=0 failed=0

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

      Шаг 6 — Проверка кластера

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

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

      Затем выполните следующую команду, чтобы получить данные о статусе кластера:

      Вы увидите примерно следующий результат:

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.14.0 worker1 Ready <none> 1d v1.14.0 worker2 Ready <none> 1d v1.14.0

      Если на всех ваших узлах отображается значение Ready для параметра STATUS, это означает, что они являются частью кластера и готовы к выполнению рабочих задач.

      Если же на некоторых узлах отображается значение NotReady для параметра STATUS, это может означать, что настройка рабочих узлов еще не завершена. Подождите от пяти до десяти минут, а затем снова запустите команду kubectl get nodes и проверьте полученные результаты. Если для некоторых узлов еще отображается статус NotReady, вам нужно проверить и заново запустить команды, которые выполнялись на предыдущих шагах.

      Теперь кластер успешно проверен, и мы запланируем запуск на кластере образца приложения Nginx.

      Шаг 7 — Запуск приложения на кластере

      Теперь вы можете развернуть на кластере любое приложение в контейнере. Для удобства мы развернем Nginx с помощью Deployments и Services и посмотрим, как можно развернуть это приложение на кластере. Вы можете использовать приведенные ниже команды для других приложений в контейнерах, если вы измените имя образа Docker и дополнительные параметры (такие как ports и volumes).

      Запустите на главном узле следующую команду для создания развертывания с именем nginx:

      • kubectl create deployment nginx --image=nginx

      Развертывание — это тип объекта Kubernetes, обеспечивающий постоянную работу определенного количества подов на основе заданного шаблона, даже в случае неисправности пода в течение срока службы кластера. Вышеуказанное развертывание создаст под с одним контейнером из образа Nginx Docker в реестре Docker.

      Запустите следующую команду, чтобы создать службу nginx, которая сделает приложение общедоступным. Для этого используется схема NodePort, которая делает под доступным на произвольном порту, который открывается на каждом узле кластера:

      • kubectl expose deploy nginx --port 80 --target-port 80 --type NodePort

      Службы — это еще один тип объектов Kubernetes, который открывает внутренние службы кластера для внутренних и внешних клиентов. Они поддерживают запросы балансировки нагрузки на разные поды и являются неотъемлемым компонентом Kubernetes, который часто взаимодействует с другими компонентами.

      Запустите следующую команду:

      Будет выведен текст следующего вида:

      Output

      NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d nginx NodePort 10.109.228.209 <none> 80:nginx_port/TCP 40m

      В третьей сроке результатов указан номер порта, на котором запущен Nginx. Kubernetes автоматически назначает случайный порт с номером выше 30000 и при этом проверяет, не занят ли этот порт другой службой.

      Чтобы убедиться в работе всех элементов, откройте адрес http://worker_1_ip:nginx_port или http://worker_2_ip:nginx_port в браузере на локальном компьютере. Вы увидите знакомую начальную страницу Nginx.

      Если вы захотите удалить приложение Nginx, предварительно удалите службу nginx с главного узла:

      • kubectl delete service nginx

      Запустите следующую команду, чтобы проверить удаление службы:

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

      Output

      NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d

      Затем удалите развертывание:

      • kubectl delete deployment nginx

      Запустите следующую команду для проверки успешности выполнения:

      Output

      No resources found.

      Заключение

      В этом обучающем модуле вы научились успешно настраивать кластер Kubernetes в Ubuntu 18.04, используя для автоматизации Kubeadm и Ansible.

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

      • Докеризация приложений — детальные примеры контейнеризации приложений с помощью Docker.

      • Обзор подов — детальное описание принципов работы подов и их отношений с другими объектами Kubernetes. Поды используются в Kubernetes повсеместно, так что понимание этой концепции упростит вашу работу.

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

      • Обзор служб — рассказывает о службах, еще одном часто используемом объекте кластеров Kubernetes. Понимание типов служб и доступных для них опций важно для использования приложений с сохранением состояния и без сохранения состояния.

      Другие важные концепции, полезные при развертывании рабочих приложений: тома, входы и секреты.

      В Kubernetes имеется множество функций и возможностей. Официальная документация Kubernetes — лучший источник информации о концепциях, руководств по конкретным задачам и ссылок API для различных объектов.



      Source link

      Cómo crear un clúster de Kubernetes usando Kubeadm en Ubuntu 18.04


      El autor seleccionó la Free and Open Source Fund para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Kubernetes es un sistema de orquestación de contenedores que administra contenedores a escala. Fue inicialmente desarrollado por Google en base a su experiencia en ejecución de contenedores en producción, es de código abierto y una comunidad mundial impulsa su desarrollo de manera activa.

      Nota: Para este tutorial se utiliza la versión 1.14 de Kubernetes, la versión oficial admitida en el momento de la publicación de este artículo. Para obtener información actualizada sobre la versión más reciente, consulte las notas de la versión actual en la documentación oficial de Kubernetes.

      Kubeadm automatiza la instalación y la configuración de componentes de Kubernetes como el servidor de API, Controller Manager y Kube DNS. Sin embargo, no crea usuarios ni maneja la instalación de dependencias al nivel del sistema operativo ni su configuración. Para estas tareas preliminares, se puede usar una herramienta de administración de configuración como Ansible o SaltStack. El uso de estas herramientas hace que la creación de clústeres adiciones o la recreación de los existentes sea mucho más simple y menos propensa a errores.

      A través de esta guía, configurará un clúster de Kubernetes desde cero usando Ansible y Kubeadm y luego implementará una aplicación de Nginx en contenedores.

      Objetivos

      Su clúster incluirá los siguientes recursos físicos:

      El nodo maestro (un nodo de Kubernetes hace referencia a un servidor) se encarga de administrar el estado del clúster. Ejecuta Etcd, que almacena datos de clústeres entre componentes que organizan cargas de trabajo en nodos de trabajo.

      Los nodos de trabajo son los servidores en los que se ejecutarán sus cargas de trabajo (es decir, aplicaciones y servicios en contenedores). Un trabajador seguirá ejecutando su volumen de trabajo una vez que se le asigne, incluso si el maestro se desactiva cuando la programación se complete. La capacidad de un clúster puede aumentarse añadiendo trabajadores.

      Tras completar esta guía, tendrá un clúster listo para ejecutar aplicaciones en contenedores siempre que los servidores del clúster cuenten con suficientes recursos de CPU y RAM para sus aplicaciones. Casi cualquier aplicación tradicional de Unix que incluya aplicaciones web, bases de datos, demonios y herramientas de línea de comandos pueden estar contenedorizadas y hechas para ejecutarse en el clúster. El propio clúster consumirá entre 300 y 500 MB de memoria y un 10 % de CPU en cada nodo.

      Una vez que se configure el clúster, implementará el servidor web Nginx para que garantice que se ejecuten correctamente las cargas de trabajo.

      Requisitos previos

      Paso 1: Configurar el directorio de espacio de trabajo y el archivo de inventario de Ansible

      En esta sección, creará un directorio en su máquina local que funcionará como su espacio de trabajo. Configurará Ansible localmente para que pueda comunicarse con comandos y ejecutarlos en sus servidores remotos. Una vez realizado esto, creará un archivo de hosts que contenga información de inventario como las direcciones IP de sus servidores y los grupos a los que pertenece cada servidor.

      De sus tres servidores, uno será el maestro con un IP que se mostrará como master_ip. Los otros dos servidores serán trabajadores y tendrán los IPS worker_1_ip y worker_2_ip.

      Cree un directorio llamado ~/kube-cluster en el directorio de inicio de su máquina local y cd en él:

      • mkdir ~/kube-cluster
      • cd ~/kube-cluster

      Este directorio será su espacio de trabajo para el resto del tutorial y contendrá todos sus libros de reproducción de Ansible. También será el directorio dentro del que ejecutará todos los comandos locales.

      Cree un archivo llamado ~/kube-cluster/hosts usando nano o su editor de texto favorito:

      • nano ~/kube-cluster/hosts

      Añada el siguiente texto al archivo, que especificará información sobre la estructura lógica de su clúster:

      ~/kube-cluster/hosts

      [masters]
      master ansible_host=master_ip ansible_user=root
      
      [workers]
      worker1 ansible_host=worker_1_ip ansible_user=root
      worker2 ansible_host=worker_2_ip ansible_user=root
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Es posible que recuerde que los archivos de inventario de Ansible se utilizan para especificar datos del servidor, como direcciones IP, usuarios remotos y las agrupaciones de servidores que se abordarán como una sola unidad para ejecutar comandos. ~/kube-cluster/hosts será su archivo de inventario y usted agregó a este dos grupos de Ansible (maestros *y *trabajadores) para especificar la estructura lógica de su clúster.

      En el grupo de maestros, existe una entrada de servidor llamada “master” que enumera el IP del nodo maestro (master_ip) y especifica que Ansible debería ejecutar comandos remotos como usuario root.

      De modo similar, en el grupo de trabajadores, existen dos entradas para los servidores de trabajo worker_1_ip y worker_2_ip que también especifican el ansible_user como root.

      La última línea del archivo indica a Ansible que utilice los intérpretes de Python 3 de servidores remotos para sus operaciones de administración.

      Guarde y cierre el archivo después de agregar el texto.

      Tras haber configurado el inventario del servidor con grupos, instalaremos dependencias a nivel del sistema operativo y crearemos ajustes de configuración.

      Paso 2: Crear un usuario no root en todos los servidores remotos

      En esta sección, creará un usuario no root con privilegios sudo en todos los servidores para poder acceder a SSH manualmente como usuario no privilegiado. Esto puede ser útil si, por ejemplo, desea ver la información del sistema con comandos como top/htop, ver una lista de contenedores en ejecución o cambiar archivos de configuración pertenecientes a root. Estas operaciones se realizan de forma rutinaria durante el mantenimiento de un clúster, y el empleo de un usuario no root para esas tareas minimiza el riesgo de modificar o eliminar archivos importantes o de realizar de forma no intencionada otras operaciones peligrosas.

      Cree un archivo llamado ~/kube-cluster/initial.yml en el espacio de trabajo:

      • nano ~/kube-cluster/initial.yml

      A continuación, añada el siguiente play al archivo para crear un usuario no root con privilegios sudo en todos los servidores. Un play en Ansible es una colección de pasos que se deben realizar y se orientan a servidores y grupos específicos. El siguiente play creará un usuario sudo no root:

      ~/kube-cluster/initial.yml

      - hosts: all
        become: yes
        tasks:
          - name: create the 'ubuntu' user
            user: name=ubuntu append=yes state=present createhome=yes shell=/bin/bash
      
          - name: allow 'ubuntu' to have passwordless sudo
            lineinfile:
              dest: /etc/sudoers
              line: 'ubuntu ALL=(ALL) NOPASSWD: ALL'
              validate: 'visudo -cf %s'
      
          - name: set up authorized keys for the ubuntu user
            authorized_key: user=ubuntu key="{{item}}"
            with_file:
              - ~/.ssh/id_rsa.pub
      

      Este es un desglose de lo que hace este libro de reproducción:

      • Crea el usuario no root ubuntu.

      • Configura el archivo sudoers para permitir que el usuario de ubuntu ejecute comandos sudo sin un mensaje de contraseña.

      • Añade la clave pública de su máquina local (por lo general ~/.ssh/id_rsa.pub) a la lista de claves autorizadas del usuario ubuntu remoto. Esto le permitirá usar SSH en cada servidor como usuario ubuntu.

      Guarde y cierre el archivo tras haber añadido el texto.

      A continuación, ejecute el libro de reproducción ejecutando lo siguiente a nivel local:

      • ansible-playbook -i hosts ~/kube-cluster/initial.yml

      El comando se completará en dos o cinco minutos. Al finalizar, verá resultados similares al siguiente:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [master] ok: [worker1] ok: [worker2] TASK [create the 'ubuntu' user] **** changed: [master] changed: [worker1] changed: [worker2] TASK [allow 'ubuntu' user to have passwordless sudo] **** changed: [master] changed: [worker1] changed: [worker2] TASK [set up authorized keys for the ubuntu user] **** changed: [worker1] => (item=ssh-rsa AAAAB3...) changed: [worker2] => (item=ssh-rsa AAAAB3...) changed: [master] => (item=ssh-rsa AAAAB3...) PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0 worker1 : ok=5 changed=4 unreachable=0 failed=0 worker2 : ok=5 changed=4 unreachable=0 failed=0

      Ahora que la configuración preliminar está completa, puede instalar dependencias específicas de Kubernetes.

      Paso 3: Instalar las dependencias de Kubernetetes

      A través de esta sección, instalará los paquetes a nivel del sistema operativo requeridos por Kubernetes con el administrador de paquetes de Ubuntu. Estos paquetes son l:

      • Docker: un tiempo de ejecución de contenedores. Es el componente que ejecuta sus contenedores. La compatibilidad con otros tiempos de ejecución como rkt se encuentra en etapa de desarrollo activo en Kubernetes.

      • kubeadm: herramienta de CLI que instalará y configurará los distintos componentes de un clúster de forma estándar.

      • kubelet: servicio o programa del sistema que se ejecuta en todos los nodos y gestiona operaciones a nivel de nodo.

      • kubectl: una herramienta de CLI que se utiliza para emitir comandos al clúster a través de su servidor de API.

      Cree un archivo llamado ~/kube-cluster/kube-dependencies.yml en el espacio de trabajo:

      • nano ~/kube-cluster/kube-dependencies.yml

      Añada los siguientes play al archivo para instalar estos paquetes a sus servidores:

      ~/kube-cluster/kube-dependencies.yml

      - hosts: all
        become: yes
        tasks:
         - name: install Docker
           apt:
             name: docker.io
             state: present
             update_cache: true
      
         - name: install APT Transport HTTPS
           apt:
             name: apt-transport-https
             state: present
      
         - name: add Kubernetes apt-key
           apt_key:
             url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
             state: present
      
         - name: add Kubernetes' APT repository
           apt_repository:
            repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
            state: present
            filename: 'kubernetes'
      
         - name: install kubelet
           apt:
             name: kubelet=1.14.0-00
             state: present
             update_cache: true
      
         - name: install kubeadm
           apt:
             name: kubeadm=1.14.0-00
             state: present
      
      - hosts: master
        become: yes
        tasks:
         - name: install kubectl
           apt:
             name: kubectl=1.14.0-00
             state: present
             force: yes
      

      El primer play del playbook hace lo siguiente:

      • Instala Docker, el tiempo de ejecución del contenedor.

      • Instala apt-transport-https, que le permite añadir fuentes HTTPS externas a su lista de fuentes APT.

      • Añade la clave apt del repositorio de APT de Kubernetes para la verificación de claves.

      • Añade el repositorio de APT de Kubernetes a la lista de fuentes APT de sus servidores remotos.

      • Instala kubelet y kubeadm.

      El segundo play consta de una única tarea que instala kubectl en su nodo maestro.

      Nota: Aunque en la documentación de Kubernetes se le recomienda usar la última versión estable de Kubernetes para su entorno, en este tutorial se utiliza una versión específica. Esto garantizará que pueda seguir los pasos correctamente, ya que Kubernetes cambia de forma rápida y es posible que la última versión no funcione con este tutorial.

      Guarde y cierre el archivo cuando haya terminado.

      A continuación, ejecute el playbook ejecutando lo siguiente a nivel local:

      • ansible-playbook -i hosts ~/kube-cluster/kube-dependencies.yml

      Al finalizar, verá resultados similares al siguiente:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [worker1] ok: [worker2] ok: [master] TASK [install Docker] **** changed: [master] changed: [worker1] changed: [worker2] TASK [install APT Transport HTTPS] ***** ok: [master] ok: [worker1] changed: [worker2] TASK [add Kubernetes apt-key] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [add Kubernetes' APT repository] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubelet] ***** changed: [master] changed: [worker1] changed: [worker2] TASK [install kubeadm] ***** changed: [master] changed: [worker1] changed: [worker2] PLAY [master] ***** TASK [Gathering Facts] ***** ok: [master] TASK [install kubectl] ****** ok: [master] PLAY RECAP **** master : ok=9 changed=5 unreachable=0 failed=0 worker1 : ok=7 changed=5 unreachable=0 failed=0 worker2 : ok=7 changed=5 unreachable=0 failed=0

      Tras la ejecución, Docker, kubeadm y kubelet se instalarán en todos los servidores remotos. kubectl no es un componente necesario y solo se necesita para ejecutar comandos de clúster. Si la instalación se realiza solo en el nodo maestro tiene sentido en este contexto, ya que ejecutará comandos kubectl solo desde el maestro. Tenga en cuenta, sin embargo, que los comandos kubectl pueden ejecutarse desde cualquiera de los nodos de trabajo o desde cualquier máquina en donde se pueda instalar y configurar para apuntar a un clúster.

      Con esto, quedarán instaladas todas las dependencias del sistema. Configuraremos el nodo maestro e iniciaremos el clúster.

      Paso 4: Configurar el nodo maestro

      En esta sección, configurará el nodo maestro. Sin embargo, antes de crear cualquier playbook, valdrá la pena abarcar algunos conceptos como Pods y complementos de red de Pods, ya que su clúster incluirá ambos.

      Un pod es una unidad atómica que ejecuta uno o más contenedores. Estos contenedores comparten recursos como volúmenes de archivos e interfaces de red en común. Los pods son la unidad básica de programación de Kubernetes: se garantiza que todos los contenedores de un pod se ejecutan en el mismo nodo en el que está programado el pod.

      Cada pod tiene su propia dirección IP y un pod de un nodo debería poder acceder a un pod de otro usando el IP del pod. Los contenedores de un nodo único pueden comunicarse fácilmente a través de una interfaz local. Sin embargo, la comunicación entre los pods es más complicada y requiere un componente de red independiente que puede dirigir de forma transparente el tráfico de un pod de un nodo a un pod de otro.

      Los complementos de red de pods ofrecen esta funcionalidad. Para este clúster usará Flannel, una opción estable y apta.

      Cree un libro de reproducción de Ansible llamado master.yml en su máquina local:

      • nano ~/kube-cluster/master.yml

      Añada el siguiente play al archivo para iniciar el clúster e instalar Flannel:

      ~/kube-cluster/master.yml

      - hosts: master
        become: yes
        tasks:
          - name: initialize the cluster
            shell: kubeadm init --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
            args:
              chdir: $HOME
              creates: cluster_initialized.txt
      
          - name: create .kube directory
            become: yes
            become_user: ubuntu
            file:
              path: $HOME/.kube
              state: directory
              mode: 0755
      
          - name: copy admin.conf to user's kube config
            copy:
              src: /etc/kubernetes/admin.conf
              dest: /home/ubuntu/.kube/config
              remote_src: yes
              owner: ubuntu
      
          - name: install Pod network
            become: yes
            become_user: ubuntu
            shell: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/a70459be0084506e4ec919aa1c114638878db11b/Documentation/kube-flannel.yml >> pod_network_setup.txt
            args:
              chdir: $HOME
              creates: pod_network_setup.txt
      

      A continuación, se muestra un desglose de este play:

      • La primera tarea inicia el clúster ejecutando kubeadm init. Pasar el argumento --pod-network-cidr=10.244.0.0/16 especifica la subred privada desde la cual se asignarán los IP del pod. Flannel utiliza la subred anterior por defecto; le indicaremos a kubeadm que use la misma subred.

      • La segunda tarea crea un directorio .kube en /home/ubuntu. En este directorio se almacenarán datos de configuración, como los archivos de claves de administrador que se necesitan para establecer conexión con el clúster, y la dirección API del clúster.

      • La tercera tarea copia el archivo /etc/kubernetes/admin.conf que se generó desde kubeadm init al directorio principal de su usuario no root. Esto le permitirá usar kubectl para acceder al clúster recién creado.

      • La última tarea ejecuta kubectl apply para instalar Flannel. kubectl apply -f descriptor.[yml|json]​​​​​​ es la sintaxis para indicar a ​​​kubectl​​​​​​ que cree los objetos descritos en ​​​​​​el archivo descriptor.[yml|json]​​​​​. El archivo kube-flannel.yml contiene las descripciones de los objetos necesarios para configurar Flannel en el clúster.

      Guarde y cierre el archivo cuando haya terminado.

      Implemente el playbook a nivel local ejecutando lo siguiente:

      • ansible-playbook -i hosts ~/kube-cluster/master.yml

      Al finalizar, verá un resultado similar al siguiente:

      Output

      PLAY [master] **** TASK [Gathering Facts] **** ok: [master] TASK [initialize the cluster] **** changed: [master] TASK [create .kube directory] **** changed: [master] TASK [copy admin.conf to user's kube config] ***** changed: [master] TASK [install Pod network] ***** changed: [master] PLAY RECAP **** master : ok=5 changed=4 unreachable=0 failed=0

      Para comprobar el estado del nodo maestro, aplique SSH en él con el siguiente comando:

      Una vez dentro del nodo maestro, ejecute lo siguiente:

      Ahora verá lo siguiente:

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.14.0

      El resultado indica que el nodo master ha completado todas las tareas de inicialización y se encuentra en el estado Ready, a partir de lo cual puede comenzar a aceptar nodos de trabajo y ejecutar tareas enviadas al servidor de la API. Ahora puede añadir los trabajadores desde su máquina local.

      Paso 5: Configurar los nodos del trabajo

      La incorporación de trabajadores al clúster implica ejecutar un único comando en cada uno. Este comando incluye la información de clúster necesaria, como la dirección IP y el puerto del servidor de la API del maestro y un token seguro. Solo podrán incorporarse al clúster los nodos que puedan pasar el token seguro.

      Regrese a su espacio de trabajo y cree un libro de reproducción denominado workers.yml:

      • nano ~/kube-cluster/workers.yml

      Añada el siguiente texto al archivo para añadir los trabajadores al clúster:

      ~/kube-cluster/workers.yml

      - hosts: master
        become: yes
        gather_facts: false
        tasks:
          - name: get join command
            shell: kubeadm token create --print-join-command
            register: join_command_raw
      
          - name: set join command
            set_fact:
              join_command: "{{ join_command_raw.stdout_lines[0] }}"
      
      
      - hosts: workers
        become: yes
        tasks:
          - name: join cluster
            shell: "{{ hostvars['master'].join_command }} >> node_joined.txt"
            args:
              chdir: $HOME
              creates: node_joined.txt
      

      Esto es lo que hace el playbook:

      • El primer play obtiene el comando de incorporación que debe ejecutarse en los nodos de trabajo. Este comando se mostrará en el siguiente formato: kubeadm join --token <token> <master-ip>:<master-port> --discovery-token-ca-cert-hash sha256:<hash> Una vez que obtiene el comando real con el token y los valores hash adecuados, la tarea lo establece como un hecho para que el siguiente play pueda acceder a esta información.

      • El segundo play tiene una sola tarea que ejecuta el comando de incorporación en todos los nodos de trabajo. Una vez que se complete esta tarea, los dos nodos de trabajo formarán parte del clúster.

      Guarde y cierre el archivo cuando haya terminado.

      Implemente el playbook ejecutando lo siguiente a nivel local:

      • ansible-playbook -i hosts ~/kube-cluster/workers.yml

      Al finalizar, verá resultados similares al siguiente:

      Output

      PLAY [master] **** TASK [get join command] **** changed: [master] TASK [set join command] ***** ok: [master] PLAY [workers] ***** TASK [Gathering Facts] ***** ok: [worker1] ok: [worker2] TASK [join cluster] ***** changed: [worker1] changed: [worker2] PLAY RECAP ***** master : ok=2 changed=1 unreachable=0 failed=0 worker1 : ok=2 changed=1 unreachable=0 failed=0 worker2 : ok=2 changed=1 unreachable=0 failed=0

      Con la adición de los nodos de trabajo, ahora su clúster estará completamente configurado y activo, con los trabajadores listos para ejecutar el volumen de trabajo. Antes de programar aplicaciones, comprobaremos que el clúster funcione como se espera.

      Paso 6: Verificar el clúster

      Un clúster puede fallar durante la configuración debido a la indisponibilidad de un nodo o a que la conexión de red entre el maestro y el trabajador no funciona correctamente. Comprobaremos el clúster y nos aseguraremos de que los nodos funcionen correctamente.

      Deberá comprobar el estado actual del clúster desde el nodo maestro para asegurarse de que los nodos estén listos. Si interrumpió la conexión con el nodo maestro, puede aplicar SSH en él de nuevo con el siguiente comando:

      Luego, ejecute el siguiente comando para obtener el estado del clúster:

      El resultado debe ser similar a lo siguiente:

      Output

      NAME STATUS ROLES AGE VERSION master Ready master 1d v1.14.0 worker1 Ready <none> 1d v1.14.0 worker2 Ready <none> 1d v1.14.0

      Si el valor de STATUS es Ready para todos sus nodos, significa que son parte del clúster y están listos para ejecutar cargas de trabajo.

      Sin embargo, si el valor de STATUS es NotReady para algunos de los nodos, podría significar que los nodos de trabajo aún no han terminado su configuración. Espere de 5 a 10 minutos antes de volver a ejecutar kubectl get nodes y verificar el nuevo resultado. Si el estado de algunos nodos todavía es NotReady, es posible que deba verificar y volver a ejecutar los comandos de los pasos anteriores.

      Ahora que su clúster se ha verificado correctamente, programaremos una aplicación de Nginx de ejemplo en el clúster.

      Paso 7: Ejecutar una aplicación en el clúster

      Ahora puede implementar cualquier aplicación en contenedor en su clúster. Para que sea sencillo, implementaremos Nginx usando implementaciones y _servicios _para ver la forma en que se puede implementar esta aplicación en el clúster. Puede usar también los comandos que se muestran a continuación para otras aplicaciones en contenedores siempre que cambie el nombre de imagen de Docker y cualquier indicador pertinente (por ejemplo, ports y volumes).

      Dentro del nodo maestro, ejecute el siguiente comando para crear una implementación llamada nginx:

      • kubectl create deployment nginx --image=nginx

      Una implementación es un tipo de objeto de Kubernetes que garantiza que siempre haya un número especificado de pods ejecutándose según una plantilla definida, incluso cuando el pod se bloquee durante la vida útil del clúster. La implementación anterior creará un pod con un contenedor desde la imagen de Docker de Nginx del registro de Docker.

      A continuación, ejecute el siguiente comando para crear un servicio llamado nginx que mostrará la aplicación públicamente. Esto lo hará a través de un NodePort, un esquema que permitirá el acceso al pod a través de un puerto arbitrario abierto en cada nodo del clúster:

      • kubectl expose deploy nginx --port 80 --target-port 80 --type NodePort

      Los servicios son otro tipo de objeto de Kubernetes que exponen los servicios internos del clúster a los clientes, tanto internos como externos. También pueden usar solicitudes de equilibrio de carga para varios pods y son un componente integral de Kubernetes que interactúa de forma frecuente con otros.

      Ejecute el siguiente comando:

      Con esto se mostrará texto similar al siguiente:

      Output

      NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d nginx NodePort 10.109.228.209 <none> 80:nginx_port/TCP 40m

      Desde la tercera línea del resultado anterior, puede recuperar el puerto en el que Nginx se ejecuta. Kubernetes asignará de forma aleatoria y automática un puerto superior al 30000, y garantizará que no esté ya vinculado a otro servicio.

      Para probar que todo esté funcionando, visite http://worker_1_ip:nginx_port o http://worker_2_ip:nginx_port a través de un navegador en su máquina local. Visualizará la página de bienvenida conocida de Nginx.

      Si desea eliminar la aplicación de Nginx, primero elimine el servicio nginx del nodo maestro:

      • kubectl delete service nginx

      Ejecute lo siguiente para asegurarse de que el servicio se haya eliminado:

      Verá lo siguiente:

      Output

      NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1d

      Luego elimine la implementación:

      • kubectl delete deployment nginx

      Ejecute lo siguiente para confirmar que esto haya funcionado:

      Output

      No resources found.

      Conclusión

      A través de esta guía, configuró correctamente un clúster de Kubernetes en Ubuntu 18.04 usando Kubeadm y Ansible para la automatización.

      Si se pregunta qué hacer con el clúster ahora que está configurado, un buen paso sería lograr implementar con comodidad aplicaciones y servicios propios en el clúster. A continuación, se presenta una lista de enlaces con más información que puede orientarlo en el proceso:

      • Implementar Docker en aplicaciones: contiene ejemplos en los que se detalla la forma de disponer aplicaciones en contenedores usando Docker.

      • Descripción general de Pod: describe en detalle el funcionaminento de los Pods y su relación con otros objetos Kubernetes. Los pods se encuentran en todas partes en Kubernetes. Por ello, si los comprende su trabajo será más sencillo.

      • Descripción general de las implementaciones: ofrece un panorama de las implementaciones. Resulta útil comprender el funcionamiento de controladores como las implementaciones, ya que se utilizan con frecuencia en aplicaciones sin estado para escalar y reparar aplicaciones no saludables de forma automática.

      • Descripción general de services: abarca services, otro objeto usado con frecuencia en los clústeres de Kubernetes. Comprender los tipos de servicios y las opciones que tienen es esencial para ejecutar aplicaciones con y sin estado.

      Otros conceptos importantes que puede ver son los de Volume, Ingress y Secret, los cuales son útiles cuando se implementan aplicaciones de producción.

      Kubernetes ofrece muchas funciones y características. La documentación oficial de Kubernetes es la mejor forma de aprender sobre conceptos, encontrar guías específicas para tareas y buscar referencias de API para varios objetos.



      Source link

      Getting Started with Kubernetes: Use kubeadm to Deploy a Cluster on Linode


      Updated by Linode

      Contributed by

      Linode

      Linode offers several pathways for users to easily deploy a Kubernetes cluster. If you prefer the command line, you can create a Kubernetes cluster with one command using the Linode CLI’s k8s-alpha plugin, and Terraform. Or, if you prefer a full featured GUI, Linode’s Rancher integration enables you to deploy and manage Kubernetes clusters with a simple web interface. The Linode Kubernetes Engine, currently under development with an early access beta version on its way this summer, allows you to spin up a Kubernetes cluster with Linode handling the management and maintenance of your control plane. These are all great options for production ready deployments.

      Kubeadm is a cloud provider agnostic tool that automates many of the tasks required to get a cluster up and running. Users of kubeadm can run a few simple commands on individual servers to turn them into a Kubernetes cluster consisting of a master node and worker nodes. This guide will walk you through installing kubeadm and using it to deploy a Kubernetes cluster on Linode. While the kubeadm approach requires more manual steps than other Kubernetes cluster creation pathways offered by Linode, this solution will be covered as way to dive deeper into the various components that make up a Kubernetes cluster and the ways in which they interact with each other to provide a scalable and reliable container orchestration mechanism.

      Note

      This guide’s example instructions will result in the creation of three billable Linodes. Information on how to tear down the Linodes are provided at the end of the guide. Interacting with the Linodes via the command line will provide the most opportunity for learning, however, this guide is written so that users can also benefit by reading along.

      Before You Begin

      1. Deploy three Linodes running Ubuntu 18.04 with the following system requirements:

        • One Linode to use as the master Node with 4GB RAM and 2 CPU cores.
        • Two Linodes to use as the Worker Nodes each with 1GB RAM and 1 CPU core.
      2. Follow the Getting Started and the Securing Your Server guides for instructions on setting up your Linodes. The steps in this guide assume the use of a limited user account with sudo privileges.

      Note

      When following the Getting Started guide, make sure that each Linode is using a different hostname. Not following this guideline will leave you unable to join some or all nodes to the cluster in a later step.
      1. Disable swap memory on your Linodes. Kubernetes requires that you disable swap memory on any cluster nodes to prevent the Kubernetes scheduler (kube-scheduler) from ever sending a pod to a node that has run out of CPU/memory or reached its designated CPU/memory limit.

        sudo swapoff -a
        

        Verify that your swap has been disabled. You should expect to see a value of 0 returned.

        cat /proc/meminfo | grep 'SwapTotal'
        

        To learn more about managing compute resources for containers, see the official Kubernetes documentation.

      2. Read the Beginners Guide to Kubernetes to familiarize yourself with the major components and concepts of Kubernetes. The current guide assumes a working knowledge of common Kubernetes concepts and terminology.

      Build a Kubernetes Cluster

      Kubernetes Cluster Architecture

      A Kubernetes cluster consists of a master node and worker nodes. The master node hosts the control plane, which is the combination of all the components that provide it the ability to maintain the desired cluster state. This cluster state is defined by manifest files and the kubectl tool. While the control plane components can be run on any cluster node, it is a best practice to isolate the control plane on its own node and to run any application containers on a separate worker node. A cluster can have a single worker node or up to 5000. Each worker node must be able to maintain running containers in a pod and be able to communicate with the master node’s control plane.

      The table below provides a list of the Kubernetes tooling you will need to install on your master and worker nodes in order to meet the minimum requirements for a functioning Kubernetes cluster as described above.

      ToolDescriptionMaster NodeWorker Nodes
      kubeadmThis tool provides a simple way to create a Kubernetes cluster by automating the tasks required to get a cluster up and running. New Kubernetes users with access to a cloud hosting provider, like Linode, can use kubeadm to build out a playground cluster. kubeadm is also used as a foundation to create more mature Kubernetes deployment tooling.xx
      Container RuntimeA container runtime is responsible for running the containers that make up a cluster’s pods. This guide will use Docker as the container runtime.xx
      kubeletkubelet ensures that all pod containers running on a node are healthy and meet the specifications for a pod’s desired behavior.xx
      kubectlA command line tool used to manage a Kubernetes cluster.xx
      Control PlaneSeries of services that form Kubernetes master structure that allow it to control the cluster. Kubeadm allows the control plane services to run as containers on the master node. The control plane will be created when you initialize kubeadm later in this guide.x

      Install the Container Runtime: Docker

      Docker is the software responsible for running the pod containers on each node. You can use other container runtime software with Kubernetes, such as Containerd and CRI-O. You will need to install Docker on all three Linodes.

      These steps install Docker Community Edition (CE) using the official Ubuntu repositories. To install on another distribution, see the official installation page.

      1. Remove any older installations of Docker that may be on your system:

        sudo apt remove docker docker-engine docker.io
        
      2. Make sure you have the necessary packages to allow the use of Docker’s repository:

        sudo apt install apt-transport-https ca-certificates curl software-properties-common
        
      3. Add Docker’s GPG key:

        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
        
      4. Verify the fingerprint of the GPG key:

        sudo apt-key fingerprint 0EBFCD88
        

        You should see output similar to the following:

          
        pub   4096R/0EBFCD88 2017-02-22
                Key fingerprint = 9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
        uid                  Docker Release (CE deb) 
        sub   4096R/F273FCD8 2017-02-22
        
        
      5. Add the stable Docker repository:

        sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
        
      6. Update your package index and install Docker CE:

        sudo apt update
        sudo apt install docker-ce
        
      7. Add your limited Linux user account to the docker group. Replace $USER with your username:

        sudo usermod -aG docker $USER
        

        Note

        After entering the usermod command, you will need to close your SSH session and open a new one for this change to take effect.

      8. Check that the installation was successful by running the built-in “Hello World” program:

        sudo docker run hello-world
        
      9. Setup the Docker daemon to use systemd as the cgroup driver, instead of the default cgroupfs. This is a recommended step so that Kubelet and Docker are both using the same cgroup manager. This will make it easier for Kubernetes to know which resources are available on your cluster’s nodes.

        sudo bash -c 'cat > /etc/docker/daemon.json <<EOF
        {
          "exec-opts": ["native.cgroupdriver=systemd"],
          "log-driver": "json-file",
          "log-opts": {
            "max-size": "100m"
          },
          "storage-driver": "overlay2"
        }
        EOF'
        
      10. Create a systemd directory for Docker:

        sudo mkdir -p /etc/systemd/system/docker.service.d
        
      11. Restart Docker:

        sudo systemctl daemon-reload
        sudo systemctl restart docker
        

      Install kubeadm, kubelet, and kubectl

      Complete the steps outlined in this section on all three Linodes.

      1. Update the system and install the required dependencies for installation:

        sudo apt-get update && sudo apt-get install -y apt-transport-https curl
        
      2. Add the required GPG key to your apt-sources keyring to authenticate the Kubernetes related packages you will install:

        curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
        
      3. Add Kubernetes to the package manager’s list of sources:

        sudo bash -c "cat <<EOF >/etc/apt/sources.list.d/kubernetes.list
        deb https://apt.kubernetes.io/ kubernetes-xenial main
        EOF"
        
      4. Update apt, install Kubeadm, Kubelet, and Kubectl, and hold the installed packages at their installed versions:

        sudo apt-get update
        sudo apt-get install -y kubelet kubeadm kubectl
        sudo apt-mark hold kubelet kubeadm kubectl
        
      5. Verify that kubeadm, kubelet, and kubectl have installed by retrieving their version information. Each command should return version information about each package.

        kubeadm version
        kubelet --version
        kubectl version
        

      Set up the Kubernetes Control Plane

      After installing the Kubernetes related tooling on all your Linodes, you are ready to set up the Kubernetes control plane on the master node. The control plane is responsible for allocating resources to your cluster, maintaining the health of your cluster, and ensuring that it meets the minimum requirements you designate for the cluster.

      The primary components of the control plane are the kube-apiserver, kube-controller-manager, kube-scheduler, and etcd. kubeadm provides a way to easily initialize the Kubernetes master node with all the necessary control plane components. For more information on each of control plane component see the Beginner’s Guide to Kubernetes.

      In addition to the baseline control plane components, there are several addons, that can be installed on the master node to access additional cluster features. You will need to install a networking and network policy provider add on that will implement Kubernetes’ network model on the cluster’s pod network.

      This guide will use Calico as the pod network add on. Calico is a secure and open source L3 networking and network policy provider for containers. There are several other network and network policy providers to choose from. To view a full list of providers, refer to the official Kubernetes documentation.

      Note

      kubeadm only supports Container Network Interface (CNI) based networks. CNI consists of a specification and libraries for writing plugins to configure network interfaces in Linux containers

      1. Initialize kubeadm on the master node. This command will run checks against the node to ensure it contains all required Kubernetes dependencies, if the checks pass, it will then install the control plane components.

        When issuing this command, it is necessary to set the pod network range that Calico will use to allow your pods to communicate with each other. It is recommended to use the private IP address space, 10.2.0.0/16.

        Note

        The pod network IP range should not overlap with the service IP network range. The default service IP address range is 10.96.0.0/12. You can provide an alternative service ip address range using the --service-cidr=10.97.0.0/12 option when initializing kubeadm. Replace 10.97.0.0/12 with the desired service IP range.

        For a full list of available kubeadm initialization options, see the official Kubernetes documentation.

        sudo kubeadm init --pod-network-cidr=10.2.0.0/16
        

        You should see a similar output:

          
        Your Kubernetes control-plane has initialized successfully!
        
        To start using your cluster, you need to run the following as a regular user:
        
          mkdir -p $HOME/.kube
          sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
          sudo chown $(id -u):$(id -g) $HOME/.kube/config
        
        You should now deploy a pod network to the cluster.
        Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
          https://kubernetes.io/docs/concepts/cluster-administration/addons/
        
        Then you can join any number of worker nodes by running the following on each as root:
        
        kubeadm join 192.0.2.0:6443 --token udb8fn.nih6n1f1aijmbnx5 
            --discovery-token-ca-cert-hash sha256:b7c01e83d63808a4a14d2813d28c127d3a1c4e1b6fc6ba605fe4d2789d654f26
              
        

        The kubeadm join command will be used in the Join a Worker Node to the Cluster section of this guide to bootstrap the worker nodes to the Kubernetes cluster. This command should be kept handy for later use. Below is a description of the required options you will need to pass in with the kubeadm join command:

        • The master node’s IP address and the Kubernetes API server’s port number. In the example output, this is 192.0.2.0:6443. The Kubernetes API server’s port number is 6443 by default on all Kubernetes installations.
        • A bootstrap token. The bootstrap token has a 24-hour TTL (time to live). A new bootstrap token can be generated if your current token expires.
        • A CA key hash. This is used to verify the authenticity of the data retrieved from the Kubernetes API server during the bootstrap process.
      2. Copy the admin.conf configuration file to your limited user account. This file allows you to communicate with your cluster via kubectl and provides superuser privileges over the cluster. It contains a description of the cluster, users, and contexts. Copying the admin.conf to your limited user account will provide you with administrative privileges over your cluster.

        mkdir -p $HOME/.kube
        sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
        sudo chown $(id -u):$(id -g) $HOME/.kube/config
        
      3. Install the necessary Calico manifests to your master node and apply them using kubectl. The first file, rbac-kdd.yaml, works with Kubernetes’ role-based access control (RBAC) to provide Calico components access to necessary parts of the Kubernetes API. The second file, calico.yaml, configures a self-hosted Calico installation that uses the Kubernetes API directly as the datastore (instead of etcd).

        kubectl apply -f https://docs.projectcalico.org/v3.3/getting-started/kubernetes/installation/hosted/rbac-kdd.yaml
        kubectl apply -f https://docs.projectcalico.org/v3.3/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml
        

      Inspect the Master Node with Kubectl

      After completing the previous section, your Kubernetes master node is ready with all the necessary components to manage a cluster. To gain a better understanding of all the parts that make up the master’s control plane, this section will walk you through inspecting your master node. If you have not yet reviewed the Beginner’s Guide to Kubernetes, it will be helpful to do so prior to continuing with this section as it relies on the understanding of basic Kubernetes concepts.

      1. View the current state of all nodes in your cluster. At this stage, the only node you should expect to see is the master node, since worker nodes have yet to be bootstrapped. A STATUS of Ready indicates that the master node contains all necessary components, including the pod network add-on, to start managing clusters.

        kubectl get nodes
        

        Your output should resemble the following:

          
        NAME        STATUS     ROLES     AGE   VERSION
        kube-master   Ready     master      1h    v1.14.1
            
        
      2. Inspect the available namespaces in your cluster.

        kubectl get namespaces
        

        Your output should resemble the following:

          
        NAME              STATUS   AGE
        default           Active   23h
        kube-node-lease   Active   23h
        kube-public       Active   23h
        kube-system       Active   23h
            
        

        Below is an overview of each namespace installed by default on the master node by kubeadm:

        • default: The default namespace contains objects with no other assigned namespace. By default, a Kubernetes cluster will instantiate a default namespace when provisioning the cluster to hold the default set of Pods, Services, and Deployments used by the cluster.
        • kube-system: The namespace for objects created by the Kubernetes system. This includes all resources used by the master node.
        • kube-public: This namespace is created automatically and is readable by all users. It contains information, like certificate authority data (CA), that helps kubeadm join and authenticate worker nodes.
        • kube-node-lease: The kube-node-lease namespace contains lease objects that are used by kubelet to determine node health. kubelet creates and periodically renews a Lease on a node. The node lifecycle controller treats this lease as a health signal. kube-node-lease was released to beta in Kubernetes 1.14.
      3. View all resources available in the kube-system namespace. The kube-system namespace contains the widest range of resources, since it houses all control plane resources. Replace kube-system with another namespace to view its corresponding resources.

        kubectl get all -n kube-system
        

      Join a Worker Node to the Cluster

      Now that your Kubernetes master node is set up, you can join worker nodes to your cluster. In order for a worker node to join a cluster, it must trust the cluster’s control plane, and the control plane must trust the worker node. This trust is managed via a shared bootstrap token and a certificate authority (CA) key hash. kubeadm handles the exchange between the control plane and the worker node. At a high-level the worker node bootstrap process is the following:

      1. kubeadm retrieves information about the cluster from the Kubernetes API server. The bootstrap token and CA key hash are used to ensure the information originates from a trusted source.

      2. kubelet can take over and begin the bootstrap process, since it has the necessary cluster information retrieved in the previous step. The bootstrap token is used to gain access to the Kubernetes API server and submit a certificate signing request (CSR), which is then signed by the control plane.

      3. The worker node’s kubelet is now able to connect to the Kubernetes API server using the node’s established identity.

      Before continuing, you will need to make sure that you know your Kubernetes API server’s IP address, that you have a bootstrap token, and a CA key hash. This information was provided when kubeadm was initialized on the master node in the Set up the Kubernetes Control Plane section of this guide. If you no longer have this information, you can regenerate the necessary information from the master node.


      Regenerate a Bootstrap Token

      These commands should be issued from your master node.

      1. Generate a new bootstrap token and display the kubeadm join command with the necessary options to join a worker node to the master node’s control plane:

        kubeadm token create --print-join-command
        

      Follow the steps below on each node you would like to bootstrap to the cluster as a worker node.

      1. SSH into the Linode that will be used as a worker node in the Kubernetes cluster.

        ssh [email protected]
        
      2. Join the node to your cluster using kubeadm. Ensure you replace 192.0.2.0:6443 with the IP address for your master node along with its Kubernetes API server’s port number, udb8fn.nih6n1f1aijmbnx5 with your bootstrap token, and sha256:b7c01e83d63808a4a14d2813d28c127d3a1c4e1b6fc6ba605fe4d2789d654f26 with your CA key hash. The bootstrap process will take a few moments.

        sudo kubeadm join 192.0.2.0:6443 --token udb8fn.nih6n1f1aijmbnx5 
        --discovery-token-ca-cert-hash sha256:b7c01e83d63808a4a14d2813d28c127d3a1c4e1b6fc6ba605fe4d2789d654f26
        

        When the bootstrap process has completed, you should see a similar output:

          
          This node has joined the cluster:
        * Certificate signing request was sent to apiserver and a response was received.
        * The Kubelet was informed of the new secure connection details.
        
        Run 'kubectl get nodes' on the control-plane to see this node join the cluster.
              
        
      3. Repeat the steps outlined above on the second worker node to bootstrap it to the cluster.

      4. SSH into the master node and verify the worker nodes have joined the cluster:

         kubectl get nodes
        

        You should see a similar output.

          
        NAME          STATUS   ROLES    AGE     VERSION
        kube-master   Ready    master   1d22h   v1.14.1
        kube-node-1   Ready       1d22h   v1.14.1
        kube-node-2   Ready       1d22h   v1.14.1
              
        

      Next Steps

      Now that you have a Kubernetes cluster up and running, you can begin experimenting with the various ways to configure pods, group resources, and deploy services that are exposed to the public internet. To help you get started with this, move on to follow along with the Deploy a Static Site on Linode using Kubernetes guide.

      Tear Down Your Cluster

      If you are done experimenting with your Kubernetes Cluster, be sure to remove the Linodes you have running in order to avoid being further billed for them. See the Removing Services section of the Billing and Payments guide.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link