Linux 网卡 Bonding 配置实战:bond0 主备与负载均衡 - 夜莺博客

Linux 网卡 Bonding 配置实战:bond0 主备与负载均衡

服务器双网卡做 Bonding(链路聚合)是 Linux 运维的必修课:一根网线断掉不丢业务、带宽翻倍,还能配合交换机做链路冗余。但很多运维第一次配置 bond 都栽在模式选择上——mode 0 和 mode 4 都叫"负载均衡",行为却完全不同,配错模式轻则带宽不叠加,重则造成广播风暴。本文从 bond 的七种模式讲起,给出 mode 1(主备)和 mode 4(LACP 动态聚合)两套完整配置,并总结最常见的排障命令。

Bond 七种模式速览

模式 名称 特点 交换机要求
mode 0 balance-rr 轮询负载均衡,所有口收发 需要静态链路聚合
mode 1 active-backup 主备冗余,只有一块口工作 无要求
mode 2 balance-xor 按 XOR 哈希分流 需要静态链路聚合
mode 3 broadcast 所有口同时收发(广播) 需要静态链路聚合
mode 4 802.3ad 动态 LACP,按哈希分流 必须支持 LACP
mode 5 balance-tlb 发送负载均衡(自适应) 无要求
mode 6 balance-alb 收发都均衡(自适应) 无要求

实战中最常用的是 mode 1(纯冗余,随便哪台交换机都行)和 mode 4(LACP,带宽叠加,交换机需配置 Eth-Trunk/Bridge-Aggregation)。

配置一:mode 1 主备(最稳妥)

加载 bonding 内核模块并设置参数:

# vim /etc/modprobe.d/bonding.conf
alias bond0 bonding
options bond0 mode=1 miimon=100

配置 bond0 与两块物理网卡(以 RHEL/CentOS 为例):

# /etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
BOOTPROTO=static
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
ONBOOT=yes

# ifcfg-eth0
DEVICE=eth0
MASTER=bond0
SLAVE=yes
ONBOOT=yes

# ifcfg-eth1(内容与 eth0 相同)

重启网络或 systemctl restart network 生效。Ubuntu 用 netplan 配置更简洁:

# /etc/netplan/01-netcfg.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0: {dhcp4: no}
    eth1: {dhcp4: no}
  bonds:
    bond0:
      interfaces: [eth0, eth1]
      addresses: [192.168.1.100/24]
      parameters:
        mode: active-backup
        mii-monitor-interval: 100

配置二:mode 4 LACP 负载均衡

mode 4 需要交换机侧配合(华为:interface Eth-Trunk1 + mode lacp-static;H3C:link-aggregation mode dynamic),服务器侧:

# /etc/modprobe.d/bonding.conf
options bond0 mode=4 miimon=100 lacp_rate=1 xmit_hash_policy=layer3+4

Ubuntu netplan 版本:

  bonds:
    bond0:
      interfaces: [eth0, eth1]
      addresses: [192.168.1.100/24]
      parameters:
        mode: 802.3ad
        lacp-rate: fast
        mii-monitor-interval: 100
        transmit-hash-policy: layer3+4

xmit_hash_policy=layer3+4 按 IP+端口哈希分流,避免单条大流量(如备份)把流量压在一个口上。

验证与排障

cat /proc/net/bonding/bond0
ip link show bond0
ip -s link show bond0
ethtool eth0

关键检查点:

  • cat /proc/net/bonding/bond0MII Status 是否 up、Bonding Mode 是否正确、当前 Currently Active Slave 是哪块。
  • mode 4 下出现大量 multi 或流量不均匀,检查交换机聚合模式是否为动态 LACP、两端 lacp_rate 是否一致。
  • 拔掉主用网卡测试切换:mode 1 应秒级切换到备用口(miimon=100 时约 100ms 检测周期)。

常见坑位

  • 两块网卡 MAC 地址相同导致交换机端口学不到 MAC:bond 默认使用第一块口的 MAC,属正常现象。
  • mode 0/2/3/4 交换机侧必须配聚合,否则可能环路广播风暴。
  • 忘加 miimon:链路断开但口状态仍 up 时不会切换,等于没有冗余。

延伸阅读:Linux 网络故障排查实战Docker 网络模式详解

原文链接:https://www.kernel.org/doc/Documentation/networking/bonding.txt