Kubernetes install mac os

How to Install Kubernetes on Mac

This is a step-by-step guide to installing and running Kubernetes on your Mac so that you can develop applications locally.

You will be guided through running and accessing a Kubernetes cluster on your local machine using the following tools:

  • Homebrew
  • Docker for Mac
  • Minikube
  • virtualbox
  • kubectl

Installation Guide

The only pre-requisite for this guide is that you have Homebrew installed. Homebrew is a package manager for the Mac. You’ll also need Homebrew Cask, which you can install after Homebrew by running brew tap caskroom/cask in your Terminal.

Install Docker for Mac. Docker is used to create, manage, and run our containers. It lets us construct containers that will run in Kubernetes Pods.

Install VirtualBox for Mac using Homebrew. Run brew cask install virtualbox in your Terminal. VirtualBox lets you run virtual machines on your Mac (like running Windows inside macOS, except for a Kubernetes cluster.)

Skip to step three if everything has worked to this point.

In my case, I already had the non-Homebrew VirtualBox app installed which caused issues when trying to start minikube.

If you already have VirtualBox installed, start the installation as before with brew cask install virtualbox . You will get a warning that confirms this saying Warning: Cask ‘virtualbox’ is already installed. . Once this is confirmed, you can reinstall VirtualBox with Homebrew by running brew cask reinstall virtualbox .

If you happen to have VirtualBox already running when you do this, you could see an error saying Failed to unload org.virtualbox.kext.VBoxDrv — (libkern/kext) kext is in use or retained (cannot unload).

This is because the kernel extensions that VirtualBox uses were in use when the uninstall occurred. If you scroll up in the output of that command, beneath Warning! Found the following active VirtualBox processes: you’ll see a list of the processes that need to be killed.

Kill each of these in turn by running kill first_column_number ( first_column_number is the process identifier for that process).

Now re-run brew cask reinstall virtualbox and it should succeed.

Install kubectl for Mac. This is the command-line interface that lets you interact with Kuberentes. Run brew install kubectl in your Terminal.

Install Minikube via the Installation > OSX instructions from the latest release. At the time of writing, this meant running the following command in Terminal…

Minikube will run a Kubernetes cluster with a single node.

Everything should work! Start your Minikube cluster with minikube start . Then run kubectl api-versions . If you see a list of versions, everything’s working! minikube start might take a few minutes.

At this point, I got an error saying Error starting host: Error getting state for host: machine does not exist. because I had previously tried to run Minikube. You can fix this by running open

/.minikube/ to open Minikube’s data files, and then deleting and deleting the machines directory. Then run minikube start again.

Come Together

You’ve installed all these tools and everything looks like it’s working. A quick explanation of how the components relate is needed.

  • VirtualBox is a generic tool for running virtual machines. You can use it to run Ubuntu, Windows, etc. inside your macOS operating system host.
  • Minikube is a Kubernetes-specific package that runs a Kubernetes cluster on your machine. That cluster has a single node and has some unique features that make it more suitable for local development. Minikube tells VirtualBox to run. Minikube can use other virtualization tools—not just VirtualBox—however these require extra configuration.
  • kubectl is the command line application that lets you interact with your Minikube Kubernetes cluster. It sends request to the Kubernetes API server running on the cluser to manage your Kubernetes environment. kubectl is like any other application that runs on your Mac—it just makes HTTP requests to the Kubernetes API on the cluster.
Читайте также:  Rs 232 com порт usb драйвер windows 10

Learn Kube Faster.
Get the #1 guide.

Get my book on Kubernetes for software developers, used by engineers at Google, Microsoft, and IBM.

Meet the Author

Matthew Palmer is a software developer and author. He’s created popular desktop apps, scaled SaaS web services, and taught Computer Science students at the University of New South Wales.

Источник

Local Kubernetes for Mac– MiniKube vs Docker Desktop

In the previous articles of the series, we have seen the local Kubernetes solutions for Windows and Linux. In this article, we talk about MacOS and take a look at Docker Desktop and Minikube.

Similar to the Windows version, Docker for Mac provides an out of the box solution using a native virtualization system. Docker for Mac is very easy to install, but it also comes with limited configuration options.

On the other hand, Minikube has more complete Kubernetes support with multiple add-ons and driver support (e.g. VirtualBox) at the cost of a more complicated configuration.

Docker on Mac with Kubernetes support

Kubernetes is available in Docker for Mac for 18.06 Stable or higher and includes a Kubernetes server and client, as well as integration with the Docker executable. The Kubernetes server runs locally within your Docker instance and it is similar to the Docker on Windows solution. Notice that Docker on Mac uses a native MacOS virtualization system called Hyperkit.

When Kubernetes support is enabled, you can deploy new workloads not only on Kubernetes but also on Swarm and as standalone containers, without affecting any of your existing workloads.

Installation

As mentioned already, Kubernetes is included in the Docker on Mac binary so it installed automatically with it. You can download and install Docker for Mac from the Docker Store.

Note: If you already use a previous version of Docker (e.g. docker toolbox ), or an older version of Docker on Mac, we strongly recommend upgrading to the newer version, instead of having multiple docker installations versions active. If for some reason you cannot upgrade, you should be able to use Minikube instead.

After a successful installation, you need to explicitly enable Kubernetes support. Click the Docker icon in the status bar, go to “Preferences”, and on the “Kubernetes” tab check “Enable Kubernetes” as shown in the figure below.

This will start a single node Kubernetes cluster for you and install the kubectl command line utility as well. This might take a while, but the dialog will let you know once the Kubernetes cluster is ready.

Management

Now you are ready to deploy your workloads similar to Windows. If you are working with multiple Kubernetes clusters and different environments you should already be familiar with switching contexts. You can view contexts using the kubectl config command:

Set the context to use as docker-for-desktop :

Unfortunately, (as was the case with the Windows version), the bundled Kubernetes distribution does not come with its dashboardenabled. You need to enable it with the following command:

To view the dashboard in your web browser run:

Deployment

Deploying an application it is very straightforward. In the following example, we install a cluster of nginx servers using the commands:

Once Kubernetes completed downloading the containers, you can see the containers running by using the command:

Читайте также:  Virtual box как установить windows

You can view the dashboard, as mentioned before, to verify that nginx was indeed installed and your cluster is in working mode.

Kubernetes on Mac using Minikube

As another alternative to Docker-for-Mac, we can also use Minikube to set up and operate a single node Kubernetes cluster as a local development environment. Minikube for Mac supports multiple hypervisors such as VirtualBox, VMWare, and Hyperkit. In this tutorial, we are talking about the installation mode that uses VirtualBox. (If Hyperkit is available then Docker-for-Mac is easier to install.)

Installation

Instead of manually installing all the needed packages for Minikube, it is easier to install all prerequisites using the Homebrew package manager. If you don’t have the Homebrew package manager already installed, you can easily install it using the following command in the terminal application:

This will also include prerequisites such as Xcode command line tools.
To install Minikube itself including the prerequisites, we execute the following command:

After completion, the following packages will be installed in your machine:

Management

After successful installation, you can start Minikube by executing the following command in your terminal:

Now Minikube is started and you have created a Kubernetes context called “minikube”, which is set by default during startup. You can switch between contexts using the command:

Furthermore, to access the Kubernetes dashboard, you need to execute/run the following command:

Additional information, on how to configure and manage the Kubernetes cluster can be found in the official documentation.

Deployment

Deploying an application is the same for all drivers supported in Minikube. For example, you can deploy, expose, and scale a service using the usual kubectl commands, as provided in the Minikube Tutorial.

You can view the workloads of your Minikube cluster either through the Kubernetes dashboard or using the command line interface — kubectl. For example, to see the deployed pods you can use the command:

Conclusion

After looking at both solutions, here are our results…

Minikube is a mature solution available for all major operating systems. Its main advantage is that it provides a unified way of working with a local Kubernetes cluster regardless of the operating system. It is perfect for people that are using multiple OS machines and have some basic familiarity with Kubernetes and Docker.

  • Mature solution
  • Works on Windows (any version and edition), Mac, and Linux
  • Multiple drivers that can match any environment
  • Installs several plugins (such as dashboard) by default
  • Very flexible on installation requirements and upgrades
  • Installation and removal not as streamlined as other solutions
  • Does not integrate into the MacOS UI

Docker Desktop for Mac is a very user-friendly solution with good integration for the MacOS UI.

  • Very easy installation for beginners
  • All-in-one Docker and Kubernetes solution
  • Configurable via UI
  • Relatively new, possibly unstable
  • Limited configuration options (i.e. driver support)

Let us know in the comments which local Kubernetes solution you are using and why.

Thomas Pliakas is a passionate Java software engineer, where he likes to work in performance improvements in each phase of the project life cycle. He has primarily been working on architecting, developing, and tuning low latency and high throughput telco products. He is also a co-organizer of Java Hellenic User Groups (jhug) meetups.

Источник

Начало работы в Kubernetes с помощью Minikube

Предисловие переводчика: Minikube — удобный инструмент, который мы применяем в компании для локальных экспериментов с Kubernetes (в частности, для выполнения лабораторных работ по этой системе при обучении сотрудников). Эта статья показалась мне полезной во время моего знакомства с Kubernetes. Она написана год назад автором, использующим Mac OS X, а я проделывал все операции в Ubuntu 16.04 совсем недавно и с актуальными версиями основного софта: Minikube 0.20, Docker 17.06.0-ce, kubectl 1.7.0. Поэтому все выводы команд были переделаны под новые версии и незначительно отличаются от приведённых в оригинальной статье.
Kubernetes — система оркестровки контейнеров с открытым исходным кодом, готовая для production и предназначенная для автоматизации размещения, масштабирования и управления контейнерами.

Читайте также:  Безопасный режим работы компьютера windows

Это упрощенная версия руководства Hello Minikube, в которой Minikube используется для запуска локального кластера Kubernetes вместо Google Container Engine, благодаря чему отпадает необходимость в наличии облачной платформы.

Руководство написано под Mac OS X, но представленные ниже команды подойдут и для любой другой ОС. (Как уже отмечалось выше, всё было воспроизведено и адаптировано под Linux — прим. перев.)

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

    Проверьте, что ваша система поддерживает виртуализацию VT-x/AMD-v с помощью команды:

Если команда вернула непустой результат — можно продолжать.

Установите последний VirtualBox или VMware Fusion. В этом руководстве используется VirtualBox. Если вы устанавливали Docker Toolbox, то, возможно, у вас уже есть установленный VirtualBox.

    Проверить в Linux (Ubuntu/Debian):

Установите последний Minikube для вашей ОС и архитектуры:

Прим. перев.: sudo mv minikube /usr/local/bin/ можно убрать или поменять, если вы хотите использовать другой путь.

Установите kubectl для вашей ОС и архитектуры:

Прим. перев.: Для Ubuntu 16.04 и старше еще доступен snap-пакет:

Протестируйте свою инсталляцию Minikube

Мы можем увидеть список запущенных в кластере подов:

Установка пода hello-minikube

Проект Minikube на GitHub предлагает демо-версию для быстрого старта, использующую собранный Docker-образ hello-minikube . Так как мы уже запустили кластер, то первый шаг ( minikube start ) можно пропустить.

Теперь давайте запустим встроенный под hello-minikube . Для этого пода будет создан предварительно настроенный deployment:

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

Для доступа к сервису hello-minikube нужно открыть ему внешний IP командой:

Примечание: необходимо использовать тип NodePort , т.к. Minikube не поддерживает сервис LoadBalancer . Так можно убедиться, что сервис стал открыт:

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

Примечание: IP-адрес, который управляется VirtualBox’ом, может изменяться. Узнайте его с помощью команды minikube ip или в выводе ifconfig :

После того, как мы закончили с hello-minikube , можем удалить его deployment и сервис, освободив ресурсы и проверив, что все действительно удалено:

Сборка и установка сервиса с Docker

Этот пример несколько сложнее и описывает создание небольшого Node.js-сервера, сборки его в образ Docker с использованием Dockerfile и запуск в Kubernetes.

Создадим простой Node.js-проект hello-node :

Создадим простой HTTP-сервер, который возвращает «Hello World!»:

Поправим Dockerfile , объявив, что образ использует node 4.4 и контейнер запускает сервис с помощью файла server.js :

Перед запуском каких-либо команд Docker нужно задать окружение. Аналогично запуску eval $(docker-machine env) , мы создаем переменные окружения Docker для Minikube с помощью команды minikube docker-env :

Теперь соберем образ. Это займет некоторое время, т.к. для разрешения зависимостей будут подгружены образы из Docker Hub, такие как node 4.4. По завершении вы получите новый Docker-образ, готовый к деплою (завершающая точка . в конце команды говорит Docker собрать образ из текущей директории ­— прим. перев.):

Теперь мы можем разместить под hello-node в локальный кластер Kubernetes с помощью kubectl :

Как и прежде, необходимо присвоить сервису внешний IP и порт, чтобы получить к нему доступ с помощью curl :

Победа! Мы успешно написали, собрали и разместили простой сервис Node.js, используя Docker-образ в локальном кластере Kubernetes.

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

Уборка

Не забудьте удалить сервис и deployment для hello-node и выключить службу minikube , когда закончите:

P.S. От переводчика

Более полную документацию по локальному запуску Kubernetes с Minikube можно найти на сайте проекта. Вам также могут быть интересны следующие статьи из нашего блога:

Источник

Оцените статью