Implantação de um aglomerado Kubernetes

Fonte: Pt Ikoula wiki
Revisão em 12h11min de 25 de outubro de 2021 por Cbrochot1072d (discussão | contribs)
(dif) ← Revisão anterior | Revisão atual (dif) | Revisão seguinte → (dif)
Ir para navegação Ir para pesquisar

ro:Implementarea unui cluster Kubernetes ru:Развертывание кластера Kubernetes pl:Wdrażanie klastra Kubernetes ja:Kubernetesクラスタのデプロイ zh:部署一个Kubernetes集群 de:Bereitstellen eines Kubernetes-Clusters nl:Een Kubernetes cluster implementeren fr:Deployer un cluster Kubernetes
Este artigo foi traduzido por um sistema de tradução automática. Você pode visualizar a fonte do artigo aqui.

es:Despliegue de un clúster Kubernetes en:Deploying a Kubernetes cluster it:Configurare un cluster Kubernetes fr:Deployer un cluster Kubernetes


O que é Kubernetes?

Kubernetes é uma plataforma de código aberto para a gestão de cargas de trabalho e serviços de contentores. Apoia a escrita da configuração declarativa mas também a automatização. Kubernetes é um ecossistema grande e em rápido crescimento.


Este procedimento permitir-lhe-á implantar rápida e facilmente um agrupamento de três nós Kubernetes (k8s) Este procedimento permitir-lhe-á implantar rápida e facilmente um agrupamento de três nós a partir de três CentOS 7, implantados dentro da mesma rede numa zona de avanço.


Um destes três casos será o nosso nó mestre e os outros dois serão os nossos nós de trabalhadores. Em resumo, o nó mestre é o nó a partir do qual gerimos o aglomerado Kubernetes (orquestrador de contentores) a partir do seu API e os nós operários são os nós sobre os quais as cápsulas ou contentores (Docker no nosso caso) irão funcionar.


Assumiremos que os seus 3 CentOS 7 já estão implantados e que tem acesso ssh a eles para executar os comandos que se seguirão.


Aqui está a configuração que temos no nosso exemplo e que será utilizada como exemplo ao longo de todo este procedimento:


Node master: "k8s-master" / 10.1.1.16
Primeiro trabalhador do nó: "k8s-worker01" / 10.1.1.1.169
Trabalhador do segundo nó: "k8s-worker02" / 10.1.1.87


Tutorial de preparação do sistema e instalação de Kubernetes

As seguintes acções devem ser realizadas em todas as instâncias (mestre e trabalhadores) como raiz (ou com os necessários direitos de sudo).


Comece por preencher o ficheiro /etc/hosts em cada uma das suas instâncias para que possam resolver o respectivo hostname (normalmente já o caso numa rede de zona avançada onde o router virtual é um resolvedor DNS).


No nosso exemplo, isto dá o seguinte ficheiro /etc/hosts sobre as nossas três instâncias (adapte-o com o nome e ip das suas instâncias):

cat /etc/hosts
127.0.0.1   localhost
::1         localhost

10.1.1.16 k8s-master
10.1.1.169 k8s-worker01
10.1.1.87 k8s-worker02


Activar o módulo de ponte e as regras do iptables para ele com os três comandos seguintes:

modprobe bridge
echo "net.bridge.bridge-nf-call-iptables = 1" >> /etc/sysctl.conf
sysctl -p /etc/sysctl.conf


Adicionar o repositório YUM Docker :

cat <<EOF > /etc/yum.repos.d/docker.repo
[docker-ce-stable]
name=Docker CE Stable - \$basearch
baseurl=https://download.docker.com/linux/centos/7/\$basearch/stable
enabled=1
gpgcheck=1
gpgkey=https://download.docker.com/linux/centos/gpg
EOF


Acrescentar o repositório YUM Kubernetes :

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg
        https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF


Instalar o Docker :

yum install -y docker-ce


Em seguida, instalar os pacotes Kubernetes necessários:

yum install -y kubeadm kubelet kubectl


Editar o ficheiro de configuração do sistemad kubelet (/etc/systemd/system/kubelet.service.d/10-kubeadm.conf) para adicionar a seguinte linha na secção "[Service]":

Environment="KUBELET_CGROUP_ARGS=--cgroup-driver=cgroupfs"


de tal forma que :

cat /etc/systemd/system/kubelet.service.d/10-kubeadm.conf
# Note: This dropin only works with kubeadm and kubelet v1.11+
[Service]
Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf"
Environment="KUBELET_CONFIG_ARGS=--config=/var/lib/kubelet/config.yaml"
*Environment="KUBELET_CGROUP_ARGS=--cgroup-driver=cgroupfs"*
# This is a file that "kubeadm init" and "kubeadm join" generates at runtime, populating the KUBELET_KUBEADM_ARGS variable dynamically
EnvironmentFile=-/var/lib/kubelet/kubeadm-flags.env
# This is a file that the user can use for overrides of the kubelet args as a last resort. Preferably, the user should use
# the .NodeRegistration.KubeletExtraArgs object in the configuration files instead. KUBELET_EXTRA_ARGS should be sourced from this file.
EnvironmentFile=-/etc/sysconfig/kubelet
ExecStart=
ExecStart=/usr/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_KUBEADM_ARGS $KUBELET_EXTRA_ARGS


Recarregar a configuração, activar e depois iniciar os serviços de estivador e kubelet através dos três comandos seguintes:


systemctl daemon-reload systemctl permite kubelet docker kubelet systemctl start docker kubelet </syntaxhighlight>


Desactivar a troca do sistema (kubelet não suporta memória swap, obterá um erro durante as verificações pré-voo ao inicializar o seu cluster via kubeadms se não o desactivar):

swapoff -a


lembre-se também de comentar/remover a linha swap no ficheiro /etc/fstab de cada uma das suas instâncias, tais como :

#/dev/mapper/vg01-swap  swap            swap    defaults                0       0

Inicialização do aglomerado Kubernetes

As seguintes acções devem ser realizadas apenas na instância mestre do nó


Comece a inicialização do seu cluster Kubernetes através do comando abaixo, tendo o cuidado de modificar o valor do parâmetro "--apiserver-advertise-advertise-address=" pelo endereço ip da sua instância principal.

kubeadm init --apiserver-advertise-address=<ip de votre instance master> --pod-network-cidr=10.244.0.0/16

Nota: Por favor não modificar o ip de rede "10.244.0.0/16" indicado no parâmetro "--pod-network-cidr=" porque este parâmetro permite-nos indicar que vamos utilizar o plugin CNI Flannel para gerir a parte de rede das nossas cápsulas.


Eis como deve ser o regresso deste comando quando o agrupamento se inicializa com sucesso:

[root@k8s-master ~]# kubeadm init --apiserver-advertise-address=10.1.1.16 --pod-network-cidr=10.244.0.0/16
[init] using Kubernetes version: v1.12.2
[preflight] running pre-flight checks
[preflight/images] Pulling images required for setting up a Kubernetes cluster
[preflight/images] This might take a minute or two, depending on the speed of your internet connection
[preflight/images] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[preflight] Activating the kubelet service
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [k8s-master.cs437cloud.internal kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 10.1.1.16]
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Generated etcd/ca certificate and key.
[certificates] Generated etcd/server certificate and key.
[certificates] etcd/server serving cert is signed for DNS names [k8s-master.cs437cloud.internal localhost] and IPs [127.0.0.1 ::1]
[certificates] Generated etcd/peer certificate and key.
[certificates] etcd/peer serving cert is signed for DNS names [k8s-master.cs437cloud.internal localhost] and IPs [10.1.1.16 127.0.0.1 ::1]
[certificates] Generated etcd/healthcheck-client certificate and key.
[certificates] Generated apiserver-etcd-client certificate and key.
[certificates] valid certificates and keys now exist in "/etc/kubernetes/pki"
[certificates] Generated sa key and public key.
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/scheduler.conf"
[controlplane] wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests"
[init] this might take a minute or longer if the control plane images have to be pulled
[apiclient] All control plane components are healthy after 32.502898 seconds
[uploadconfig] storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.12" in namespace kube-system with the configuration for the kubelets in the cluster
[markmaster] Marking the node k8s-master.cs437cloud.internal as master by adding the label "node-role.kubernetes.io/master=''"
[markmaster] Marking the node k8s-master.cs437cloud.internal as master by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s-master.cs437cloud.internal" as an annotation
[bootstraptoken] using token: e83pes.u3igpccj2metetu8
[bootstraptoken] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstraptoken] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstraptoken] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstraptoken] creating the "cluster-info" ConfigMap in the "kube-public" namespace
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes master 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/

You can now join any number of machines by running the following on each node
as root:

  kubeadm join 10.1.1.16:6443 --token e83pes.u3igpccj2metetu8 --discovery-token-ca-cert-hash sha256:7ea9169bc5ac77b3a2ec37e5129006d9a895ce040e306f3093ce77e7422f7f1c


Realizamos as operações solicitadas a fim de finalizar a inicialização do nosso agrupamento:


Criamos um directório e um ficheiro de configuração no directório do nosso utilizador (raiz no nosso caso):

mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config


Implementamos a nossa rede de flanelas para o nosso agrupamento:

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.extensions/kube-flannel-ds-amd64 created
daemonset.extensions/kube-flannel-ds-arm64 created
daemonset.extensions/kube-flannel-ds-arm created
daemonset.extensions/kube-flannel-ds-ppc64le created
daemonset.extensions/kube-flannel-ds-s390x created

nota: manteremos o último comando fornecido pelo retorno do comando de inicialização lateral ("kubeadm join...") a fim de o executarmos nas nossas instâncias de trabalhadores para mais tarde os juntarmos ao nosso agrupamento.


Podemos agora fazer as primeiras verificações do nosso agrupamento a partir da nossa instância principal:

Digite o comando "kubectl get nodes" para verificar os nós actualmente presentes no seu agrupamento:

[root@k8s-master ~]# kubectl get nodes
NAME                             STATUS   ROLES    AGE   VERSION
k8s-master.cs437cloud.internal   Ready    master   41m   v1.12.2

Nota: actualmente só existe o seu nó mestre, o que é normal uma vez que ainda não adicionámos os outros nós ao aglomerado.


Digite o comando "kubectl get pods --all-namespaces" para verificar as cápsulas/contentores actualmente presentes no seu agrupamento:

[root@k8s-master ~]# kubectl get pods --all-namespaces
NAMESPACE     NAME                                                     READY   STATUS    RESTARTS   AGE
kube-system   coredns-576cbf47c7-fwxj9                                 1/1     Running   0          41m
kube-system   coredns-576cbf47c7-t86s9                                 1/1     Running   0          41m
kube-system   etcd-k8s-master.cs437cloud.internal                      1/1     Running   0          41m
kube-system   kube-apiserver-k8s-master.cs437cloud.internal            1/1     Running   0          41m
kube-system   kube-controller-manager-k8s-master.cs437cloud.internal   1/1     Running   0          41m
kube-system   kube-flannel-ds-amd64-wcm7v                              1/1     Running   0          84s
kube-system   kube-proxy-h94bs                                         1/1     Running   0          41m
kube-system   kube-scheduler-k8s-master.cs437cloud.internal            1/1     Running   0          40m

Nota: Só há cápsulas correspondentes aos componentes Kubernetes necessários para o nosso nó mestre (kube-apiserver, etcd, kube-scheduler, etc).


Podemos verificar o estado destes componentes com o seguinte comando:

[root@k8s-master ~]# kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
scheduler            Healthy   ok
controller-manager   Healthy   ok
etcd-0               Healthy   {"health": "true"}

Acrescentar nós de trabalhadores ao aglomerado

Acções a serem realizadas apenas em instâncias/nós de trabalhadores

Em cada uma das suas instâncias operárias (não o faça na sua instância principal), execute o comando "kubeadm join ..." fornecido no final da inicialização do seu cluster acima:

[root@k8s-worker01 ~]# kubeadm join 10.1.1.16:6443 --token e83pes.u3igpccj2metetu8 --discovery-token-ca-cert-hash sha256:7ea9169bc5ac77b3a2ec37e5129006d9a895ce040e306f3093ce77e7422f7f1c
[preflight] running pre-flight checks
        [WARNING RequiredIPVSKernelModulesAvailable]: the IPVS proxier will not be used, because the following required kernel modules are not loaded: [ip_vs_sh ip_vs ip_vs_rr ip_vs_wrr] or no builtin kernel ipvs support: map[ip_vs:{} ip_vs_rr:{} ip_vs_wrr:{} ip_vs_sh:{} nf_conntrack_ipv4:{}]
you can solve this problem with following methods:
 1. Run 'modprobe -- ' to load missing kernel modules;
2. Provide the missing builtin kernel ipvs support

[discovery] Trying to connect to API Server "10.1.1.16:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://10.1.1.16:6443"
[discovery] Requesting info from "https://10.1.1.16:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "10.1.1.16:6443"
[discovery] Successfully established connection with API Server "10.1.1.16:6443"
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.12" ConfigMap in the kube-system namespace
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[preflight] Activating the kubelet service
[tlsbootstrap] Waiting for the kubelet to perform the TLS Bootstrap...
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s-worker01.cs437cloud.internal" as an annotation

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 master to see this node join the cluster.
[root@k8s-worker02 ~]# kubeadm join 10.1.1.16:6443 --token e83pes.u3igpccj2metetu8 --discovery-token-ca-cert-hash sha256:7ea9169bc5ac77b3a2ec37e5129006d9a895ce040e306f3093ce77e7422f7f1c
[preflight] running pre-flight checks
        [WARNING RequiredIPVSKernelModulesAvailable]: the IPVS proxier will not be used, because the following required kernel modules are not loaded: [ip_vs_wrr ip_vs_sh ip_vs ip_vs_rr] or no builtin kernel ipvs support: map[ip_vs:{} ip_vs_rr:{} ip_vs_wrr:{} ip_vs_sh:{} nf_conntrack_ipv4:{}]
you can solve this problem with following methods:
 1. Run 'modprobe -- ' to load missing kernel modules;
2. Provide the missing builtin kernel ipvs support

[discovery] Trying to connect to API Server "10.1.1.16:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://10.1.1.16:6443"
[discovery] Requesting info from "https://10.1.1.16:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "10.1.1.16:6443"
[discovery] Successfully established connection with API Server "10.1.1.16:6443"
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.12" ConfigMap in the kube-system namespace
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[preflight] Activating the kubelet service
[tlsbootstrap] Waiting for the kubelet to perform the TLS Bootstrap...
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8s-worker02.cs437cloud.internal" as an annotation

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 master to see this node join the cluster.

Verificação do estado do agrupamento

Acções a realizar a partir da instância principal/nó


Verifique se os seus nós de trabalhadores foram adicionados ao seu agrupamento, reexecutando o comando "kubectl get nodes":

[root@k8s-master ~]# kubectl get nodes
NAME                               STATUS   ROLES    AGE    VERSION
k8s-master.cs437cloud.internal     Ready    master   46m    v1.12.2
k8s-worker01.cs437cloud.internal   Ready    <none>   103s   v1.12.2
k8s-worker02.cs437cloud.internal   Ready    <none>   48s    v1.12.2

Observação : Podemos ver os nossos dois nós trabalhadores (k8s-worker01 e k8s-worker02), pelo que foram adicionados ao nosso aglomerado.


Vamos agora executar novamente o comando "kubectl get pods --all-namespaces":

[root@k8s-master ~]# kubectl get pods --all-namespaces
NAMESPACE     NAME                                                     READY   STATUS    RESTARTS   AGE
kube-system   coredns-576cbf47c7-fwxj9                                 1/1     Running   0          46m
kube-system   coredns-576cbf47c7-t86s9                                 1/1     Running   0          46m
kube-system   etcd-k8s-master.cs437cloud.internal                      1/1     Running   0          46m
kube-system   kube-apiserver-k8s-master.cs437cloud.internal            1/1     Running   0          46m
kube-system   kube-controller-manager-k8s-master.cs437cloud.internal   1/1     Running   0          46m
kube-system   kube-flannel-ds-amd64-724nl                              1/1     Running   0          2m6s
kube-system   kube-flannel-ds-amd64-wcm7v                              1/1     Running   0          6m31s
kube-system   kube-flannel-ds-amd64-z7mwg                              1/1     Running   3          70s
kube-system   kube-proxy-8r7wg                                         1/1     Running   0          2m6s
kube-system   kube-proxy-h94bs                                         1/1     Running   0          46m
kube-system   kube-proxy-m2f5r                                         1/1     Running   0          70s
kube-system   kube-scheduler-k8s-master.cs437cloud.internal            1/1     Running   0          46m

Nota: Pode ver que existem tantos "kube-flannel" e "kube-proxy" vagens/contentores como nós temos nós no nosso agrupamento.

Implantação de uma primeira cápsula

Vamos destacar o nosso primeiro cápsula no nosso aglomerado de Kubernetes.


Para simplificar, optamos por implantar uma cápsula (sem réplicas) denominada "nginx" e utilizando a imagem "nginx":

[root@k8s-master ~]# kubectl create deployment nginx --image=nginx
deployment.apps/nginx created


Se verificarmos, este aparece bem no regresso do comando listando as cápsulas do nosso agrupamento:

[root@k8s-master ~]# kubectl get pods --all-namespaces
NAMESPACE     NAME                                                     READY   STATUS    RESTARTS   AGE
default       nginx-55bd7c9fd-5bghl                                    1/1     Running   0          104s
kube-system   coredns-576cbf47c7-fwxj9                                 1/1     Running   0          57m
kube-system   coredns-576cbf47c7-t86s9                                 1/1     Running   0          57m
kube-system   etcd-k8s-master.cs437cloud.internal                      1/1     Running   0          57m
kube-system   kube-apiserver-k8s-master.cs437cloud.internal            1/1     Running   0          57m
kube-system   kube-controller-manager-k8s-master.cs437cloud.internal   1/1     Running   0          57m
kube-system   kube-flannel-ds-amd64-724nl                              1/1     Running   0          13m
kube-system   kube-flannel-ds-amd64-wcm7v                              1/1     Running   0          17m
kube-system   kube-flannel-ds-amd64-z7mwg                              1/1     Running   3          12m
kube-system   kube-proxy-8r7wg                                         1/1     Running   0          13m
kube-system   kube-proxy-h94bs                                         1/1     Running   0          57m
kube-system   kube-proxy-m2f5r                                         1/1     Running   0          12m
kube-system   kube-scheduler-k8s-master.cs437cloud.internal            1/1     Running   0          57m

Aparece no topo da lista num espaço de nomes diferente de "kube-system", uma vez que não é um componente específico do funcionamento de Kubernetes.


Também é possível evitar a exibição de cápsulas específicas para o namespace do sistema kube-system, executando este mesmo comando sem o parâmetro "--all-namespace":

[root@k8s-master ~]# kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
nginx-55bd7c9fd-vs4fq     1/1     Running   0          3d2h


Para exibir as etiquetas :

[root@k8s-master ~]# kubectl get pods --show-labels
NAME                      READY   STATUS    RESTARTS   AGE    LABELS
nginx-55bd7c9fd-ckltn     1/1     Running   0          8m2s   app=nginx,pod-template-hash=55bd7c9fd


Podemos também verificar os nossos destacamentos com o seguinte comando:

[root@k8s-master ~]# kubectl get deployments
NAME    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx   1         1         1            1           93m


Assim, temos uma cápsula nginx implantada e iniciada, mas ainda não está acessível a partir do exterior. Para o tornar acessível externamente, precisamos de expor o porto da nossa cápsula, criando o serviço (do tipo NodePort) através do seguinte comando:

[root@k8s-master ~]# kubectl create service nodeport nginx --tcp=80:80
service/nginx created


O nosso serviço é assim criado:

[root@k8s-master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        147m
nginx        NodePort    10.108.251.178   <none>        80:30566/TCP   20s

Nota: Ouve na porta 80/tcp e estará disponível/exposta do exterior na porta 30566/tcp


Podemos obter o ip de flanela da nossa cápsula e o nome do nó em que ela está actualmente a correr através do seguinte comando:

[root@k8s-master ~]# kubectl get pods --selector="app=nginx" --output=wide
NAME                    READY   STATUS    RESTARTS   AGE    IP           NODE                               NOMINATED NODE
nginx-55bd7c9fd-vs4fq   1/1     Running   0          174m   10.244.2.2   k8s-worker02.cs437cloud.internal   <none>

Aqui o nosso nginx pod tem o ip 10.244.2.2 e funciona no nosso nó k8s-worker02.


Também pode simplesmente executar um comando ou abrir uma concha na nossa cápsula nginx através do seguinte comando (muito semelhante ao comando do estivador):

[root@k8s-master ~]# kubectl exec -it nginx-55bd7c9fd-vs4fq -- /bin/bash
root@nginx-55bd7c9fd-vs4fq:/#


Tudo o que tem de fazer é criar a sua regra de equilíbrio de carga na sua rede Ikoula One Cloud para aceder / tornar público o seu servidor web (nginx pod):

- Ligue-se ao Cloud Ikoula One

- ir para "Rede" no menu vertical esquerdo

- clique na sua rede na qual implantou as suas instâncias Kubernetes, depois em "Ver Endereços IP" e no seu IP de Origem NAT e vá para o separador "Configuração

- clique em "Load Balancing" e crie a sua regra especificando um nome, a porta pública "80" no nosso caso, a porta privada "30566" no nosso caso (ver acima), escolhendo um algoritmo LB (por exemplo, round-robin) tal como :


Instância Kubernetes


- assinale todas as instâncias do seu trabalhador:


Verifique as suas instâncias de trabalhadores kubernetes


Teste o acesso ao seu servidor web / nginx pod a partir do seu browser (através do ip público da sua rede em que criou a regra LB):


Acesso ao seu servidor web


O facto de o seu nginx pod poder ser acedido a partir de qualquer um dos seus nós é tornado possível pelo componente "kube-proxy", que é responsável por apontar ligações para o(s) nó(s) em que está a funcionar (no caso de réplicas).


Assim, acabam de implementar um aglomerado básico de Kubernetes de 3 nós com um mestre e dois trabalhadores.

Vá mais longe

Pode ir mais longe implantando o painel de instrumentos Kubernetes ou criando volumes persistentes para as suas cápsulas, aumentando o número de nós de trabalhadores, ou mesmo atribuindo redundantemente o papel principal para alta disponibilidade ou dedicando nós a certos componentes como Etcd, por exemplo.


Aqui estão alguns links úteis:


https://kubernetes.io/docs/reference/kubectl/cheatsheet/

https://kubernetes.io/docs/reference/kubectl/docker-cli-to-kubectl/

https://kubernetes.io/docs/concepts/storage/volumes/

https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/

https://kubernetes.io/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/

https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/