- How to Install Kubernetes on Mac
- Installation Guide
- Come Together
- Learn Kube Faster. Get the #1 guide.
- Meet the Author
- Install Tools
- kubectl
- minikube
- kubeadm
- Feedback
- Install and Set Up kubectl on macOS
- Before you begin
- Install kubectl on macOS
- Install kubectl binary with curl on macOS
- Install with Homebrew on macOS
- Install with Macports on macOS
- Verify kubectl configuration
- Optional kubectl configurations and plugins
- Enable shell autocompletion
- Introduction
- Upgrade Bash
- Install bash-completion
- Enable kubectl autocompletion
- Install kubectl convert plugin
- Установка и настройка kubectl
- Подготовка к работе
- Установка kubectl в Linux
- Установка двоичного файла kubectl с помощью curl в Linux
- Установка с помощью встроенного пакетного менеджера
- Установка с помощью стороннего пакетного менеджера
- Установка kubectl в macOS
- Установка двоичного файла kubectl с помощью curl в macOS
- Установка с помощью Homebrew в macOS
- Установка с помощью Macports в macOS
- Установка kubectl в Windows
- Установка двоичного файла kubectl с помощью curl в Windows
- Установка с помощью Powershell из PSGallery
- Установка в Windows с помощью Chocolatey или Scoop
- Установка kubectl из SDK Google Cloud
- Проверка конфигурации kubectl
- Дополнительная конфигурация kubectl
- Включение автодополнения ввода shell
- Основные сведения
- Установка bash-completion
- Включение автодополнения ввода kubectl
- Основные сведения
- Установка bash-completion
- Включение автодополнения ввода kubectl
- Что дальше
- Обратная связь
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.
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.
Install Tools
kubectl
The Kubernetes command-line tool, kubectl, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs. For more information including a complete list of kubectl operations, see the kubectl reference documentation.
kubectl is installable on a variety of Linux platforms, macOS and Windows. Find your preferred operating system below.
kind lets you run Kubernetes on your local computer. This tool requires that you have Docker installed and configured.
The kind Quick Start page shows you what you need to do to get up and running with kind.
minikube
Like kind , minikube is a tool that lets you run Kubernetes locally. minikube runs a single-node Kubernetes cluster on your personal computer (including Windows, macOS and Linux PCs) so that you can try out Kubernetes, or for daily development work.
You can follow the official Get Started! guide if your focus is on getting the tool installed.
Once you have minikube working, you can use it to run a sample application.
kubeadm
You can use the kubeadm tool to create and manage Kubernetes clusters. It performs the actions necessary to get a minimum viable, secure cluster up and running in a user friendly way.
Installing kubeadm shows you how to install kubeadm. Once installed, you can use it to create a cluster.
Feedback
Was this page helpful?
Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it on Stack Overflow. Open an issue in the GitHub repo if you want to report a problem or suggest an improvement.
Install and Set Up kubectl on macOS
Before you begin
You must use a kubectl version that is within one minor version difference of your cluster. For example, a v1.25 client can communicate with v1.24, v1.25, and v1.26 control planes. Using the latest compatible version of kubectl helps avoid unforeseen issues.
Install kubectl on macOS
The following methods exist for installing kubectl on macOS:
Install kubectl binary with curl on macOS
Download the latest release:
To download a specific version, replace the $(curl -L -s https://dl.k8s.io/release/stable.txt) portion of the command with the specific version.
For example, to download version v1.25.0 on Intel macOS, type:
And for macOS on Apple Silicon, type:
Validate the binary (optional)
Download the kubectl checksum file:
Validate the kubectl binary against the checksum file:
If valid, the output is:
If the check fails, shasum exits with nonzero status and prints output similar to:
Make the kubectl binary executable.
Move the kubectl binary to a file location on your system PATH .
Test to ensure the version you installed is up-to-date:
Or use this for detailed view of version:
Install with Homebrew on macOS
If you are on macOS and using Homebrew package manager, you can install kubectl with Homebrew.
Run the installation command:
Test to ensure the version you installed is up-to-date:
Install with Macports on macOS
If you are on macOS and using Macports package manager, you can install kubectl with Macports.
Run the installation command:
Test to ensure the version you installed is up-to-date:
Verify kubectl configuration
In order for kubectl to find and access a Kubernetes cluster, it needs a kubeconfig file, which is created automatically when you create a cluster using kube-up.sh or successfully deploy a Minikube cluster. By default, kubectl configuration is located at
Check that kubectl is properly configured by getting the cluster state:
If you see a URL response, kubectl is correctly configured to access your cluster.
If you see a message similar to the following, kubectl is not configured correctly or is not able to connect to a Kubernetes cluster.
For example, if you are intending to run a Kubernetes cluster on your laptop (locally), you will need a tool like Minikube to be installed first and then re-run the commands stated above.
If kubectl cluster-info returns the url response but you can’t access your cluster, to check whether it is configured properly, use:
Optional kubectl configurations and plugins
Enable shell autocompletion
kubectl provides autocompletion support for Bash, Zsh, Fish, and PowerShell which can save you a lot of typing.
Below are the procedures to set up autocompletion for Bash, Fish, and Zsh.
Introduction
The kubectl completion script for Bash can be generated with kubectl completion bash . Sourcing this script in your shell enables kubectl completion.
However, the kubectl completion script depends on bash-completion which you thus have to previously install.
Upgrade Bash
The instructions here assume you use Bash 4.1+. You can check your Bash’s version by running:
If it is too old, you can install/upgrade it using Homebrew:
Reload your shell and verify that the desired version is being used:
Homebrew usually installs it at /usr/local/bin/bash .
Install bash-completion
You can test if you have bash-completion v2 already installed with type _init_completion . If not, you can install it with Homebrew:
As stated in the output of this command, add the following to your
Reload your shell and verify that bash-completion v2 is correctly installed with type _init_completion .
Enable kubectl autocompletion
You now have to ensure that the kubectl completion script gets sourced in all your shell sessions. There are multiple ways to achieve this:
Source the completion script in your
Add the completion script to the /usr/local/etc/bash_completion.d directory:
If you have an alias for kubectl, you can extend shell completion to work with that alias:
If you installed kubectl with Homebrew (as explained here), then the kubectl completion script should already be in /usr/local/etc/bash_completion.d/kubectl . In that case, you don’t need to do anything.
In any case, after reloading your shell, kubectl completion should be working.
The kubectl completion script for Fish can be generated with the command kubectl completion fish . Sourcing the completion script in your shell enables kubectl autocompletion.
To do so in all your shell sessions, add the following line to your
After reloading your shell, kubectl autocompletion should be working.
The kubectl completion script for Zsh can be generated with the command kubectl completion zsh . Sourcing the completion script in your shell enables kubectl autocompletion.
To do so in all your shell sessions, add the following to your
If you have an alias for kubectl, kubectl autocompletion will automatically work with it.
After reloading your shell, kubectl autocompletion should be working.
If you get an error like 2: command not found: compdef , then add the following to the beginning of your
Install kubectl convert plugin
A plugin for Kubernetes command-line tool kubectl , which allows you to convert manifests between different API versions. This can be particularly helpful to migrate manifests to a non-deprecated api version with newer Kubernetes release. For more info, visit migrate to non deprecated apis
Download the latest release with the command:
Установка и настройка kubectl
Инструмент командной строки Kubernetes kubectl позволяет запускать команды для кластеров Kubernetes. Вы можете использовать kubectl для развертывания приложений, проверки и управления ресурсов кластера, а также для просмотра логов. Полный список операций kubectl смотрите в Overview of kubectl.
Подготовка к работе
Используемая вами мажорная версия kubectl не должна отличаться от той, которая используется в кластере. Например, версия v1.2 может работать с версиями v1.1, v1.2 и v1.3. Использование последней версии kubectl поможет избежать непредвиденных проблем.
Установка kubectl в Linux
Установка двоичного файла kubectl с помощью curl в Linux
Загрузите последнюю версию с помощью команды:
Чтобы загрузить определенную версию, вставьте в фрагмент команды $(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt) нужную версию.
Например, команда загрузки версии v1.25.0 для Linux будет выглядеть следующим образом:
Сделайте двоичный файл kubectl исполняемым:
Переместите двоичный файл в директорию из переменной окружения PATH:
Убедитесь, что установлена последняя версия:
Установка с помощью встроенного пакетного менеджера
Установка с помощью стороннего пакетного менеджера
Если вы используйте Ubuntu или другой Linux-дистрибутив, в котором есть пакетный менеджер snap, kubectl доступен в виде приложения snap.
Если вы работаете в Linux и используете пакетный менеджер Homebrew, то kubectl можно установить через него.
Установка kubectl в macOS
Установка двоичного файла kubectl с помощью curl в macOS
Загрузите последнюю версию:
Чтобы загрузить определенную версию, вставьте в фрагмент команды $(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt) нужную версию.
Например, команда загрузки версии v1.25.0 для macOS будет выглядеть следующим образом:
Сделайте двоичный файл kubectl исполняемым:
Переместите двоичный файл в директорию из переменной окружения PATH:
Убедитесь, что установлена последняя версия:
Установка с помощью Homebrew в macOS
Если вы используете macOS и Homebrew, то kubectl можно установить с помощью пакетного менеджера Homebrew.
Выполните команду установки:
Убедитесь, что установлена последняя версия:
Установка с помощью Macports в macOS
Если вы используйте macOS и Macports, то kubectl можно установить с помощью пакетного менеджера Macports.
Выполните команду установки:
Убедитесь, что установлена последняя версия:
Установка kubectl в Windows
Установка двоичного файла kubectl с помощью curl в Windows
Загрузите последнюю версию v1.25.0 по этой ссылке.
Либо, если у вас установлен curl , выполните команду ниже:
Последнюю стабильную версию (например, при написании скриптов) вы можете узнать из файла по ссылке https://storage.googleapis.com/kubernetes-release/release/stable.txt.
Переместите двоичный файл в директорию из переменной окружения PATH:
Убедитесь, что версия kubectl совпадает загружённой:
Установка с помощью Powershell из PSGallery
Если вы работаете в Windows и используете менеджер пакетов Powershell Gallery, вы можете установить и обновить kubectl с помощью Powershell.
Выполните команды по установке (обязательно укажите DownloadLocation ):
Установщик создаст $HOME/.kube вместе с конфигурационным файлом.
Убедитесь, что установлена последняя версия:
Установка в Windows с помощью Chocolatey или Scoop
Для установки kubectl в Windows вы можете использовать либо менеджер пакетов Chocolatey , либо установщик в командной строке Scoop.
Перейдите в домашнюю директорию:
Создайте директорию .kube :
Перейдите в созданную только что директорию .kube :
Настройте kubectl, чтобы возможно было использовать удаленный кластер Kubernetes:
Установка kubectl из SDK Google Cloud
Вы можете использовать kubectl из SDK Google Cloud, который использует этот CLI-инструмент.
Выполните команду для установки kubectl :
Убедитесь, что установлена последняя версия:
Проверка конфигурации kubectl
Чтобы kubectl мог найти и получить доступ к кластеру Kubernetes, нужен файл kubeconfig, который создаётся автоматически при создании кластера с помощью скрипта kube-up.sh или при успешном развертывании кластера Minikube. По умолчанию конфигурация kubectl находится в
Посмотрите на состояние кластера, чтобы убедиться, что kubectl правильно сконфигурирован:
Если вы видите URL-ответ, значит kubectl корректно настроен для работы с вашим кластером.
Если вы видите сообщение следующего содержания, то значит kubectl настроен некорректно или не может подключиться к кластеру Kubernetes:
Например, если вы собираетесь запустить кластер Kubernetes на своем ноутбуке (локально), вам потребуется сначала установить специальный для этого инструмент, например Minikube, а затем снова выполнить указанные выше команды.
Если команда kubectl cluster-info возвращает URL-ответ, но вы не можете подключиться к своему кластеру, чтобы убедиться, что он правильно настроен, воспользуйтесь этой командой:
Дополнительная конфигурация kubectl
Включение автодополнения ввода shell
kubectl поддерживает автодополнение (автозаполнение) ввода в Bash и Zsh, которое сэкономит вам много времени на набор команд.
Ниже приведены инструкции по настройке автодополнения для Bash (для Linux и macOS) и Zsh.
Основные сведения
Скрипт дополнения ввода kubectl для Bash может быть сгенерирован с помощью команды kubectl completion bash . Подключение скрипта дополнения ввода в вашу оболочку включает поддержку автозаполнения ввода для kubectl.
Однако скрипт дополнения ввода зависит от bash-completion, поэтому вам нужно сначала установить этот пакет (вы можете выполнить команду type _init_completion , чтобы проверить, установлен ли у вас уже bash-completion).
Установка bash-completion
bash-completion можно установить через многие менеджеры пакеты (см. здесь). Вы можете установить его с помощью apt-get install bash-completion или yum install bash-completion и т.д.
Приведенные выше команды создадут файл /usr/share/bash-completion/bash_completion , который является основным скриптом bash-completion. В зависимости от используемого менеджера пакетов, вы можете подключить этот файл в файле
Чтобы убедиться, что этот скрипт выполняется, перезагрузите оболочку и выполните команду type _init_completion . Если команда отработала успешно, установка сделана правильно, в противном случае добавьте следующее содержимое в файл
Перезагрузите вашу оболочку и убедитесь, что bash-completion правильно установлен, напечатав в терминале type _init_completion .
Включение автодополнения ввода kubectl
Теперь нужно убедиться, что скрипт дополнения ввода kubectl выполняется во всех сессиях командной оболочки. Есть два способа сделать это:
Добавьте запуск скрипта дополнения ввода в файл
Добавьте скрипт дополнения ввода в директорию /etc/bash_completion.d :
Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки:
Оба подхода эквивалентны. После перезагрузки вашей оболочки, должны появляться дополнения ввода kubectl.
Основные сведения
Скрипт дополнения ввода kubectl для Bash может быть сгенерирован с помощью команды kubectl completion bash . Подключение скрипта дополнения ввода в вашей оболочке включает поддержку автозаполнения ввода для kubectl.
Однако скрипт дополнения ввода kubectl зависит от пакета bash-completion, который первым делом нужно установить.
Установка bash-completion
Вы можете проверить, установлен ли у вас bash-completion v2, набрав команду type _init_completion . Если он не установлен, вы можете сделать это с помощью Homebrew:
Как указано в выводе этой команды, добавьте следующий код в файл
Перезагрузите вашу командную оболочку и убедитесь, что bash-completion v2 корректно установлен, напечатав в терминале type _init_completion .
Включение автодополнения ввода kubectl
Теперь нужно убедиться, что скрипт дополнения ввода kubectl выполняется во всех сессиях командной оболочки. Есть два способа сделать это:
Добавьте запуск скрипта дополнения ввода в файл
Добавьте скрипт дополнения ввода в директорию /etc/bash_completion.d :
Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки:
Если вы установили kubectl с помощью Homebrew (как описано выше), то скрипт дополнения ввода kubectl уже должен быть находится в /usr/local/etc/bash_completion.d/kubectl . В этом случае вам не нужно ничего делать.
Какой вариант бы вы не выбрали, после перезагрузки командной оболочки, дополнение ввода kubectl должно заработать.
Скрипт дополнения ввода kubectl для Zsh может быть сгенерирован с помощью команды kubectl completion zsh . Подключение скрипта дополнения ввода в вашу оболочку включает поддержку автозаполнения ввода для kubectl.
Чтобы подключить его во все сессии командной оболочки, добавьте следующую строчку в файл
Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки:
После перезагрузки командной оболочки должны появляться дополнения ввода kubectl.
Если появляется такая ошибка как complete:13: command not found: compdef , то добавьте следующее содержимое в начало вашего файла
Что дальше
- Установка Minikube
- Смотрите руководства по установке, чтобы узнать больше про создание кластеров.
- Learn how to launch and expose your application.
- Если у вас нет доступа к кластеру, который не создавали, посмотрите страницу Совместный доступ к кластеру.
- Read the kubectl reference docs
Обратная связь
Была ли эта страница полезной?
Спасибо за отзыв! Если у вас есть конкретный вопрос об использовании Kubernetes, спрашивайте Stack Overflow. Сообщите о проблеме в репозитории GitHub, если вы хотите сообщить о проблеме или предложить улучшение.