Ubuntu 上设置 iptables 规则开机自启

在 Ubuntu 上设置 iptables 规则开机自启,可以通过以下方法实现:

方法 1:使用 iptables-persistent(推荐)

Ubuntu 服务器上 iptables 规则不会自动保存,因此需要 iptables-persistent 来持久化规则并在开机时自动加载。

  1. 安装 iptables-persistent
    sudo apt update
    sudo apt install iptables-persistent -y
    安装过程中会要求保存当前的 iptables 规则,选择 Yes。
  2. 保存 iptables 规则
    如果你已经配置了 iptables 规则,可以手动保存:
    sudo netfilter-persistent save
    或者:
    sudo iptables-save > /etc/iptables/rules.v4
    sudo ip6tables-save > /etc/iptables/rules.v6 # 如果使用 IPv6
  3. 重新加载 iptables 规则
    sudo netfilter-persistent reload
  4. 确保 iptables-persistent 在开机时运行
    sudo systemctl enable netfilter-persistent
    sudo systemctl start netfilter-persistent

方法 2:使用 rc.local(适用于较旧版本的 Ubuntu)

如果你不想使用 iptables-persistent,可以在 /etc/rc.local 中添加规则。

  1. 编辑 /etc/rc.local
    sudo nano /etc/rc.local
    在 exit 0 之前添加:
    iptables-restore < /etc/iptables/rules.v4
    如果使用 IPv6:
    ip6tables-restore < /etc/iptables/rules.v6
    然后保存并退出(Ctrl + X,然后按 Y)。
  2. 赋予执行权限
    sudo chmod +x /etc/rc.local
  3. 让 rc.local 生效
    如果 /etc/rc.local 不存在,可以手动创建并启用:
    sudo touch /etc/rc.local
    sudo chmod +x /etc/rc.local
    sudo systemctl enable rc-local
    sudo systemctl start rc-local

方法 3:使用 systemd 自定义服务

你可以创建一个 systemd 服务来在启动时恢复 iptables 规则。

  1. 创建 iptables 服务
    sudo nano /etc/systemd/system/iptables.service
    添加以下内容:

    Unit

    Description=Restore iptables rules
    After=network.target

Service

Type=oneshot

ExecStart=/sbin/iptables-restore < /etc/iptables/rules.v4

ExecStart=/sbin/ip6tables-restore < /etc/iptables/rules.v6

RemainAfterExit=yes

Install

WantedBy=multi-user.target

  1. 重新加载 systemd 并启用服务

sudo systemctl daemon-reload

sudo systemctl enable iptables

sudo systemctl start iptables

验证 iptables 规则是否生效

sudo iptables -L -v -n

如果重启后 iptables 规则仍然存在,则说明设置成功。

如果你是用于生产环境,建议使用 方法 1(iptables-persistent),因为它是 Ubuntu 官方推荐的方法,并且管理方便。

相关推荐
摘星|1 天前
架设一台NFS服务器,并按照以下要求配置
linux·运维·服务器
做运维的阿瑞1 天前
Linux环境变量持久化完全指南
linux·运维·服务器
天才奇男子1 天前
从零开始搭建Linux Web服务器
linux·服务器·前端
DY009J1 天前
如何在Ubuntu虚拟机中设置Samba共享,并在Windows宿主机中挂载为网络驱动器
网络·windows·ubuntu
Mr_Dwj1 天前
【运维】GNU/Linux 入门笔记
linux·运维·gnu
Elias不吃糖1 天前
NebulaChat项目构建笔记
linux·c++·笔记·多线程
Wang's Blog1 天前
MySQL: 服务器性能优化全面指南:参数配置与数据库设计的最佳实践
服务器·数据库·mysql
顾安r1 天前
11.14 脚本网页 迷宫逃离
服务器·javascript·游戏·flask·html
---学无止境---1 天前
Linux内核brk系统调用深度解析:堆内存管理的设计与实现
linux
网络坤子-蔡先生1 天前
openEuler 22.03 ARM64 KVM虚拟化安装
linux·开源·负载均衡