如何使用 systemd-networkd 變更預設閘道的順序

如何使用 systemd-networkd 變更預設閘道的順序

我有一個配置有兩個網路介面的 lxd 容器(使用 systemd-networkd)。

第一個有靜態 IP 位址:

testuser@lxd-7e5cbece-180b-427f-a8b1-b2c12f6e9d79:~$ cat /etc/systemd/network/20-net0.network 
[Match]
Name=net0

[Network]
Address=162.132.242.249/26
Gateway=162.132.192.252
DNS=162.132.192.252
DNS=162.132.170.6

lxd 的預設介面(使用 DHCP):

testuser@lxd-7e5cbece-180b-427f-a8b1-b2c12f6e9d79:~$ cat /etc/systemd/network/eth0.network 
[Match]
Name=eth0

[Network]
DHCP=ipv4

[DHCP]
SendHostname=True

現在的問題是,路由表是使用162.132.192.252(來自 net0)作為預設網關產生的,但我希望來自 eth0 的網關成為預設網關。

testuser@lxd-7e5cbece-180b-427f-a8b1-b2c12f6e9d79:~$ sudo route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         162.132.242.252 0.0.0.0         UG    0      0        0 net0
0.0.0.0         10.245.111.1    0.0.0.0         UG    1024   0        0 eth0
10.245.111.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
10.245.111.1    0.0.0.0         255.255.255.255 UH    1024   0        0 eth0
162.132.242.192 0.0.0.0         255.255.255.192 U     0      0        0 net0

1)為什麼路由表是照這個順序產生的? (首先是net0,然後是eth0)

2) 是否可以更改預設網關的順序?

答案1

對於遇到相同問題的任何人,您實際上可以使用指標來做到這一點。您可以將具有較低度量的預設路由新增至靜態接口,而不是在 [Network] 部分中定義預設網關:

[Match]
Name=net0

[Network]
Address=162.132.242.249/26
DNS=162.132.192.252
DNS=162.132.170.6

[Route]
Gateway=162.132.192.252
Destination=0.0.0.0/0
Metric=1024

此後,您可以對 DHCP 介面執行相同的操作(請注意,您不必定義網關,因為這將由 DHCP 伺服器提供):

[Match]
Name=eth0

[Network]
DHCP=ipv4

[DHCP]
SendHostname=True
UseDomains=True

[Route]
Destination=0.0.0.0/0
Metric=1000

現在您獲得了所需的路由表,其中 eth0 介面作為預設閘道:

> ip route list
default dev eth0 proto static metric 1000 
default dev net0 proto static metric 1024 
default via 10.245.111.1 dev eth0 proto dhcp src 10.245.111.96 metric 1024 
10.245.111.0/24 dev eth0 proto kernel scope link src 10.245.111.96 
10.245.111.1 dev eth0 proto dhcp scope link src 10.245.111.96 metric 1024 
162.132.242.192/26 dev net0 proto kernel scope link src 162.132.242.249 

答案2

這其實不是一個程式設計問題。您最好在 StackExchange Unix & Linux 上詢問此類問題。

我遇到過類似的情況:使用 DHCP 的多個介面導致多個預設路由。

我所做的,也許對你也有用,就是告訴介面我們不需要 DHCP 路由,我們不需要它們。在.network介面的檔案中,新增 DHCPUseRoutes=false選項,如下例所示:

[Match]
Name=eno3

[Network]
DHCP=ipv4

[DHCP]
UseRoutes=false

相關內容