# 在裸机云中使用 K3S 启动 Kubernetes 集群

在裸机实例上运行容器相比在虚拟机上运行有许多优势，例如通过移除虚拟机层减少软件堆栈，简化网络配置，无需虚拟机桥接或转换。

Kubernetes 是一个开源容器编排平台，而 K3S 则旨在成为轻量级的 Kubernetes，具有更小的占用空间，能够在 Intel x86 和 ARM CPU 上运行。

## K3S 是什么？

K3S 具有以下特点：

* 轻量级 Kubernetes
* 单个二进制文件（约 50MB）
* 低内存/CPU 占用
* CNCF 认证发行版
* 适用于生产环境
* 支持 ARM
* 非常适合边缘计算

Kubernetes 集群包括一个主节点和一个或多个工作节点。它们的功能如下：

* **主节点** – 控制集群、处理 API 调用等。
* **工作节点** – 部署 pod 并运行应用程序。可以根据需求添加或移除工作节点。

要设置一个 K3S 集群，我们需要至少两台主机，一个主节点和一个工作节点。在本示例中，我们将使用来自 Zenlayer 裸机云（BMC）产品的两台主机。

Zenlayer BMC 提供多种服务器类型选择，通常包括 S/M/L 类型及其变体。在本示例中，我们选择了 S 类型，因为 K3S 在 16G 内存配置下也能表现出色。

## 实例配置

在 zenConsole 上 [创建一个裸机实例](/welcome/cn/bare-metal/get-started/create-a-bare-metal-instance.md)，

选择在实例中安装 Ubuntu 20.04，并启用 SSH 密钥访问。

实例将在几分钟内准备好，我们可以使用无密钥 SSH 访问它。

## K3S 安装

访问 [K3S.io](https://k3s.io) 并从 [这里](https://github.com/k3s-io/k3s/releases/download/v1.22.2%2Bk3s1/k3s) 下载二进制文件。使用 '`chmod +x k3s`' 命令使其可执行。

* 在主节点上，运行以下命令：

```
sudo k3s server &
# Kubeconfig 写入 /etc/rancher/k3s/k3s.yaml。
# 通过运行以下命令检查主节点：
sudo k3s kubectl get node
```

我们应该能看到类似以下的输出：

<figure><img src="/files/ETwvHmqwi4u16Cl2RxCa" alt=""><figcaption><p>代码结果</p></figcaption></figure>

从主节点中，在 `/var/lib/rancher/k3s/server/node-token` 找到 `NODE_TOKEN`。

* 在工作节点上，运行以下命令：

```
sudo k3s agent --server https://${Ipaddress_of_master_node}:6443 --token ${NODE_TOKEN}
```

我们将看到来自两个实例的大量日志信息。不久后，我们运行 '`.k3s kubectl get node`' 命令，应该能看到两个节点都已准备好。从此处我们可以运行其他 Kubernetes 命令。

<figure><img src="/files/q7ewd3uxt7v4SQ94ffJq" alt=""><figcaption><p>运行 Kubernetes 命令</p></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.console.zenlayer.com/welcome/cn/bare-metal/best-practice/start-kubernetes-cluster-using-k3s-in-bare-metal-cloud.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
