One place for hosting & domains

      Kubeadm

      How To Create a Kubernetes Cluster Using Kubeadm on Ubuntu 20.04


      Introduction

      Kubernetes is a container orchestration system that manages containers at scale. Initially developed by Google based on its experience running containers in production, Kubernetes is open source and actively developed by a community around the world.

      Note: This tutorial uses version 1.22 of Kubernetes, the official supported version at the time of this article’s publication. For up-to-date information on the latest version, please see the current release notes in the official Kubernetes documentation.

      Kubeadm automates the installation and configuration of Kubernetes components such as the API server, Controller Manager, and Kube DNS. It does not, however, create users or handle the installation of operating-system-level dependencies and their configuration. For these preliminary tasks, it is possible to use a configuration management tool like Ansible or SaltStack. Using these tools makes creating additional clusters or recreating existing clusters much simpler and less error prone.

      In this guide, you will set up a Kubernetes cluster from scratch using Ansible and Kubeadm, and then deploy a containerized Nginx application to it.

      Goals

      Your cluster will include the following physical resources:

      The control plane node (a node in Kubernetes refers to a server) is responsible for managing the state of the cluster. It runs Etcd, which stores cluster data among components that schedule workloads to worker nodes.

      Worker nodes are the servers where your workloads (i.e. containerized applications and services) will run. A worker will continue to run your workload once they’re assigned to it, even if the control plane goes down once scheduling is complete. A cluster’s capacity can be increased by adding workers.

      After completing this guide, you will have a cluster ready to run containerized applications, provided that the servers in the cluster have sufficient CPU and RAM resources for your applications to consume. Almost any traditional Unix application including web applications, databases, daemons, and command line tools can be containerized and made to run on the cluster. The cluster itself will consume around 300-500MB of memory and 10% of CPU on each node.

      Once the cluster is set up, you will deploy the web server Nginx to it to ensure that it is running workloads correctly.

      Prerequisites

      • An SSH key pair on your local Linux/macOS/BSD machine. If you haven’t used SSH keys before, you can learn how to set them up by following this explanation of how to set up SSH keys on your local machine.

      • Three servers running Ubuntu 20.04 with at least 2GB RAM and 2 vCPUs each. You should be able to SSH into each server as the root user with your SSH key pair.

      Note: If you haven’t SSH’d into each of these servers at least once prior to following this tutorial, you may be prompted to accept their host fingerprints at an inconvenient time later on. You should do this now, or as an alternative, you can disable host key checking.

      Step 1 — Setting Up the Workspace Directory and Ansible Inventory File

      In this section, you will create a directory on your local machine that will serve as your workspace. You will configure Ansible locally so that it can communicate with and execute commands on your remote servers. Once that’s done, you will create a hosts file containing inventory information such as the IP addresses of your servers and the groups that each server belongs to.

      Out of your three servers, one will be the control plane with an IP displayed as control_plane_ip. The other two servers will be workers and will have the IPs worker_1_ip and worker_2_ip.

      Create a directory named ~/kube-cluster in the home directory of your local machine and cd into it:

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

      This directory will be your workspace for the rest of the tutorial and will contain all of your Ansible playbooks. It will also be the directory inside which you will run all local commands.

      Create a file named ~/kube-cluster/hosts using nano or your favorite text editor:

      • nano ~/kube-cluster/hosts

      Add the following text to the file, which will specify information about the logical structure of your cluster:

      ~/kube-cluster/hosts

      [control_plane]
      control1 ansible_host=control_plane_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
      

      You may recall that inventory files in Ansible are used to specify server information such as IP addresses, remote users, and groupings of servers to target as a single unit for executing commands. ~/kube-cluster/hosts will be your inventory file and you’ve added two Ansible groups (control plane and workers) to it specifying the logical structure of your cluster.

      In the control plane group, there is a server entry named “control1” that lists the control plane’s IP (control_plane_ip) and specifies that Ansible should run remote commands as the root user.

      Similarly, in the workers group, there are two entries for the worker servers (worker_1_ip and worker_2_ip) that also specify the ansible_user as root.

      The last line of the file tells Ansible to use the remote servers’ Python 3 interpreters for its management operations.

      Save and close the file after you’ve added the text. If you are using nano, press Ctrl+X, then when prompted, Y and Enter.

      Having set up the server inventory with groups, let’s move on to installing operating system level dependencies and creating configuration settings.

      Step 2 — Creating a Non-Root User on All Remote Servers

      In this section you will create a non-root user with sudo privileges on all servers so that you can SSH into them manually as an unprivileged user. This can be useful if, for example, you would like to see system information with commands such as top/htop, view a list of running containers, or change configuration files owned by root. These operations are routinely performed during the maintenance of a cluster, and using a non-root user for such tasks minimizes the risk of modifying or deleting important files or unintentionally performing other dangerous operations.

      Create a file named ~/kube-cluster/initial.yml in the workspace:

      • nano ~/kube-cluster/initial.yml

      Next, add the following play to the file to create a non-root user with sudo privileges on all of the servers. A play in Ansible is a collection of steps to be performed that target specific servers and groups. The following play will create a non-root sudo user:

      ~/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
      

      Here’s a breakdown of what this playbook does:

      • Creates the non-root user ubuntu.

      • Configures the sudoers file to allow the ubuntu user to run sudo commands without a password prompt.

      • Adds the public key in your local machine (usually ~/.ssh/id_rsa.pub) to the remote ubuntu user’s authorized key list. This will allow you to SSH into each server as the ubuntu user.

      Save and close the file after you’ve added the text.

      Next, run the playbook locally:

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

      The command will complete within two to five minutes. On completion, you will see output similar to the following:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [control1] ok: [worker1] ok: [worker2] TASK [create the 'ubuntu' user] **** changed: [control1] changed: [worker1] changed: [worker2] TASK [allow 'ubuntu' user to have passwordless sudo] **** changed: [control1] 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: [control1] => (item=ssh-rsa AAAAB3...) PLAY RECAP **** control1 : ok=4 changed=3 unreachable=0 failed=0 worker1 : ok=4 changed=3 unreachable=0 failed=0 worker2 : ok=4 changed=3 unreachable=0 failed=0

      Now that the preliminary setup is complete, you can move on to installing Kubernetes-specific dependencies.

      Step 3 — Installing Kubernetetes’ Dependencies

      In this section, you will install the operating-system-level packages required by Kubernetes with Ubuntu’s package manager. These packages are:

      • Docker – a container runtime. It is the component that runs your containers. Kubernetes supports other runtimes, but Docker is still a popular and straightforward choice.

      • kubeadm – a CLI tool that will install and configure the various components of a cluster in a standard way.

      • kubelet – a system service/program that runs on all nodes and handles node-level operations.

      • kubectl – a CLI tool used for issuing commands to the cluster through its API Server.

      Create a file named ~/kube-cluster/kube-dependencies.yml in the workspace:

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

      Add the following plays to the file to install these packages to your servers:

      ~/kube-cluster/kube-dependencies.yml

      ---
      - hosts: all
        become: yes
        tasks:
         - name: create Docker config directory
           file: path=/etc/docker state=directory
      
      - name: changing Docker to systemd driver
           copy:
            dest: "/etc/docker/daemon.json"
            content: |
              {
              "exec-opts": ["native.cgroupdriver=systemd"]
              }
      
         - 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.22.4-00
             state: present
             update_cache: true
      
         - name: install kubeadm
           apt:
             name: kubeadm=1.22.4-00
             state: present
      
      - hosts: control_plane
        become: yes
        tasks:
         - name: install kubectl
           apt:
             name: kubectl=1.22.4-00
             state: present
             force: yes
      

      The first play in the playbook does the following:

      • Installs Docker, the container runtime, and configures a compatibility setting.

      • Installs apt-transport-https, allowing you to add external HTTPS sources to your APT sources list.

      • Adds the Kubernetes APT repository’s apt-key for key verification.

      • Adds the Kubernetes APT repository to your remote servers’ APT sources list.

      • Installs kubelet and kubeadm.

      The second play consists of a single task that installs kubectl on your control plane node.

      Note: While the Kubernetes documentation recommends you use the latest stable release of Kubernetes for your environment, this tutorial uses a specific version. This will ensure that you can follow the steps successfully, as Kubernetes changes rapidly and the latest version may not work with this tutorial. Although “xenial” is the name of Ubuntu 16.04, and this tutorial is for Ubuntu 20.04, Kubernetes is still referring to Ubuntu 16.04 package sources by default, and they are supported on 20.04 in this case.

      Save and close the file when you are finished.

      Next, run the playbook locally with the following command:

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

      On completion, you will receive output similar to the following:

      Output

      PLAY [all] **** TASK [Gathering Facts] **** ok: [worker1] ok: [worker2] ok: [control1] TASK [create Docker config directory] **** changed: [control1] changed: [worker1] changed: [worker2] TASK [changing Docker to systemd driver] **** changed: [control1] changed: [worker1] changed: [worker2] TASK [install Docker] **** changed: [control1] changed: [worker1] changed: [worker2] TASK [install APT Transport HTTPS] ***** ok: [control1] ok: [worker1] changed: [worker2] TASK [add Kubernetes apt-key] ***** changed: [control1] changed: [worker1] changed: [worker2] TASK [add Kubernetes' APT repository] ***** changed: [control1] changed: [worker1] changed: [worker2] TASK [install kubelet] ***** changed: [control1] changed: [worker1] changed: [worker2] TASK [install kubeadm] ***** changed: [control1] changed: [worker1] changed: [worker2] PLAY [control1] ***** TASK [Gathering Facts] ***** ok: [control1] TASK [install kubectl] ****** changed: [control1] PLAY RECAP **** control1 : ok=11 changed=9 unreachable=0 failed=0 worker1 : ok=9 changed=8 unreachable=0 failed=0 worker2 : ok=9 changed=8 unreachable=0 failed=0

      After running this playbook, Docker, kubeadm, and kubelet will be installed on all of the remote servers. kubectl is not a required component and is only needed for executing cluster commands. Installing it only on the control plane node makes sense in this context, since you will run kubectl commands only from the control plane. Note, however, that kubectl commands can be run from any of the worker nodes or from any machine where it can be installed and configured to point to a cluster.

      All system dependencies are now installed. Let’s set up the control plane node and initialize the cluster.

      Step 4 — Setting Up the Control Plane Node

      In this section, you will set up the control plane node. Before creating any playbooks, however, it’s worth covering a few concepts such as Pods and Pod Network Plugins, since your cluster will include both.

      A pod is an atomic unit that runs one or more containers. These containers share resources such as file volumes and network interfaces in common. Pods are the basic unit of scheduling in Kubernetes: all containers in a pod are guaranteed to run on the same node that the pod is scheduled on.

      Each pod has its own IP address, and a pod on one node should be able to access a pod on another node using the pod’s IP. Containers on a single node can communicate easily through a local interface. Communication between pods is more complicated, however, and requires a separate networking component that can transparently route traffic from a pod on one node to a pod on another.

      This functionality is provided by pod network plugins. For this cluster, you will use Flannel, a stable and performant option.

      Create an Ansible playbook named control-plane.yml on your local machine:

      • nano ~/kube-cluster/control-plane.yml

      Add the following play to the file to initialize the cluster and install Flannel:

      ~/kube-cluster/control-plane.yml

      ---
      - hosts: control_plane
        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/master/Documentation/kube-flannel.yml >> pod_network_setup.txt
            args:
              chdir: $HOME
              creates: pod_network_setup.txt
      

      Here’s a breakdown of this play:

      • The first task initializes the cluster by running kubeadm init. Passing the argument --pod-network-cidr=10.244.0.0/16 specifies the private subnet that the pod IPs will be assigned from. Flannel uses the above subnet by default; we’re telling kubeadm to use the same subnet.

      • The second task creates a .kube directory at /home/ubuntu. This directory will hold configuration information such as the admin key files, which are required to connect to the cluster, and the cluster’s API address.

      • The third task copies the /etc/kubernetes/admin.conf file that was generated from kubeadm init to your non-root user’s home directory. This will allow you to use kubectl to access the newly-created cluster.

      • The last task runs kubectl apply to install Flannel. kubectl apply -f descriptor.[yml|json] is the syntax for telling kubectl to create the objects described in the descriptor.[yml|json] file. The kube-flannel.yml file contains the descriptions of objects required for setting up Flannel in the cluster.

      Save and close the file when you are finished.

      Run the playbook locally with the following command:

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

      On completion, you will see output similar to the following:

      Output

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

      To check the status of the control plane node, SSH into it with the following command:

      • ssh ubuntu@control_plane_ip

      Once inside the control plane node, execute:

      You will now see the following output:

      Output

      NAME STATUS ROLES AGE VERSION control1 Ready control-plane,master 51s v1.22.4

      Note: As of Ubuntu 20.04, kubernetes is in the process of updating their old terminology. The node we’ve referred to as control-plane throughout this tutorial used to be called the master node, and occasionally you’ll see kubernetes assigning both roles simultaneously for compatibility reasons.

      The output states that the control-plane node has completed all initialization tasks and is in a Ready state from which it can start accepting worker nodes and executing tasks sent to the API Server. You can now add the workers from your local machine.

      Step 5 — Setting Up the Worker Nodes

      Adding workers to the cluster involves executing a single command on each. This command includes the necessary cluster information, such as the IP address and port of the control plane’s API Server, and a secure token. Only nodes that pass in the secure token will be able join the cluster.

      Navigate back to your workspace and create a playbook named workers.yml:

      • nano ~/kube-cluster/workers.yml

      Add the following text to the file to add the workers to the cluster:

      ~/kube-cluster/workers.yml

      ---
      - hosts: control_plane
        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['control1'].join_command }} >> node_joined.txt"
            args:
              chdir: $HOME
              creates: node_joined.txt
      

      Here’s what the playbook does:

      • The first play gets the join command that needs to be run on the worker nodes. This command will be in the following format:kubeadm join --token <token> <control-plane-ip>:<control-plane-port> --discovery-token-ca-cert-hash sha256:<hash>. Once it gets the actual command with the proper token and hash values, the task sets it as a fact so that the next play will be able to access that info.

      • The second play has a single task that runs the join command on all worker nodes. On completion of this task, the two worker nodes will be part of the cluster.

      Save and close the file when you are finished.

      Run the playbook by locally with the following command:

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

      On completion, you will see output similar to the following:

      Output

      PLAY [control1] **** TASK [get join command] **** changed: [control1] TASK [set join command] ***** ok: [control1] PLAY [workers] ***** TASK [Gathering Facts] ***** ok: [worker1] ok: [worker2] TASK [join cluster] ***** changed: [worker1] changed: [worker2] PLAY RECAP ***** control1 : 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

      With the addition of the worker nodes, your cluster is now fully set up and functional, with workers ready to run workloads. Before scheduling applications, let’s verify that the cluster is working as intended.

      Step 6 — Verifying the Cluster

      A cluster can sometimes fail during setup because a node is down or network connectivity between the control plane and workers is not working correctly. Let’s verify the cluster and ensure that the nodes are operating correctly.

      You will need to check the current state of the cluster from the control plane node to ensure that the nodes are ready. If you disconnected from the control plane node, you can SSH back into it with the following command:

      • ssh ubuntu@control_plane_ip

      Then execute the following command to get the status of the cluster:

      You will see output similar to the following:

      Output

      NAME STATUS ROLES AGE VERSION control1 Ready control-plane,master 3m21s v1.22.0 worker1 Ready <none> 32s v1.22.0 worker2 Ready <none> 32s v1.22.0

      If all of your nodes have the value Ready for STATUS, it means that they’re part of the cluster and ready to run workloads.

      If, however, a few of the nodes have NotReady as the STATUS, it could mean that the worker nodes haven’t finished their setup yet. Wait for around five to ten minutes before re-running kubectl get nodes and inspecting the new output. If a few nodes still have NotReady as the status, you might have to verify and re-run the commands in the previous steps.

      Now that your cluster is verified successfully, let’s schedule an example Nginx application on the cluster.

      Step 7 — Running An Application on the Cluster

      You can now deploy any containerized application to your cluster. To keep things familiar, let’s deploy Nginx using Deployments and Services to explore how this application can be deployed to the cluster. You can use the commands below for other containerized applications as well, provided you change the Docker image name and any relevant flags (such as ports and volumes).

      Ensure that you are logged into the control plane node and then and then run the following command to create a deployment named nginx:

      • kubectl create deployment nginx --image=nginx

      A deployment is a type of Kubernetes object that ensures there’s always a specified number of pods running based on a defined template, even if the pod crashes during the cluster’s lifetime. The above deployment will create a pod with one container from the Docker registry’s Nginx Docker Image.

      Next, run the following command to create a service named nginx that will expose the app publicly. It will do so through a NodePort, a scheme that will make the pod accessible through an arbitrary port opened on each node of the cluster:

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

      Services are another type of Kubernetes object that expose cluster internal services to clients, both internal and external. They are also capable of load balancing requests to multiple pods, and are an integral component in Kubernetes, frequently interacting with other components.

      Run the following command:

      This command will output text similar to the following:

      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

      From the highlighted line of the above output, you can retrieve the port that Nginx is running on. Kubernetes will assign a random port that is greater than 30000 automatically, while ensuring that the port is not already bound by another service.

      To test that everything is working, visit http://worker_1_ip:nginx_port or http://worker_2_ip:nginx_port through a browser on your local machine. You will see Nginx’s familiar welcome page.

      If you would like to remove the Nginx application, first delete the nginx service from the control plane node:

      • kubectl delete service nginx

      Run the following to ensure that the service has been deleted:

      You will see the following output:

      Output

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

      Then delete the deployment:

      • kubectl delete deployment nginx

      Run the following to confirm that this worked:

      Output

      No resources found.

      Conclusion

      In this guide, you’ve successfully set up a Kubernetes cluster on Ubuntu 20.04 using Kubeadm and Ansible for automation.

      If you’re wondering what to do with the cluster now that it’s set up, a good next step would be to get comfortable deploying your own applications and services onto the cluster. Here’s a list of links with further information that can guide you in the process:

      • Dockerizing applications - lists examples that detail how to containerize applications using Docker.

      • Pod Overview - describes in detail how Pods work and their relationship with other Kubernetes objects. Pods are ubiquitous in Kubernetes, so understanding them will facilitate your work.

      • Deployments Overview - provides an overview of deployments. It is useful to understand how controllers such as deployments work since they are used frequently in stateless applications for scaling and the automated healing of unhealthy applications.

      • Services Overview - covers services, another frequently used object in Kubernetes clusters. Understanding the types of services and the options they have is essential for running both stateless and stateful applications.

      Other important concepts that you can look into are Volumes, Ingresses and Secrets, all of which come in handy when deploying production applications.

      Kubernetes has a lot of functionality and features to offer. The Kubernetes Official Documentation is the best place to learn about concepts, find task-specific guides, and look up API references for various objects. You can also review our Kubernetes for Full-Stack Developers curriculum.



      Source link

      Как создать кластер Kubernetes с помощью Kubeadm в Ubuntu 16.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 — Установка зависимостей Kubernetes

      В этом разделе вы научитесь устанавливать требующиеся 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, которую нужно запустить на рабочих узлах. Эта команда имеет следующий формат: 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 node и проверьте полученные результаты. Если для некоторых узлов по-прежнему отображается статус 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 16.04, используя для автоматизации Kubeadm и Ansible.

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

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

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

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

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

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

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



      Source link

      Cómo crear un clúster de Kubernetes usando Kubeadm en Ubuntu 16.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 adicionales 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 contenedor.

      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 en contenedores 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 de 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. También configurará Ansible a nivel local para que pueda comunicarse con sus servidores remotos y ejecutar comandos en ellos. Para hacer esto, creará un archivo 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 IP worker_1_ip y worker_2_ip.

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

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

      Este directorio será su espacio de trabajo para el resto del tutorial y contendrá todos sus playbooks 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 aportará información específica 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
      

      Posiblemente 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.

      Después de configurar 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 sin privilegios. 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
      

      A continuación, se ofrece un desglose de las funciones de este playbook:

      • Crea el usuario no root ubuntu.

      • Configura el archivo sudoers para permitir que el usuario ubuntu ejecute comandos sudo sin una solicitud 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 después de agregar el texto.

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

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

      El comando se aplicará por completo en un plazo de dos a 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

      En esta sección, instalará los paquetes a nivel del sistema operativo requeridos por Kubernetes con el administrador de paquetes de Ubuntu. Estos paquetes son los siguientes:

      • Docker: 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 manera estándar.

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

      • kubectl: 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 en 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 termine.

      A continuación, active 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

      A lo largo de esta sección, configurará el nodo maestro. Sin embargo, antes de crear playbooks, 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 ejecuten 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 pueda 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 playbook 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 inicializa el clúster ejecutando kubeadm init. Al pasar el argumento --pod-network-cidr=10.244.0.0/16 se 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.

      • Con la segunda tarea se 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.

      • Con la tercera tarea se 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.

      • Con la última tarea se 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 termine.

      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 que ingrese en el 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 completó 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, podrá añadir los trabajadores desde su máquina local.

      Paso 5: Configurar los nodos del trabajador

      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 llamado workers.yml:

      • nano ~/kube-cluster/workers.yml

      Añada el siguiente texto al archivo para agregar 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 de hash adecuados, la tarea lo fija 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 trabajadores. Una vez que se complete esta tarea, los dos nodos de trabajo formarán parte del clúster.

      Guarde y cierre el archivo cuando termine.

      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

      Una vez agregados los nodos de trabajo, su clúster estará completamente configurado y activo, con los trabajadores listos para ejecutar cargas 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:

      Verá resultados similares al 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 todos sus nodos tienen el valor Ready para STATUS, 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, es posible que aún no haya concluido la configuración de los nodos de trabajo. Espere entre 5 y 10 minutos antes de volver a ejecutar kubectl get node 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 la verificación de su clúster se completó con éxito, programaremos una aplicación de Nginx de ejemplo en el clúster.

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

      Ahora podrá 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. Con la implementación anterior se 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. 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 clientes internos y 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 se ejecuta Nginx. 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 funcionó:

      Output

      No resources found.

      Conclusión

      A través de esta guía, configuró correctamente un clúster de Kubernetes en Ubuntu 16.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 los pods: explicación detallada de su funcionaminento 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: resumen sobre estas. 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 opción para aprender conceptos, encontrar guías específicas para tareas y buscar referencias de API para varios objetos.



      Source link