Установка minikube в Unix/Linux

Minikube реализует локальный кластер Kubernetes на MacOS или Linux ОС. Основные цели minikube — стать лучшим инструментом для разработки локальных приложений Kubernetes и поддерживать все подходящие функции Kubernetes.

Установка minikube на MacOS

Чтобы проверить, поддерживается ли виртуализация в вашей macOS, выполните следующую команду на своем терминале:

$ sysctl -a | grep -E --color 'machdep.cpu.features|VMX'
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX SMX EST TM2 SSSE3 FMA CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC MOVBE POPCNT AES PCID XSAVE OSXSAVE SEGLIM64 TSCTMR AVX1.0 RDRAND F16C

Как видно с моего вывода — у меня имеется все необходимое.

-=== СПОСОБ 1 ===-

Устанавливаем homebrew, статья тут — установка homebrew

А затем можно вводить комнду:

$ brew cask install minikube

-=== СПОСОБ 2 ===-

Также можно установить его на macOS, загрузив отдельный двоичный файл:

$ sudo curl -Lo /usr/local/bin/minikube https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64 \
  && sudo chmod +x /usr/local/bin/minikube

Проверим версию можно так:

$ minikube version
minikube version: v1.4.0
commit: 7969c25a98a018b94ea87d949350f3271e9d64b6

Вот так вот!

Настройка minikube в Unix/Linux

Чтобы проверить, поддерживается ли виртуализация в Linux, выполните следующую команду и убедитесь, что выходные данные не пусты:

$ grep -E --color 'vmx|svm' /proc/cpuinfo

Затем стоит установить kubectl. Далее, стоит установить гипервизер, например kvm или virtualbox:

Установить Virtualbox на Centos/Fedora

Установить VirtualBox на Ubuntu/Debian или Linux Mint

Установка гипервизора KVM на Debian/Ubuntu

Например, можно выполнить установку KVM так, но для этого установим пакет:

$ sudo apt install cpu-checker && sudo kvm-ok

Если после запуска kvm-ok вы получите следующий вывод, вы можете использовать KVM на своем компьютере (в противном случае проверьте свою конфигурацию):

$ sudo kvm-ok
INFO: /dev/kvm exists
KVM acceleration can be used

Теперь давайте установим KVM и libvirt и добавим нашего текущего пользователя в группу libvirt для предоставления достаточных разрешений:

$ sudo apt install libvirt-clients libvirt-daemon-system qemu-kvm \
    && sudo usermod -a -G libvirt $(whoami) \
    && newgrp libvirt

После установки libvirt вы можете проверить допустимость хоста для запуска виртуальных машин с помощью инструмента virt-host-validate, который является частью libvirt:

$ sudo virt-host-validate

Ставим kubectl:

$ curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl \
    && sudo install kubectl /usr/local/bin && rm kubectl

Если KVM используется в качестве единственного драйвера для Minikube на нашей машине, более удобно установить его в качестве драйвера по умолчанию и запускать Minikube с меньшим количеством аргументов командной строки. Следующая команда устанавливает драйвер KVM по умолчанию:

$ minikube config set vm-driver kvm2

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

$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 \
  && chmod +x minikube

Вот простой способ добавить исполняемый файл Minikube к вашему пути:

$ sudo mkdir -p /usr/local/bin/ && \
install minikube /usr/local/bin/

Можно проверить версию утилиты:

$ minikube version

Установка выполнена.

Работа с minikube в Unix/Linux

Запуск очень простой:

$ minikube start

Но можно указать количество ядер и сколько оперативной памяти выделить миникубу:

$ minikube start --cpus 6 --memory 8192
😄  minikube v1.2.0 on darwin (amd64)
👍  minikube will upgrade the local cluster from Kubernetes 1.10.0 to 1.15.0
💿  Downloading Minikube ISO ...
 129.33 MB / 129.33 MB [============================================] 100.00% 0s
💡  Tip: Use 'minikube start -p <name>' to create a new cluster, or 'minikube delete' to delete this one.
🔄  Restarting existing virtualbox VM for "minikube" ...
⌛  Waiting for SSH access ...
🐳  Configuring environment for Kubernetes v1.15.0 on Docker 17.12.1-ce
💾  Downloading kubeadm v1.15.0
💾  Downloading kubelet v1.15.0
🚜  Pulling images ...
🔄  Relaunching Kubernetes v1.15.0 using kubeadm ...
⌛  Verifying: apiserver proxy etcd scheduler controller dns
🏄  Done! kubectl is now configured to use "minikube"

PS: Запуск был выполнен на МакОС, а в качестве гипервизера был выбрал virtualbox.

Можно получить следующую ошибку:

machine does not exist

Решение:

$ minikube delete && minikube start

Чтобы проверить статус, выполните:

$ minikube status

Если есть необходимость удалить стек, выполните:

$ minikube delete
🔥  Deleting "minikube" in virtualbox ...
💔  The "minikube" cluster has been deleted.

Для помощи, выполняем:

$ minikube --help
Minikube is a CLI tool that provisions and manages single-node Kubernetes clusters optimized for development workflows.

Basic Commands:
  start          Starts a local kubernetes cluster
  status         Gets the status of a local kubernetes cluster
  stop           Stops a running local kubernetes cluster
  delete         Deletes a local kubernetes cluster
  dashboard      Access the kubernetes dashboard running within the minikube cluster

Images Commands:
  docker-env     Sets up docker env variables; similar to '$(docker-machine env)'
  cache          Add or delete an image from the local cache.

Configuration and Management Commands:
  addons         Modify minikube's kubernetes addons
  config         Modify minikube config
  profile        Profile gets or sets the current minikube profile
  update-context Verify the IP address of the running cluster in kubeconfig.

Networking and Connectivity Commands:
  service        Gets the kubernetes URL(s) for the specified service in your local cluster
  tunnel         tunnel makes services of type LoadBalancer accessible on localhost

Advanced Commands:
  mount          Mounts the specified directory into minikube
  ssh            Log into or run a command on a machine with SSH; similar to 'docker-machine ssh'
  kubectl        Run kubectl

Troubleshooting Commands:
  ssh-key        Retrieve the ssh identity key path of the specified cluster
  ip             Retrieves the IP address of the running cluster
  logs           Gets the logs of the running instance, used for debugging minikube, not user code.
  update-check   Print current and latest version number
  version        Print the version of minikube

Other Commands:
  completion     Outputs minikube shell completion for the given shell (bash or zsh)

Use "minikube <command> --help" for more information about a given command.

Или конкретно для какой-то команды:

$ minikube start --help
Starts a local kubernetes cluster

Options:
      --apiserver-ips=[]: A set of apiserver IP Addresses which are used in the generated certificate for kubernetes.
This can be used if you want to make the apiserver available from outside the machine
      --apiserver-name='minikubeCA': The apiserver name which is used in the generated certificate for kubernetes.  This
can be used if you want to make the apiserver available from outside the machine
      --apiserver-names=[]: A set of apiserver names which are used in the generated certificate for kubernetes.  This
can be used if you want to make the apiserver available from outside the machine
      --apiserver-port=8443: The apiserver listening port
      --cache-images=true: If true, cache docker images for the current bootstrapper and load them into the machine.
Always false with --vm-driver=none.
      --container-runtime='docker': The container runtime to be used (docker, crio, containerd).
      --cpus=2: Number of CPUs allocated to the minikube VM.
      --cri-socket='': The cri socket path to be used.
      --disable-driver-mounts=false: Disables the filesystem mounts provided by the hypervisors
      --disk-size='20000mb': Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or
g).
      --dns-domain='cluster.local': The cluster dns domain name used in the kubernetes cluster
      --dns-proxy=false: Enable proxy for NAT DNS requests (virtualbox driver only)
      --docker-env=[]: Environment variables to pass to the Docker daemon. (format: key=value)
      --docker-opt=[]: Specify arbitrary flags to pass to the Docker daemon. (format: key=value)
      --download-only=false: If true, only download and cache files for later use - don't install or start anything.
      --embed-certs=false: if true, will embed the certs in kubeconfig.
      --enable-default-cni=false: Enable the default CNI plugin (/etc/cni/net.d/k8s.conf). Used in conjunction with
"--network-plugin=cni".
      --extra-config=: A set of key=value pairs that describe configuration that may be passed to different components.
		The key should be '.' separated, and the first part before the dot is the component to apply the configuration to.
		Valid components are: kubelet, kubeadm, apiserver, controller-manager, etcd, proxy, scheduler
		Valid kubeadm parameters: ignore-preflight-errors, dry-run, kubeconfig, kubeconfig-dir, node-name, cri-socket,
experimental-upload-certs, certificate-key, rootfs, pod-network-cidr
      --feature-gates='': A set of key=value pairs that describe feature gates for alpha/experimental features.
      --force=false: Force minikube to perform possibly dangerous operations
      --host-dns-resolver=true: Enable host resolver for NAT DNS requests (virtualbox driver only)
      --host-only-cidr='192.168.99.1/24': The CIDR to be used for the minikube VM (virtualbox driver only)
      --hyperkit-vpnkit-sock='': Location of the VPNKit socket used for networking. If empty, disables Hyperkit
VPNKitSock, if 'auto' uses Docker for Mac VPNKit connection, otherwise uses the specified VSock (hyperkit driver only)
      --hyperkit-vsock-ports=[]: List of guest VSock ports that should be exposed as sockets on the host (hyperkit
driver only)
      --hyperv-virtual-switch='': The hyperv virtual switch name. Defaults to first found. (hyperv driver only)
      --image-mirror-country='': Country code of the image mirror to be used. Leave empty to use the global one. For
Chinese mainland users, set it to cn.
      --image-repository='': Alternative image repository to pull docker images from. This can be used when you have
limited access to gcr.io. Set it to "auto" to let minikube decide one for you. For Chinese mainland users, you may use
local gcr.io mirrors such as registry.cn-hangzhou.aliyuncs.com/google_containers
      --insecure-registry=[]: Insecure Docker registries to pass to the Docker daemon.  The default service CIDR range
will automatically be added.
      --interactive=true: Allow user prompts for more information
      --iso-url='https://storage.googleapis.com/minikube/iso/minikube-v1.4.0.iso': Location of the minikube iso.
      --keep-context=false: This will keep the existing kubectl context and will create a minikube context.
      --kubernetes-version='v1.16.0': The kubernetes version that the minikube VM will use (ex: v1.2.3)
      --kvm-gpu=false: Enable experimental NVIDIA GPU support in minikube
      --kvm-hidden=false: Hide the hypervisor signature from the guest in minikube (kvm2 driver only)
      --kvm-network='default': The KVM network name. (kvm2 driver only)
      --kvm-qemu-uri='qemu:///system': The KVM QEMU connection URI. (kvm2 driver only)
      --memory='2000mb': Amount of RAM allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or
g).
      --mount=false: This will start the mount daemon and automatically mount files into minikube.
      --mount-string='/Users:/minikube-host': The argument to pass the minikube mount command on start.
      --native-ssh=true: Use native Golang SSH client (default true). Set to 'false' to use the command line 'ssh'
command when accessing the docker machine. Useful for the machine drivers when they will not start with 'Waiting for
SSH'.
      --network-plugin='': The name of the network plugin.
      --nfs-share=[]: Local folders to share with Guest via NFS mounts (hyperkit driver only)
      --nfs-shares-root='/nfsshares': Where to root the NFS Shares, defaults to /nfsshares (hyperkit driver only)
      --no-vtx-check=false: Disable checking for the availability of hardware virtualization before the vm is started
(virtualbox driver only)
      --registry-mirror=[]: Registry mirrors to pass to the Docker daemon
      --service-cluster-ip-range='10.96.0.0/12': The CIDR to be used for service cluster IPs.
      --uuid='': Provide VM UUID to restore MAC address (hyperkit driver only)
      --vm-driver='': Driver is one of: [virtualbox parallels vmwarefusion hyperkit vmware] (defaults to virtualbox)
      --wait=true: Wait until Kubernetes core services are healthy before exiting.
      --wait-timeout=6m0s: max time to wait per Kubernetes core services to be healthy.

Usage:
  minikube start [flags] [options]

Use "minikube start options" for a list of global command-line options (applies to all commands).

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

Давайте проверим, работает ли кластер Kubernetes:

$ kubectl get nodes

Теперь давайте запустим простой пример приложения (в нашем случае nginx):

$ kubectl create deployment nginx --image=nginx

Давайте также проверим, правильно ли настроены pods в Kubernetes:

$ kubectl get pods

Вот и все, статья «Установка minikube в Unix/Linux» завершена.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.