Ubuntu 禁用IPv6的方法

IPv6 是为了解决 IPv4 地址耗尽的问题,但我们的服务器一般用不到它,反而禁用 IPv6 不仅仅会加快网络,还会有助于减少管理开销和提高安全级别。
以下几步在 Ubuntu 禁用 IPv6 (需要 root 权限)

Ubuntu 禁止加载 IPv6 模块

检查是否启用了 IPv6

如果启用了 IPv6,会看到 inet6 xxx 内容,如下所示:

[[email protected]:~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: ens3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 56:00:02:8f:cf:64 brd ff:ff:ff:ff:ff:ff
    inet 45.63.11.216/23 brd 45.63.11.255 scope global dynamic ens3
       valid_lft 86270sec preferred_lft 86270sec
    inet6 fe80::5400:2ff:fe8f:cf64/64 scope link 
       valid_lft forever preferred_lft forever

修改 /etc/sysctl.conf 文件

添加以下内容

net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
net.ipv6.conf.lo.disable_ipv6=1

执行 sysctl -p 使设置生效

[[email protected]:modprobe.d]# sysctl -p
net.ipv6.conf.all.accept_ra = 2
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

创建 /etc/rc.local 文件

上一步已经禁用了 IPv6,但是重启后会复原。要想重启后也禁用,则必须做这一步。

[[email protected]:~]# vim /etc/rc.local

填入内容

#!/bin/bash

# /etc/rc.local

/etc/sysctl.d

/etc/init.d/procps restart

exit 0

授权文件可执行

[[email protected]:~]# chmod 755 /etc/rc.local 

验证是否生效

重启后执行 ip a 验证

[[email protected]:~]# reboot
...
[[email protected]:~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: ens3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 56:00:02:8f:cf:64 brd ff:ff:ff:ff:ff:ff
    inet 45.63.11.216/23 brd 45.63.11.255 scope global dynamic ens3
       valid_lft 86332sec preferred_lft 86332sec
Responses