在 Mac 上用 Vagrant 安装 K8s

文章目录

    • [📋 1. 环境准备](#📋 1. 环境准备)
      • [1.1 系统要求](#1.1 系统要求)
      • [1.2 软件清单](#1.2 软件清单)
    • [🚀 2. 安装步骤](#🚀 2. 安装步骤)
      • [2.1 安装Parallels Desktop](#2.1 安装Parallels Desktop)
      • [2.2 配置网络代理(可选)](#2.2 配置网络代理(可选))
      • [2.3 安装Homebrew](#2.3 安装Homebrew)
      • [2,4 准备项目目录](#2,4 准备项目目录)
      • [2.5 安装Vagrant及插件](#2.5 安装Vagrant及插件)
      • [2.6 配置Python环境](#2.6 配置Python环境)
        • [2.6.1 安装Python管理工具](#2.6.1 安装Python管理工具)
        • [2.6.2 配置Shell环境](#2.6.2 配置Shell环境)
        • [2.6.3 验证Python环境](#2.6.3 验证Python环境)
      • [2.6.4 安装 pyenv](#2.6.4 安装 pyenv)
      • [2.6.5 升级Python工具](#2.6.5 升级Python工具)
      • [2.6.6 创建Python虚拟环境](#2.6.6 创建Python虚拟环境)
      • [2.7 配置Kubespray](#2.7 配置Kubespray)
        • [2.7.1 配置核心配置文件](#2.7.1 配置核心配置文件)
          • [2.7.1.1 配置集群config.rb](#2.7.1.1 配置集群config.rb)
          • [2.7.1.2 配置 containerd.yml(可选)](#2.7.1.2 配置 containerd.yml(可选))
    • [🔧 3. 部署集群](#🔧 3. 部署集群)
      • [3.1 启动虚拟机并部署K8s](#3.1 启动虚拟机并部署K8s)
      • [3.2 如果部署失败,可以重试](#3.2 如果部署失败,可以重试)
    • [🎯 4. 配置kubectl访问](#🎯 4. 配置kubectl访问)
      • [4.1 安装kubectl客户端](#4.1 安装kubectl客户端)
      • [4.2 配置集群访问](#4.2 配置集群访问)
    • [📦 5. 安装Helm(可选)](#📦 5. 安装Helm(可选))
    • [🧹 6. 清理环境](#🧹 6. 清理环境)
      • [6.1 销毁虚拟机](#6.1 销毁虚拟机)
      • [6.2 退出Python虚拟环境](#6.2 退出Python虚拟环境)
    • [🛠️ 7. 故障排除](#🛠️ 7. 故障排除)
      • [7.1 常见问题](#7.1 常见问题)
      • [7.2 有用的调试命令](#7.2 有用的调试命令)
    • [📝 8. 总结](#📝 8. 总结)

本指南将帮助你在macOS上使用Kubespray、Vagrant和Parallels Desktop搭建一个完整的Kubernetes测试集群。

📋 1. 环境准备

1.1 系统要求

  • macOS(Apple Silicon或Intel)
  • 至少16GB内存
  • 50GB以上可用磁盘空间

1.2 软件清单

  • Parallels Desktop(商业版)
  • Homebrew
  • Vagrant + vagrant-parallels插件
  • Python 3.12+ 及虚拟环境
  • Git

🚀 2. 安装步骤

2.1 安装Parallels Desktop

💡 提示: 需要购买商业版许可证,可考虑在闲鱼等平台购买

安装完成后确保Parallels Desktop正常运行。

2.2 配置网络代理(可选)

如果你的网络环境需要代理,创建代理配置脚本:

bash 复制代码
vim ~/.zshrc

添加以下内容:

bash 复制代码
# 网络代理配置
proxy_url="http://172.0.0.1:7890"  # 修改为你的代理地址
export no_proxy="10.0.0.0/8,192.168.16.0/20,localhost,127.0.0.0/8,registry.ocp.local,.svc,.svc.cluster-27,.coding.net,.tencentyun.com,.myqcloud.com"

# 代理控制函数
enable_proxy() {
    export http_proxy="${proxy_url}"
    export https_proxy="${proxy_url}"
    git config --global http.proxy "${proxy_url}"
    git config --global https.proxy "${proxy_url}"
    echo "✅ 代理已启用: ${proxy_url}"
}

disable_proxy() {
    unset http_proxy
    unset https_proxy
    git config --global --unset http.proxy
    git config --global --unset https.proxy
    echo "❌ 代理已禁用"
}

# 默认禁用代理
disable_proxy

应用配置:

bash 复制代码
source ~/.zshrc

# 如需启用代理
enable_proxy

2.3 安装Homebrew

bash 复制代码
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 更新Homebrew
brew update

2,4 准备项目目录

bash 复制代码
# 创建项目目录
mkdir -p ~/Projects/k8s-testing
cd ~/Projects/k8s-testing

# 克隆Kubespray项目
git clone https://github.com/upmio/kubespray-upm.git
cd kubespray-upm

2.5 安装Vagrant及插件

bash 复制代码
# 安装Vagrant
brew tap hashicorp/tap
brew install hashicorp/tap/hashicorp-vagrant

# 验证安装
vagrant --version

# 安装Parallels插件
vagrant plugin install vagrant-parallels

# 查看已安装插件
vagrant plugin list

2.6 配置Python环境

2.6.1 安装Python管理工具
bash 复制代码
brew install  python
2.6.2 配置Shell环境
bash 复制代码
vim ~/.zshrc

添加以下配置:

bash 复制代码
# Python环境配置
alias python=python3
alias pip=pip3

应用配置:

bash 复制代码
source ~/.zshrc
2.6.3 验证Python环境
bash 复制代码
python --version
pip --version

2.6.4 安装 pyenv

安装依赖

bash 复制代码
brew install openssl readline sqlite3 xz zlib

安装pyenv

bash 复制代码
curl https://pyenv.run | bash
bash 复制代码
vim ~/.zshrc

添加以下配置:

bash 复制代码
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

应用配置:

bash 复制代码
source ~/.zshrc

2.6.5 升级Python工具

bash 复制代码
python -m pip install --upgrade pip
pyenv update

2.6.6 创建Python虚拟环境

bash 复制代码
# 安装Python 3.12.11
pyenv install 3.12.11

# 创建专用虚拟环境
pyenv virtualenv 3.12.11 kubespray-3.12.11-env

#为项目设置默认 Python 环境
pyenv local kubespray-3.12.11-env

# 安装项目依赖
pip install -r requirements.txt

2.7 配置Kubespray

2.7.1 配置核心配置文件
bash 复制代码
# 复制Vagrant配置文件
cp vagrant_setup_scripts/Vagrantfile ./Vagrantfile

# 创建vagrant配置目录
mkdir -p vagrant
2.7.1.1 配置集群config.rb
bash 复制代码
$ vim  vagrant/config.rb
# Vagrant configuration file for Kubespray
# Vagrant configuration file for Kubespray
# Kubespray Vagrant Configuration Sample
# This file allows you to customize various settings for your Vagrant environment
# Copy this file to vagrant/config.rb and modify the values according to your needs

# =============================================================================
# PROXY CONFIGURATION
# =============================================================================
# Configure proxy settings for the cluster if you're behind a corporate firewall
# Leave empty or comment out if no proxy is needed

# HTTP proxy URL - used for HTTP traffic
# Example: "http://proxy.company.com:8080"
# $http_proxy = ""
$http_proxy = "http://10.211.55.2:7890"

# HTTPS proxy URL - used for HTTPS traffic
# Example: "https://proxy.company.com:8080"
# $https_proxy = ""
$https_proxy = "http://10.211.55.2:7890"

# No proxy list - comma-separated list of hosts/domains that should bypass proxy
# Common entries: localhost, 127.0.0.1, local domains, cluster subnets
# Example: "localhost,127.0.0.1,.local,.company.com,10.0.0.0/8,192.168.0.0/16"
# $no_proxy = ""
$no_proxy = "localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1,.demo.com"

# Additional no proxy entries - will be added to the default no_proxy list
# Use this to add extra domains without overriding the defaults
# Example: ".internal,.corp,.k8s.local"
# $additional_no_proxy = ""
$additional_no_proxy = "localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1,.demo.com"

# =============================================================================
# ANSIBLE CONFIGURATION
# =============================================================================
# Ansible verbosity level for debugging (uncomment to enable)
# Options: "v" (verbose), "vv" (more verbose), "vvv" (debug), "vvvv" (connection debug)
#$ansible_verbosity = "vvv"

# =============================================================================
# VIRTUAL MACHINE CONFIGURATION
# =============================================================================
# Prefix for VM instance names (will be followed by node number)
$instance_name_prefix = "k8s"

# Default CPU and memory settings for worker nodes
$vm_cpus = 8                    # Number of CPU cores per worker node
$vm_memory = 16384              # Memory in MB per worker node (16GB)

# Master/Control plane node resources
$kube_master_vm_cpus = 4        # CPU cores for Kubernetes master nodes
$kube_master_vm_memory = 4096   # Memory in MB for Kubernetes master nodes (4GB)

# UPM Control plane node resources (if using UPM)
$upm_control_plane_vm_cpus = 12      # CPU cores for UPM control plane
$upm_control_plane_vm_memory = 24576 # Memory in MB for UPM control plane (24GB)

# =============================================================================
# STORAGE CONFIGURATION
# =============================================================================
# Enable additional disks for worker nodes (useful for storage testing)
$kube_node_instances_with_disks = true

# Size of additional disks in GB (200GB in this example)
$kube_node_instances_with_disks_size = "200G"

# Number of additional disks per node
$kube_node_instances_with_disks_number = 1

# Directory to store additional disk files
$kube_node_instances_with_disk_dir = ENV['HOME'] + "/kubespray_vm_disk/upm_disks"

# Suffix for disk file names
$kube_node_instances_with_disk_suffix = "upm"

# VolumeGroup configuration for additional disks
# Name of the VolumeGroup to create for additional disks
$kube_node_instances_volume_group = "local_vg_dev"

# Enable automatic VolumeGroup creation for additional disks
$kube_node_instances_create_vg = true

# =============================================================================
# CLUSTER TOPOLOGY
# =============================================================================
# Total number of nodes in the cluster (masters + workers)
$num_instances = 5

# Number of etcd instances (should be odd number: 1, 3, 5, etc.)
$etcd_instances = 1

# Number of Kubernetes master/control plane instances
$kube_master_instances = 1

# Number of UPM control instances (if using UPM)
$upm_ctl_instances = 1

# =============================================================================
# SYSTEM CONFIGURATION
# =============================================================================
# Vagrant Provider Configuration
# Specify the Vagrant provider to use for virtual machines
# If not set, Vagrant will auto-detect available providers in this order:
# 1. Command line --provider argument (highest priority)
# 2. VAGRANT_DEFAULT_PROVIDER environment variable
# 3. Auto-detection of installed providers (parallels > virtualbox > libvirt)
# 
# Supported options: "virtualbox", "libvirt", "parallels"
# 
# Provider recommendations:
# - virtualbox: Best for development and testing (free, cross-platform)
# - libvirt: Good for Linux production environments (KVM-based)
# - parallels: Good for macOS users with Parallels Desktop
# 
# Leave commented for auto-detection, or uncomment and set to force a specific provider
# $provider = "virtualbox"

# Timezone for all VMs
$time_zone = "Asia/Shanghai"

# Ntp Sever Configuration
$ntp_enabled = "True"
$ntp_manage_config = "True"

# Operating system for VMs
# Supported options: "ubuntu2004", "ubuntu2204", "centos7", "centos8", "rockylinux8", "rockylinux9", etc.
$os = "rockylinux9"

# =============================================================================
# NETWORK CONFIGURATION
# =============================================================================
# Network type: "nat" or "bridge"
#
# nat: Auto-detect provider network and assign IPs (recommended)
#   - Automatically detects provider default network (usually 192.168.x.0/24)
#   - Uses NAT networking for VM internet access
#   - VMs can communicate with each other and host
#   - Simpler setup, no bridge configuration required
#   - Recommended for development and testing
#
# bridge: Use bridge network with manual IP configuration
#   - Requires manual bridge interface setup on host
#   - VMs get IPs from same subnet as host network
#   - Direct network access, VMs appear as separate devices on network
#   - More complex setup, requires bridge configuration
#   - Recommended for production-like environments
$vm_network = "nat"

# Starting IP for the 4th octet (VMs will get IPs starting from this number)
# Used in both nat (with auto-detected subnet) and bridge modes
$subnet_split4 = 100

# The following network settings are only used when $vm_network = "bridge"
# For nat, subnet/gateway/netmask are auto-detected from provider

# Network subnet (first 3 octets) - bridge only
# $subnet = "10.37.129"

# Network configuration - bridge only
# $netmask = "255.255.255.0"      # Subnet mask
# $gateway = "10.37.129.1"        # Default gateway
# $dns_server = "8.8.8.8"         # DNS server
$dns_server = "10.211.55.2"  # (可选)如果配置私有dns,需要在macOS 安装 dns server,否则重启虚拟机,可能会有pod异常。
# Bridge network interface (required when using "bridge")
# Example: On linux, libvirt bridge interface name: br0
# $bridge_nic = "br0"
# Example: On linux, vitrulbox bridge interface name: virbr0
# $bridge_nic = "virbr0"

# =============================================================================
# KUBERNETES CONFIGURATION
# =============================================================================
# Container Network Interface (CNI) plugin
# Options: "calico", "flannel", "weave", "cilium", "kube-ovn", etc.
$network_plugin = "calico"

# Cert-Manager Configuration
$cert_manager_enabled = "True"             # Enable cert-manager

# Local Path Provisioner Configuration
$local_path_provisioner_enabled = "False"    # Enable local path provisioner
$local_path_provisioner_claim_root = "/opt/local-path-provisioner/"  # Local path root

# Ansible inventory directory
$inventory = "inventory/sample"

# Shared folders between host and VMs (empty by default)
$shared_folders = {}

# Kubernetes version to install
$kube_version = "1.33.3"
# Kubespray Vagrant Configuration Sample
2.7.1.2 配置 containerd.yml(可选)
bash 复制代码
$ vim inventory/sample/group_vars/all/containerd.yml
---
# Please see roles/container-engine/containerd/defaults/main.yml for more configuration options

# containerd_storage_dir: "/var/lib/containerd"
# containerd_state_dir: "/run/containerd"
# containerd_oom_score: 0

# containerd_default_runtime: "runc"
# containerd_snapshotter: "native"

# containerd_runc_runtime:
#   name: runc
#   type: "io.containerd.runc.v2"
#   engine: ""
#   root: ""

# containerd_additional_runtimes:
# Example for Kata Containers as additional runtime:
#   - name: kata
#     type: "io.containerd.kata.v2"
#     engine: ""
#     root: ""

# containerd_grpc_max_recv_message_size: 16777216
# containerd_grpc_max_send_message_size: 16777216

# Containerd debug socket location: unix or tcp format
# containerd_debug_address: ""

# Containerd log level
# containerd_debug_level: "info"

# Containerd logs format, supported values: text, json
# containerd_debug_format: ""

# Containerd debug socket UID
# containerd_debug_uid: 0

# Containerd debug socket GID
# containerd_debug_gid: 0

# containerd_metrics_address: ""

# containerd_metrics_grpc_histogram: false

# Registries defined within containerd.
containerd_registries_mirrors:
  - prefix: quay.io
    mirrors:
    - host: https://quay.nju.edu.cn
      capabilities: ["pull", "resolve"]
      skip_verify: false
    - host: http://harbor.demo.com
      capabilities: ["pull", "resolve"]
      skip_verify: true
  - prefix: docker.io
    mirrors:
    - host: http://harbor.demo.com
      capabilities: ["pull", "resolve"]
      skip_verify: true
    - host: https://dockerproxy.com
      capabilities: ["pull", "resolve"]
      skip_verify: false
  - prefix: ghcr.io
    mirrors:
    - host: https://ghcr.nju.edu.cn
      capabilities: ["pull", "resolve"]
      skip_verify: false
    - host: https://ghcr.dockerproxy.com
      capabilities: ["pull", "resolve"]
      skip_verify: false
  - prefix: registry.k8s.io
    mirrors:
    - host: https://k8s.mirror.nju.edu.cn
      capabilities: ["pull", "resolve"]
      skip_verify: false
    - host: https://k8s.dockerproxy.com
      capabilities: ["pull", "resolve"]
      skip_verify: false

# containerd_max_container_log_line_size: -1

🔧 3. 部署集群

3.1 启动虚拟机并部署K8s

⚠️ 注意: 此过程需要10-15分钟,具体时间取决于网络状况和硬件性能

bash 复制代码
vagrant up --no-parallel

3.2 如果部署失败,可以重试

bash 复制代码
vagrant provision --provision-with ansible

🎯 4. 配置kubectl访问

4.1 安装kubectl客户端

bash 复制代码
# 下载kubectl(Apple Silicon版本)
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/arm64/kubectl"

# 设置执行权限并移动到PATH目录
chmod +x kubectl && mv kubectl /usr/local/bin/kubectl

# 验证安装
kubectl version --client

4.2 配置集群访问

bash 复制代码
# 复制kubeconfig文件
mkdir -p ~/.kube
cp inventory/sample/artifacts/admin.conf ~/.kube/config

# 验证集群连接
kubectl get nodes
kubectl get pods --all-namespaces

📦 5. 安装Helm(可选)

bash 复制代码
# 下载安装脚本
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3

# 执行安装
chmod 700 get_helm.sh
./get_helm.sh

# 验证安装
helm version

🧹 6. 清理环境

6.1 销毁虚拟机

bash 复制代码
vagrant destroy -f

6.2 退出Python虚拟环境

bash 复制代码
pyenv deactivate

🛠️ 7. 故障排除

7.1 常见问题

1. Vagrant启动失败

  • 检查Parallels Desktop是否正常运行
  • 确认系统资源充足(内存、磁盘空间)
  • 检查网络连接状态

2. Python依赖安装失败

  • 确认已激活正确的虚拟环境
  • 尝试升级pip:pip install --upgrade pip
  • 检查网络代理设置

3. kubectl无法连接集群

  • 确认kubeconfig文件路径正确
  • 检查虚拟机网络状态:vagrant status
  • 验证SSH连接:vagrant ssh

4. 网络问题

  • 如在国内环境,建议配置代理
  • 可以尝试使用国内镜像源

7.2 有用的调试命令

bash 复制代码
# 检查Vagrant状态
vagrant status

# 查看虚拟机日志
vagrant ssh -c "sudo journalctl -u kubelet"

# 重新加载Vagrant配置
vagrant reload

# 查看集群状态
kubectl cluster-info
kubectl get componentstatuses

📝 8. 总结

通过以上步骤,你应该已经成功搭建了一个基于Kubespray的Kubernetes测试集群。这个环境非常适合:

  • 学习Kubernetes核心概念
  • 测试应用部署
  • 验证集群配置
  • 开发云原生应用

💡 提示: 建议定期备份重要的配置文件和项目代码,避免因误操作导致数据丢失。


相关资源链接:

相关推荐
再看扣你眼3 小时前
Kubernetes 中 ConfigMap 与 Secret 的深度解析
云原生·容器·kubernetes
liux35286 小时前
Helm在Kubernetes中的应用部署指南与案例解析
云原生·容器·kubernetes
LCY13311 小时前
阿里云上进行k8s集群的配置
阿里云·kubernetes·云计算
only_Klein13 小时前
openeuler24.03部署k8s1.32.7高可用集群(三主三从)
linux·kubernetes
0wioiw014 小时前
Apple基础(Xcode①-项目结构解析)
ide·macos·xcode
名字不要太长 像我这样就好16 小时前
【iOS】weak修饰符
macos·ios·objective-c·cocoa·xcode
东风微鸣19 小时前
使用 Loki 配置告警,如何将原始日志内容添加告警到注释中?
docker·云原生·kubernetes·可观察性
探索云原生20 小时前
HAMi vGPU 原理分析 Part3:hami-scheduler 工作流程分析
云原生·容器·kubernetes·vgpu