如何安装k3s

在 K3s 中,节点分为 server 节点(替代传统 Kubernetes 的 master 节点)和 agent 节点(替代 worker 节点)。以下是在 Linux 环境下部署 K3s 集群的详细步骤:

一、环境准备

  1. 系统要求
    • 操作系统:Ubuntu 18.04+/CentOS 7+/RHEL 7+
    • 内存:server 节点至少 2GB,agent 节点至少 1GB
    • 网络:节点间网络互通(防火墙开放相关端口)
  2. 网络要求
    • Server 节点端口:
      • 6443(Kubernetes API 服务器)
      • 8472(VXLAN 流量,用于 Flannel 网络)
      • 9345(用于集群内部通信)
    • Agent 节点端口:
      • 10250(Kubelet API)

二、部署 Server 节点(主节点)

  1. 安装 K3s
    bash
     
     
    curl -sfL https://get.k3s.io | sh -
    
     

    • 如需自定义配置(如禁用 Traefik、修改数据存储),可使用环境变量:
      bash
       
       
      curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--disable traefik --datastore-endpoint='mysql://user:pass@tcp(mysql-server:3306)/k3s'" sh -
      
       
  2. 验证安装
    bash
     
     
    # 检查服务状态
    sudo systemctl status k3s
    
    # 获取节点信息
    sudo k3s kubectl get nodes
    
     
  3. 获取 Token(用于加入 Agent 节点)
    bash
     
     
    sudo cat /var/lib/rancher/k3s/server/node-token
    
     

三、部署 Agent 节点(工作节点)

  1. 在 Agent 节点上执行
    bash
     
     
    curl -sfL https://get.k3s.io | K3S_URL="https://<SERVER_IP>:6443" K3S_TOKEN="<NODE_TOKEN>" sh -
    
     

    • 替换:
      • <SERVER_IP>:Server 节点的 IP 地址
      • <NODE_TOKEN>:从 Server 节点获取的 token
  2. 验证 Agent 节点加入
    在 Server 节点上执行:
    bash
     
     
    sudo k3s kubectl get nodes
    
     

    应看到所有节点状态为 Ready

四、多 Server 节点高可用(HA)配置

如需高可用性,可部署多个 Server 节点:

  1. 准备外部数据库(如 MySQL、PostgreSQL)。
  2. 在首个 Server 节点上执行
    bash
     
     
    curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="server --datastore-endpoint='mysql://user:pass@tcp(mysql-server:3306)/k3s'" sh -
    
     
  3. 在其他 Server 节点上执行
    bash
     
     
    curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="server --datastore-endpoint='mysql://user:pass@tcp(mysql-server:3306)/k3s' --token=<SHARED_TOKEN>" sh -
    
     

    • <SHARED_TOKEN>:首个 Server 节点的 token。
  4. 配置负载均衡器
    将客户端请求(如 kubectl)指向负载均衡器,而非单个 Server 节点。

五、常见操作

  1. 获取 Kubeconfig 文件
    bash
     
     
    sudo cat /etc/rancher/k3s/k3s.yaml
    
     

    将此文件复制到本地 ~/.kube/config 以远程管理集群。
  2. 卸载 K3s
    • Server 节点:
      bash
       
       
      sudo /usr/local/bin/k3s-uninstall.sh
      
       
    • Agent 节点:
      bash
       
       
      sudo /usr/local/bin/k3s-agent-uninstall.sh
      
       

六、故障排查

  • 查看 K3s 服务日志:
    bash
     
     
    sudo journalctl -u k3s -f  # Server 节点
    sudo journalctl -u k3s-agent -f  # Agent 节点
    
     
     
     
     
     
     
     
     
     
     
  • 检查节点状态:
    bash
     
     
    sudo k3s kubectl get nodes -o wide
    
     
     
     
     
     
     
     
     
     

总结

通过以上步骤,你可以快速部署 K3s 单节点或多节点集群。K3s 的轻量级特性使其非常适合边缘计算和资源有限的环境。如需更详细的配置(如网络插件、存储插件),可参考 K3s 官方文档
posted @ 2025-05-26 15:39  呆瓜小贼66  阅读(380)  评论(4)    收藏  举报