基于win 10 打造K8S應用開發環境(wsl & kind)
一、wsl子系統安裝
1.1 確認windows系統版本
cmd/powershell
或者win + r 運行winver
操作系統要>= 19044
1.2 開啟wsl功能
控制面板 -> 程序 -> 啟用或關閉Windows功能
開啟適用于Linux的windows子系統
& 虛擬機平臺
確認完成后,電腦會重啟。
1.3 wsl配置
wsl
適用于 Linux 的 Windows 子系統沒有已安裝的分發版。
可以通過訪問 Microsoft Store 來安裝分發版:
https://aka.ms/wslstore#更改新分發的默認安裝版本為2
wsl --set-default-version 2
#WSL 2 內核更新
wsl --update#獲得有效分發列表
wsl --list --online#安裝Ubuntu
wsl --install -d Ubuntu
啟動ubuntu
C:\WINDOWS\system32>wsl
Provisioning the new WSL instance Ubuntu
This might take a while...
Create a default Unix user account: test
New password:
Retype new password:
passwd: password updated successfully
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 5.15.167.4-microsoft-standard-WSL2 x86_64)* Documentation: https://help.ubuntu.com* Management: https://landscape.canonical.com* Support: https://ubuntu.com/proSystem information as of Fri Apr 11 10:27:41 CST 2025System load: 0.57 Processes: 34Usage of /: 0.1% of 1006.85GB Users logged in: 0Memory usage: 3% IPv4 address for eth0: 192.168.137.113Swap usage: 0%This message is shown once a day. To disable it please create the
/home/test/.hushlogin file.
1.4 解決在WSL上虛擬機無法連通外網問題
在 WSL(Windows Subsystem for Linux)上使用 NAT(網絡地址轉換)模式時,虛擬機無法連通外網是一個常見問題
檢查DNS:
DNS 配置問題會導致無法連接外網。可以嘗試以下步驟:
1.備份并刪除自動生成的文件:
sudo cp /etc/wsl.conf /etc/wsl.conf.bk
sudo cp /etc/resolv.conf /etc/resolv.conf.bk
sudo rm /etc/resolv.conf || true
sudo rm /etc/wsl.conf || true
2.重新創建配置文件:
sudo bash -c 'cat <<EOF > /etc/wsl.conf
[network]
generateResolvConf = false
EOF'
3.重新創建 DNS 配置:
sudo bash -c 'cat <<EOF > /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
EOF'
1.5 wsl命令解釋
獲取幫助文檔
wsl --help
版權所有(c) Microsoft Corporation。保留所有權利。用法: wsl.exe [Argument] [Options...] [CommandLine]運行 Linux 二進制文件的參數:如果未提供命令行,wsl.exe 將啟動默認 shell。--exec, -e <CommandLine>在不使用默認 Linux Shell 的情況下執行指定的命令。--按原樣傳遞其余命令行。選項:--cd <Directory>將指定目錄設置為當前工作目錄。如果使用了 ~,則將使用 Linux 用戶的主頁路徑。如果路徑以 / 字符開頭,將被解釋為絕對 Linux 路徑。否則,該值一定是絕對 Windows 路徑。--distribution, -d <Distro>運行指定分發。--user, -u <UserName>以指定用戶身份運行。管理適用于 Linux 的 Windows 子系統的參數:--help顯示用法信息。--install [選項]安裝額外的適用于 Linux 的 Windows 子系統分發。要獲得有效分發列表,請使用“wsl --list --online”。選項:--distribution, -d [參數]按名稱下載并安裝分發。參數:有效分發名稱(不區分大小寫)。示例:wsl --install -d Ubuntuwsl --install --distribution Debian--set-default-version <Version>更改新分發的默認安裝版本。--shutdown立即終止所有運行的分發及 WSL 2輕型實用工具虛擬機。--status顯示適用于 Linux 的 Windows 子系統的狀態。--update [Options]如果未指定任何選項,則將 WSL 2 內核更新為最新版本。選項:--rollback恢復為 WSL 2 內核的先前版本。--inbox僅更新收件箱 WSL 2 內核。不要從 Microsoft Store 下載 WSL。--web-download從 Internet 而不是 Microsoft Store 下載最新版本的 WSL。用于管理適用于 Linux 的 Windows 子系統中的分發的參數:--export <Distro> <FileName>將分發導出到 tar 文件。對于標準輸出,文件名可以是 -。--import <Distro> <InstallLocation> <FileName> [Options]將指定的 tar 文件作為新分發導入。對于標準輸入,文件名可以是 -。選項:--version <Version>指定要用于新分發的版本。--list, -l [Options]列出分發。選項:--all列出所有分發,包括當前正在安裝或卸載的分發。--running僅列出當前正在運行的分發。--quiet, -q僅顯示分發名稱。--verbose, -v顯示所有分發的詳細信息。--online, -o顯示使用“wsl --install”進行安裝的可用分發列表。--set-default, -s <分發>將分發設置為默認值。--set-version <分發> <版本>更改指定分發的版本。--terminate, -t <分發>終止指定的分發。--unregister <分發>注銷分發并刪除根文件系統。
更改新分發的默認安裝版本為2
wsl --set-default-version 2
WSL 2 內核更新
wsl --update
獲得有效分發列表
wsl --list --online
安裝額外的適用于 Linux 的 Windows 子系統分發Ubuntu
wsl --install -d Ubuntu
運行指定分發。
wsl -d Ubuntu
運行默認的分發
wsl
列出分發并顯示版本
wsl -l -v
將Ubuntu分發設置為默認值
wsl --set-default Ubuntu
終止指定的分發。將Runing變成Stopped
wsl --terminate Ubuntu
注銷分發并刪除根文件系統。
wsl --unregister Ubuntu
顯示適用于 Linux 的 Windows 子系統的狀態。
wsl --status
默認分發: Ubuntu
默認版本: 2
以指定用戶身份運行
wsl --user root
root@DESKTOP-KCURLDV:/mnt/c/Users/Administrator#
二、安裝Docker Desktop
2.1 下載docker Desktop
https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe?utm_source=docker&utm_medium=webreferral&utm_campaign=dd-smartbutton&utm_location=module&_gl=1*5ht9ce*_gcl_au*MjQwMDkyNDQ0LjE3NDQxMTQzMzg.*_ga*MTM1ODM2MjU5NS4xNzQ0MTE0MzEx*_ga_XJWPQMJYHQ*MTc0NDExNDMxMS4xLjEuMTc0NDExNjM4OC41MC4wLjA.
2.2 安裝以及設置
一步步安裝就行。
docker配置如下圖所示
三、Golang安裝
功能:可以安裝多個golang版本,可以切換golang版本
root@DESKTOP-KCURLDV:~# bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
Cloning from https://github.com/moovweb/gvm.git to /root/.gvm
No existing Go versions detected
ERROR: Missing requirements.
Installed GVM v1.0.22Please restart your terminal session or to get started right away run`source /root/.gvm/scripts/gvm`# source /root/.gvm/scripts/gvm
ERROR: Missing requirements.
如果不執行source /root/.gvm/scripts/gvm
需要退出Ubuntu終端,再登入即可有gvm命令
# gvm versionCould not find bisonlinux: apt-get install bisonCould not find gcclinux: apt-get install gccCould not find makelinux: apt-get install makeERROR: Missing requirements.# apt-get update
# apt-get install bison gcc make
# gvm version
Go Version Manager v1.0.22 installed at /root/.gvm# gvm
Usage: gvm [command]Description:GVM is the Go Version ManagerCommands:version - print the gvm version numberget - gets the latest code (for debugging)use - select a go version to use (--default to set permanently)diff - view changes to Go roothelp - display this usage textimplode - completely remove gvminstall - install go versionsuninstall - uninstall go versionscross - install go cross compilerslinkthis - link this directory into GOPATHlist - list installed go versionslistall - list available versionsalias - manage go version aliasespkgset - manage go packages setspkgenv - edit the environment for a package setapplymod - apply the go version in go.mod
# gvm listallgvm gos (available)go1go1.0.1go1.0.2go1.0.3go1.1....# gvm install go1.19 -B
Installing go1.19 from binary source
# gvm install go1.20.3 -B
Installing go1.20.3 from binary source# gvm use go1.19
Now using version go1.19# gvm list
gvm gos (installed)=> go1.19go1.20.3
# gvm use go1.20.3
# gvm listgvm gos (installed)go1.19
=> go1.20.3
四、kubectl安裝
啟動Docker 并指定wsl為Ubuntu后,會在Ubuntu安裝docker和kubectl命令。
如果沒有kubectl命令可以手動安裝
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
sudo mv kubectl /usr/local/bin
Kind 只負責創建集群(會配置好 kubeconfig)
五、Golang安裝下載
5.1 下載安裝地址(傻瓜式)
https://www.jetbrains.com/go/download/#section=windows
5.2 創建Project
location: \\wsl$\Ubuntu\root\aiops
GOROOT: \\wsl$\Ubuntu\root\.gvm\gos\go1.19
5.3 無法訪問\wsl$\Ubuntu\root\解決
原因分析:
因此,我查找了WSL官方文檔(WSL 的文件權限 | Microsoft Learn),發現其給出如下解釋
即Windows訪問Linux的文件的權限是由WSL分發版(如Ubuntu)的默認用戶決定的,安裝WSL分發版時會創建一個用戶,一般會使用該用戶登錄,因此我們需要修改默認用戶。
解決方案:
C:\Users\Administrator>ubuntu config --default-user rootC:\Users\Administrator>wsl -l -vNAME STATE VERSION
* Ubuntu Running 2docker-desktop Running 2C:\Users\Administrator>wsl
test@DESKTOP-KCURLDV:/mnt/c/Users/Administrator$ cat /etc/wsl.conf
[boot]
systemd=true[user]
default=test
test@DESKTOP-KCURLDV:/mnt/c/Users/Administrator$ vi /etc/wsl.conf
test@DESKTOP-KCURLDV:/mnt/c/Users/Administrator$ sudo vi /etc/wsl.conf
[boot]
systemd=true[user]
#default=test
test@DESKTOP-KCURLDV:/mnt/c/Users/Administrator$
在終端使用如下命令將默認用戶變更為root(注意:ubuntu處需要根據你安裝的Linux版本改變,可用如下命令查看你的Linux發行版名稱),然后使用wsl命令打開Linux終端,正常來說就會以root用戶登錄,同時也可以直接在Windows的資源管理器中以root身份訪問Linux文件。
擁有root權限可能會對虛擬機的安全造成威脅,例如從Windows入侵Linux文件系統。因此建議在執行完相關文件上傳任務后,將默認用戶改為普通用戶(也可以改變需要訪問的文件或文件夾的權限,例如sudo chmod 777 XXX,但會相對麻煩)。
C:\Users\Administrator>wsl -l -vNAME STATE VERSION
* Ubuntu Running 2docker-desktop Running 2如果執行以上命令后仍未變更默認用戶,則可能是在Linux中使用了配置文件,使用如下命令查看并注釋掉相關配置即可。(有時可能需要重啟wsl)
```bash
C:\Users\Administrator>wsl --terminate Ubuntu
操作成功完成。C:\Users\Administrator>wsl
root@DESKTOP-KCURLDV:/mnt/c/Users/Administrator#
5.4 編寫test.go并運行
package mainimport "fmt"func main() {fmt.Println("Hello World")
}
如果出現報錯
package test is not in GOROOT
解決:GO111MODULE修改為on
命令為go env -w GO111MODULE=on
root@DESKTOP-KCURLDV:~/aiops# go env
GO111MODULE="on" # 修改為on
GOARCH="amd64"
GOBIN=""
GOCACHE="/root/.cache/go-build"
GOENV="/root/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/root/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/root/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/root/.gvm/gos/go1.19"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/root/.gvm/gos/go1.19/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.19"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/root/aiops/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build3377041513=/tmp/go-build -gno-record-gcc-switches"
六、kind安裝
Kind是Kubernetes In Docker的縮寫,顧名思義,看起來是把k8s放到docker的意思。
kind創建k8s集群的基本原理就是:提前準備好k8s節點的鏡像,通過docker啟動容器,來模擬k8s的節點,從而組成完整的k8s集群。
需要注意,kind創建的集群僅可用于開發、學習、測試等
不能用于生產環境。
創建、啟動k8s集群非常快速,資源消耗較低。
支持創建多節點的k8s集群,包括高可用模式。
kind 支持Linux,macos and windows
它是CNCF認證的k8s集群安裝方式之一。
安裝kind:
#通過設置 gvm use 命令的 --default 參數來指定默認的 Go 版本,這樣每次新建終端時就不需要手動指定了
# gvm use go1.19 --default
Now using version go1.19# go install sigs.k8s.io/kind@latest
go: downloading sigs.k8s.io/kind v0.27.0
go: downloading github.com/spf13/pflag v1.0.5
go: downloading github.com/spf13/cobra v1.8.0
go: downloading al.essio.dev/pkg/shellescape v1.5.1
go: downloading github.com/pkg/errors v0.9.1
go: downloading gopkg.in/yaml.v3 v3.0.1
go: downloading github.com/pelletier/go-toml v1.9.5
go: downloading github.com/mattn/go-isatty v0.0.20
go: downloading sigs.k8s.io/yaml v1.4.0
go: downloading github.com/BurntSushi/toml v1.4.0
go: downloading github.com/evanphx/json-patch/v5 v5.6.0
go: downloading github.com/google/safetext v0.0.0-20220905092116-b49f7bc46da2
go: downloading golang.org/x/sys v0.6.0
# kind version
kind v0.27.0 go1.19 linux/amd64# kind -h
kind creates and manages local Kubernetes clusters using Docker container 'nodes'Usage:kind [command]Available Commands:build Build one of [node-image]completion Output shell completion code for the specified shell (bash, zsh or fish)create Creates one of [cluster]delete Deletes one of [cluster]export Exports one of [kubeconfig, logs]get Gets one of [clusters, nodes, kubeconfig]help Help about any commandload Loads images into nodesversion Prints the kind CLI versionFlags:-h, --help help for kind-q, --quiet silence all stderr output-v, --verbosity int32 info log verbosity, higher value produces more output--version version for kindUse "kind [command] --help" for more information about a command.
注意docker版本和kind版本的兼容問題,如果部署失敗可能是k8s版本過低
七、使用kind實現單節點k8s集群部署
kind部署的k8s與docker中的k8s無關.
# kind create cluster --name k8s-1 --image kindest/node:v1.25.16Creating cluster "k8s-1" ...? Ensuring node image (kindest/node:v1.25.16) 🖼? Preparing nodes 📦? Writing configuration 📜? Starting control-plane 🕹?? Installing CNI 🔌? Installing StorageClass 💾
Set kubectl context to "k8s-1-kind"
You can now use your cluster with:kubectl cluster-info --context kind-kindNot sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/# kubectl cluster-info --context kind-kind
Kubernetes control plane is running at https://127.0.0.1:38317
CoreDNS is running at https://127.0.0.1:38317/api/v1/namespaces/kube-system/services/kube-dns:dns/proxyTo further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.# kind get clusters
kind# kubectl get node
NAME STATUS ROLES AGE VERSION
kind-control-plane Ready control-plane 5m37s v1.25.16# kubectl get po -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-565d847f94-6kvst 1/1 Running 0 6m
coredns-565d847f94-d7nt8 1/1 Running 0 6m
etcd-kind-control-plane 1/1 Running 0 6m12s
kindnet-cxk26 1/1 Running 0 6m
kube-apiserver-kind-control-plane 1/1 Running 0 6m15s
kube-controller-manager-kind-control-plane 1/1 Running 1 (5m16s ago) 6m15s
kube-proxy-h8g6p 1/1 Running 0 6m
kube-scheduler-kind-control-plane 1/1 Running 1 (5m18s ago) 6m12s# kind delete clusters kind
Deleted nodes: ["kind-control-plane"]
Deleted clusters: ["kind"]
八、使用kind實現多節點k8s集群部署
# cat <<EOF > kind.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
EOF# kind create cluster --image kindest/node:v1.25.16 --name kind --config kind.yaml
Creating cluster "kind" ...? Ensuring node image (kindest/node:v1.25.16) 🖼? Preparing nodes 📦 📦 📦? Writing configuration 📜? Starting control-plane 🕹?? Installing CNI 🔌? Installing StorageClass 💾? Joining worker nodes 🚜
Set kubectl context to "kind-kind"
You can now use your cluster with:kubectl cluster-info --context kind-kindNot sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/# kubectl get node
NAME STATUS ROLES AGE VERSION
kind-control-plane Ready control-plane 2m1s v1.25.16
kind-worker Ready <none> 86s v1.25.16
kind-worker2 Ready <none> 85s v1.25.16# cat <<EOF > kind1.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
networking:disableDefaultCNI: truekubeProxyMode: "ipvs"
EOF# kind create cluster --image kindest/node:v1.25.16 --name kind1 --config kind1.yaml
Creating cluster "kind1" ...? Ensuring node image (kindest/node:v1.25.16) 🖼? Preparing nodes 📦 📦 📦? Writing configuration 📜? Starting control-plane 🕹?? Installing StorageClass 💾? Joining worker nodes 🚜
Set kubectl context to "kind-kind1"
You can now use your cluster with:kubectl cluster-info --context kind-kind1Not sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/#kubectl config current-context
kind-kind1
#kubectl config use-context kind-kind# kind delete clusters kind1
Deleted nodes: ["kind1-control-plane" "kind1-worker2" "kind1-worker"]
Deleted clusters: ["kind1"]# kind delete clusters kind
Deleted nodes: ["kind-control-plane" "kind-worker2" "kind-worker"]
Deleted clusters: ["kind"]
也可以創建多套K8S集群
使用–name 指定集群名稱
使用kubectl config use-context 集群上下文名稱即可切換集群。
# cat <<EOF > kind2.yaml
# a cluster with 3 control-plane nodes and 3 workers
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: control-plane
- role: control-plane
- role: worker
- role: worker
- role: worker
EOF#kind create cluster --image kindest/node:v1.25.16 --name kind2 --config kind2.yaml
Creating cluster "kind2" ...? Ensuring node image (kindest/node:v1.25.16) 🖼? Preparing nodes 📦 📦 📦 📦 📦 📦? Configuring the external load balancer ??? Writing configuration 📜? Starting control-plane 🕹?? Installing CNI 🔌? Installing StorageClass 💾? Joining more control-plane nodes 🎮? Joining worker nodes 🚜
Set kubectl context to "kind-kind2"
You can now use your cluster with:#kubectl cluster-info --context kind-kind2Not sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/
root@DESKTOP-KCURLDV:~# kubectl cluster-info --context kind-kind2Kubernetes control plane is running at https://127.0.0.1:41983
CoreDNS is running at https://127.0.0.1:41983/api/v1/namespaces/kube-system/services/kube-dns:dns/proxyTo further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.# kubectl get nodes
NAME STATUS ROLES AGE VERSION
kind2-control-plane Ready control-plane 4m27s v1.25.16
kind2-control-plane2 Ready control-plane 3m53s v1.25.16
kind2-control-plane3 Ready control-plane 2m17s v1.25.16
kind2-worker Ready <none> 83s v1.25.16
kind2-worker2 Ready <none> 83s v1.25.16
kind2-worker3 Ready <none> 83s v1.25.16
九、通過goland開發 部署描述文件,并部署到k8s集群
編寫yaml
apiVersion: apps/v1
kind: Deployment
metadata:name: nginx
spec:selector:matchLabels:app: nginxtemplate:metadata:labels:app: nginxspec:containers:- name: nginximage: nginx:latestimagePullPolicy: IfNotPresentrestartPolicy: Always
# kubectl apply -f aiops/nginx.yaml
deployment.apps/nginx configured
# kubectl get po
NAME READY STATUS RESTARTS AGE
nginx-d5f959df4-kcqq4 1/1 Running 0 4m12s