一定要修改这个文件 开启转发规则,虽然后面的脚本也有一个开启的指令,但是好像没有效果
sudo vi /etc/sysctl.conf
#设置
net.ipv4.ip_forward=1
创建网络转发规则
sudo vi /home/autostart/zerotier-one-route.sh
#!/bin/bash
# Enable IP forwarding
sysctl -w net.ipv4.ip_forward=1
# Get the interface with the default route (assumed to be PHY_IFACE)
PHY_IFACE=$(ip route | grep default | awk '{print $5}')
echo "Physical interface detected: $PHY_IFACE"
# Initialize attempt counter
attempt=0
# Try to find the ZeroTier interface, retry up to 10 times every 5 seconds
while [ $attempt -lt 10 ]; do
ZT_IFACE=$(ip link show | grep -o 'zt[a-zA-Z0-9]*')
if [ ! -z "$ZT_IFACE" ]; then
echo "ZeroTier interface detected: $ZT_IFACE"
break
else
echo "ZeroTier interface not found, retrying in 5 seconds..."
sleep 5
((attempt++))
fi
done
# Check if ZT_IFACE was found
if [ -z "$ZT_IFACE" ]; then
echo "Failed to find ZeroTier interface after 10 attempts."
exit 1
fi
# Set up NAT
iptables -t nat -A POSTROUTING -o $PHY_IFACE -j MASQUERADE
# Set up IP forwarding rules
iptables -A FORWARD -i $PHY_IFACE -o $ZT_IFACE -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $ZT_IFACE -o $PHY_IFACE -j ACCEPT
给执行权限
sudo chmod +x /home/autostart/zerotier-one-route.sh
创建服务文件 用于开机自动运行,由于zerotier是装在docker里的,所以延时2分钟运行,以便docker启动完成
sudo vi /etc/systemd/system/zerotier-nat.service
[Unit]
# 服务描述
Description=Setup IP forwarding and iptables rules for ZeroTier
# 在 zerotier-one.service 启动后才启动本服务
Wants=zerotier-one.service
# 本服务启动顺序在 zerotier-one.service 和网络服务启动之后
After=zerotier-one.service network.target
[Service]
# 服务类型为 oneshot,表示一次性任务
Type=oneshot
# 在执行主命令前等待 180 秒,确保开机 3 分钟后再执行
ExecStartPre=/bin/sleep 180
# 要执行的主要命令,即运行脚本来设置 IP 转发和 iptables 规则
ExecStart=/home/autostart/zerotier-one-route.sh
# 使服务在执行完后保持活动状态
RemainAfterExit=yes
[Install]
# 指定当 multi-user.target 目标运行时启用该服务
WantedBy=multi-user.target
设置开机自运行,并且马上运行一次
systemctl enable --now zerotier-nat
如果发现脚本没有运行就用命令查看原因
sudo systemctl status zerotier-nat.service
另外还有一个 直接通过docker把所有操作一条龙搞定的,不需要单独设置转发,看这里
参考文章
https://halc.top/p/d556ca0e
https://cloud.tencent.com/developer/article/2345480