Guida rapida di GKE su Bare Metal

Introduzione a GKE su Bare Metal

Con GKE su Bare Metal, puoi definire quattro tipi di cluster:

  • admin: un cluster utilizzato per gestire i cluster utente.
  • utente: un cluster utilizzato per eseguire carichi di lavoro.
  • autonomo: un singolo cluster che può amministrare autonomamente e che può eseguire carichi di lavoro, ma non può creare o gestire altri cluster utente.
  • ibrido: un unico cluster sia per l'amministrazione che per i carichi di lavoro, che può anche gestire i cluster utente.

In questa guida rapida, eseguirai il deployment di un cluster ibrido a due nodi con GKE su Bare Metal. Imparerai a creare un cluster e a monitorare il relativo processo di creazione.

Questa guida rapida presuppone che tu abbia una conoscenza di base di Kubernetes.

Preparati per GKE su Bare Metal

Prima di creare un cluster in GKE su Bare Metal, devi eseguire le seguenti operazioni:

  1. Crea un progetto Google Cloud.
  2. Configura la tua workstation di amministrazione.

Crea un progetto Google Cloud

Per questa guida rapida, crea un nuovo progetto Google Cloud che organizzi tutte le risorse Google Cloud. Per creare un cluster in GKE su Bare Metal, devi avere un progetto Google Cloud in cui il tuo account ha il ruolo di proprietario.

Per i dettagli, consulta Creare e gestire progetti.

Configura una workstation di amministrazione Linux

Questa guida rapida utilizza bmctl e kubectl per creare e lavorare con un cluster. Questi strumenti a riga di comando vengono eseguiti su una workstation di amministrazione Linux. Per informazioni sulla configurazione della workstation di amministrazione, consulta Prerequisiti della workstation di amministrazione.

Crea i nodi del cluster

Crea due macchine che fungano da nodi per il tuo cluster:

  • Una macchina funge da nodo del piano di controllo.
  • Una macchina funziona come nodo worker.

Vai a Prerequisiti delle macchine dei nodi del cluster per saperne di più sui requisiti per i nodi cluster.

Crea un cluster

Per creare un cluster:

  1. Usa bmctl per creare un file di configurazione.
  2. Modifica il file di configurazione per personalizzarlo per il cluster e la rete.
  3. Usa bmctl per creare il cluster dal file di configurazione.

Creare un file di configurazione

Per creare un file di configurazione e abilitare automaticamente gli account di servizio e le API, assicurati di essere nella directory baremetal ed esegui il comando bmctl con i seguenti flag:

./bmctl create config -c CLUSTER_NAME \
  --enable-apis --create-service-accounts --project-id=PROJECT_ID

CLUSTER_NAME è il nome del tuo cluster. PROJECT_ID è il progetto che hai creato nella sezione Creare un progetto Google Cloud.

Il comando riportato sopra crea un file di configurazione nella directory baremetal nel seguente percorso: bmctl-workspace/cluster1/cluster1.yaml

Modifica il file di configurazione

Per modificare il file di configurazione:

  1. Apri il file di configurazione bmctl-workspace/cluster1/cluster1.yaml in un editor.
  2. Modifica il file con i tuoi requisiti specifici di rete e nodo. Utilizza il file di configurazione di esempio riportato di seguito come riferimento. Questa guida rapida non utilizza e non include informazioni su OpenID Connect (OIDC).
# gcrKeyPath:  < to GCR service account key>
gcrKeyPath: baremetal/gcr.json
# sshPrivateKeyPath:  < to SSH private key, used for node access>
sshPrivateKeyPath: .ssh/id_rsa
# gkeConnectAgentServiceAccountKeyPath:  < to Connect agent service account key>
gkeConnectAgentServiceAccountKeyPath: baremetal/connect-agent.json
# gkeConnectRegisterServiceAccountKeyPath:  < to Hub registration service account key>
gkeConnectRegisterServiceAccountKeyPath: baremetal/connect-register.json
# cloudOperationsServiceAccountKeyPath:  < to Cloud Operations service account key>
cloudOperationsServiceAccountKeyPath: baremetal/cloud-ops.json
---
apiVersion: v1
kind: Namespace
metadata:
  name: cluster-cluster1
---
# Cluster configuration. Note that some of these fields are immutable once the cluster is created.
# For more info, see https://cloud.google.com/anthos/clusters/docs/bare-metal/1.14/reference/cluster-config-ref#cluster_configuration_fields
apiVersion: baremetal.cluster.gke.io/v1
kind: Cluster
metadata:
  name: cluster1
  namespace: cluster-cluster1
spec:
  # Cluster type. This can be:
  #   1) admin:  to create an admin cluster. This can later be used to create user clusters.
  #   2) user:   to create a user cluster. Requires an existing admin cluster.
  #   3) hybrid: to create a hybrid cluster that runs admin cluster components and user workloads.
  #   4) standalone: to create a cluster that manages itself, runs user workloads, but does not manage other clusters.
  type: hybrid
  # Anthos cluster version.
  anthosBareMetalVersion: 1.14.11
  # GKE connect configuration
  gkeConnect:
    projectID: PROJECT_ID
  # Control plane configuration
  controlPlane:
    nodePoolSpec:
      nodes:
      # Control plane node pools. Typically, this is either a single machine
      # or 3 machines if using a high availability deployment.
      - address:  CONTROL_PLANE_NODE_IP
  # Cluster networking configuration
  clusterNetwork:
    # Pods specify the IP ranges from which pod networks are allocated.
    pods:
      cidrBlocks:
      - 192.168.0.0/16
    # Services specify the network ranges from which service virtual IPs are allocated.
    # This can be any RFC 1918 range that does not conflict with any other IP range
    # in the cluster and node pool resources.
    services:
      cidrBlocks:
      - 10.96.0.0/20
  # Load balancer configuration
  loadBalancer:
    # Load balancer mode can be either 'bundled' or 'manual'.
    # In 'bundled' mode a load balancer will be installed on load balancer nodes during cluster creation.
    # In 'manual' mode the cluster relies on a manually-configured external load balancer.
    mode: bundled
    # Load balancer port configuration
    ports:
      # Specifies the port the load balancer serves the Kubernetes control plane on.
      # In 'manual' mode the external load balancer must be listening on this port.
      controlPlaneLBPort: 443
    # There are two load balancer virtual IP (VIP) addresses: one for the control plane
    # and one for the L7 Ingress service. The VIPs must be in the same subnet as the load balancer nodes.
    # These IP addresses do not correspond to physical network interfaces.
    vips:
      # ControlPlaneVIP specifies the VIP to connect to the Kubernetes API server.
      # This address must not be in the address pools below.
      controlPlaneVIP: CONTROL_PLANE_VIP
      # IngressVIP specifies the VIP shared by all services for ingress traffic.
      # Allowed only in non-admin clusters.
      # This address must be in the address pools below.
      ingressVIP: INGRESS_VIP
    # AddressPools is a list of non-overlapping IP ranges for the data plane load balancer.
    # All addresses must be in the same subnet as the load balancer nodes.
    # Address pool configuration is only valid for 'bundled' LB mode in non-admin clusters.
    # addressPools:
    # - name: pool1
    #   addresses:
    #   # Each address must be either in the CIDR form (1.2.3.0/24)
    #   # or range form (1.2.3.1-1.2.3.5).
    #   - LOAD_BALANCER_ADDRESS_POOL-
    # A load balancer nodepool can be configured to specify nodes used for load balancing.
    # These nodes are part of the kubernetes cluster and run regular workloads as well as load balancers.
    # If the node pool config is absent then the control plane nodes are used.
    # Node pool configuration is only valid for 'bundled' LB mode.
    # nodePoolSpec:
    #   nodes:
    #   - address: LOAD_BALANCER_NODE_IP;
  # Proxy configuration
  # proxy:
  #   url: http://[username:password@]domain
  #   # A list of IPs, hostnames or domains that should not be proxied.
  #   noProxy:
  #   - 127.0.0.1
  #   - localhost
  # Logging and Monitoring
  clusterOperations:
    # Cloud project for logs and metrics.
    projectID: PROJECT_ID
    # Cloud location for logs and metrics.
    location: us-central1
    # Whether collection of application logs/metrics should be enabled (in addition to
    # collection of system logs/metrics which correspond to system components such as
    # Kubernetes control plane or cluster management agents).
    # enableApplication: false
  # Storage configuration
  storage:
    # lvpNodeMounts specifies the config for local PersistentVolumes backed by mounted disks.
    # These disks need to be formatted and mounted by the user, which can be done before or after
    # cluster creation.
    lvpNodeMounts:
      # path specifies the host machine path where mounted disks will be discovered and a local PV
      # will be created for each mount.
      path: /mnt/localpv-disk
      # storageClassName specifies the StorageClass that PVs will be created with. The StorageClass
      # is created during cluster creation.
      storageClassName: local-disks
    # lvpShare specifies the config for local PersistentVolumes backed by subdirectories in a shared filesystem.
    # These subdirectories are automatically created during cluster creation.
    lvpShare:
      # path specifies the host machine path where subdirectories will be created on each host. A local PV
      # will be created for each subdirectory.
      path: /mnt/localpv-share
      # storageClassName specifies the StorageClass that PVs will be created with. The StorageClass
      # is created during cluster creation.
      storageClassName: local-shared
      # numPVUnderSharedPath specifies the number of subdirectories to create under path.
      numPVUnderSharedPath: 5
  # NodeConfig specifies the configuration that applies to all nodes in the cluster.
  nodeConfig:
    # podDensity specifies the pod density configuration.
    podDensity:
      # maxPodsPerNode specifies the maximum number of pods allowed on a single node.
      maxPodsPerNode: 250

---
# Node pools for worker nodes
apiVersion: baremetal.cluster.gke.io/v1
kind: NodePool
metadata:
  name: node-pool-1
  namespace: cluster-cluster1
spec:
  clusterName: cluster1
  nodes:
  - address: WORKER_NODE_1_IP
  - address: WORKER_NODE_2_IP

Esegui i controlli preflight e crea il cluster

Il comando bmctl esegue controlli preflight sul file di configurazione del cluster prima di creare un cluster. Se i controlli hanno esito positivo, bmctl crea il cluster.

Per eseguire i controlli preflight e creare il cluster:

  1. Assicurati di essere nella directory baremetal.
  2. Utilizza il comando seguente per creare il cluster:
  3. ./bmctl create cluster -c CLUSTER_NAME
    
    Ad esempio:
    ./bmctl create cluster -c cluster1
    

    Il comando bmctl monitora i controlli preflight e la creazione del cluster, visualizza l'output sullo schermo e scrive informazioni dettagliate nei log bmctl.

Puoi trovare bmctl, controlli preflight e log di installazione dei nodi nella seguente directory: baremetal/bmctl-workspace/CLUSTER_NAME/log

Il preflight bmctl controlla l'installazione del cluster proposta per verificare le seguenti condizioni:

  • La distribuzione e la versione Linux sono supportate.
  • SELinux non è in modalità "enforcing".
  • Su Ubuntu, lo strumento UFW (Uncomplicated Firewall) non è attivo.
  • Google Container Registry è raggiungibile.
  • I VIP sono disponibili.
  • Le macchine cluster sono connesse tra loro.
  • Le macchine del bilanciatore del carico si trovano nella stessa subnet di livello 2.

La creazione del cluster può richiedere diversi minuti.

Recupera informazioni sul tuo cluster

Dopo aver creato correttamente un cluster, utilizza il comando kubectl per mostrare le informazioni sul nuovo cluster. Durante la creazione del cluster, il comando bmctl scrive un file kubeconfig per il cluster su cui puoi eseguire query con kubectl. Il file kubeconfig è scritto in bmctl-workspace/CLUSTER_NAME/CLUSTER_NAME-kubeconfig.

Ad esempio:

kubectl --kubeconfig bmctl-workspace/cluster1/cluster1-kubeconfig get nodes

Questo comando restituisce:

NAME      STATUS   ROLES    AGE   VERSION
node-01   Ready    master   16h   v1.17.8-gke.16
node-02   Ready    <none>   16h   v1.17.8-gke.16

Se la creazione del cluster non supera i controlli preflight, verifica la presenza di errori nei log dei controlli preflight e correggili nel file di configurazione del cluster. I log dei controlli preflight si trovano nella directory /log all'indirizzo

~/baremetal/bmctl-workspace/CLUSTER_NAME/log

I log dei controlli preflight per ogni macchina nel cluster si trovano nella directory CLUSTER_NAME e sono organizzati in base all'indirizzo IP. Ad esempio:

bmctl-workspace/cluster1/log
└── preflight-20201007-034844
    ├── 172.17.0.3
    ├── 172.17.0.4
    ├── 172.17.0.5
    ├── 172.17.0.6
    ├── 172.17.0.7
    └── node-network

Ignora gli errori di controllo pre-flight

Se la creazione del cluster non va a buon fine dopo i controlli pre-flight, puoi provare a reinstallarlo utilizzando il flag --force nel comando bmctl.

Il flag --force viene installato su un cluster esistente, ma ignora i risultati di qualsiasi errore del controllo preflight dovuto alle porte del server già allocate.

  1. Assicurati di essere nella directory baremetal.
  2. Utilizza il comando seguente con il flag --force per ricreare il cluster:
  3. ./bmctl create cluster -c CLUSTER_NAME --force
    
    Ad esempio:
    ./bmctl create cluster -c cluster1 --force

Crea un deployment e un servizio

Ecco un manifest per un deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  selector:
    matchLabels:
      app: metrics
      department: sales
  replicas: 3
  template:
    metadata:
      labels:
        app: metrics
        department: sales
    spec:
      containers:
      - name: hello
        image: "gcr.io/google-samples/hello-app:2.0"

Salva il file manifest con il nome my-deployment.yaml.

Crea il deployment con il comando seguente:

kubectl --kubeconfig bmctl-workspace/cluster1/cluster1-kubeconfig create -f my-deployment.yaml

Visualizza il deployment:

kubectl --kubeconfig bmctl-workspace/cluster1/cluster1-kubeconfig get deployments

L'output mostra che il deployment ha tre pod disponibili e pronti:

NAME               READY   UP-TO-DATE   AVAILABLE   AGE
my-deployment      3/3     3            3           16s

Il seguente manifest definisce un servizio di tipo LoadBalancer:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: metrics
    department: sales
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 8080

Salva il file manifest con il nome my-service.yaml.

Crea il servizio con il comando seguente:

kubectl --kubeconfig bmctl-workspace/cluster1/cluster1-kubeconfig create -f my-service.yaml

Visualizza il Servizio:

kubectl --kubeconfig bmctl-workspace/cluster1/cluster1-kubeconfig get service my-service

Output:

NAME         TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S
my-service   LoadBalancer   172.26.232.2   172.16.1.21   80:30060/TCP

GKE su Bare Metal assegna al servizio un indirizzo IP esterno. Utilizza l'indirizzo IP esterno per chiamare il servizio:

curl 172.16.1.21

L'output è un messaggio hello world:

Hello, world!
Version: 2.0.0
Hostname: my-deployment-75d45b64f9-6clxj

Crea un piano di controllo per l'alta disponibilità

La guida rapida ha creato un semplice cluster ibrido a due nodi. Se vuoi creare un piano di controllo ad alta disponibilità, crea un cluster che abbia tre nodi del piano di controllo.

Ad esempio, modifica il file di configurazione per aggiungere altri due nodi al piano di controllo:

controlPlane:
  nodePoolSpec:
    clusterName: cluster1
    nodes:
    # Control Plane node pools. Typically, this is either a single machine
    # or 3 machines if using a high availability deployment.
    - address: <Machine 1 IP>
    - address: <Machine 2 IP>
    - address: <Machine 3 IP>

Esegui il bilanciatore del carico nel proprio pool di nodi

La guida rapida ha creato un semplice cluster ibrido a due nodi. Pertanto, il bilanciatore del carico viene eseguito sullo stesso nodo che esegue il piano di controllo.

Se vuoi che il bilanciatore del carico venga eseguito nel proprio pool di nodi, modifica i valori nodePoolSpec della sezione loadBalancer del file di configurazione:

  loadBalancer:
    nodePoolSpec:
      clusterName: "cluster1"
      nodes:
      - address: <LB Machine 1 IP>
      - address: <LB Machine 2 IP>