CentOS 7 配置静态 IP

本文记录 CentOS 7 如何配置静态 IP。

切换到 /etc/sysconfig/network-scripts 目录下,查看该目录下的文件,以太网卡配置文件一般是以 ifcfg-网卡名称 命名的文件,比如 ifcfg-eth0ifcfg-ens3

该文件默认内容如下:

TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=eth0
UUID=cbff035e-b3d4-4c4c-80ee-36a2873e9536
DEVICE=eth0
ONBOOT=no

修改该文件内容如下:

TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
- BOOTPROTO=dhcp
+ BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=eth0
UUID=cbff035e-b3d4-4c4c-80ee-36a2873e9536
DEVICE=eth0
- ONBOOT=no
+ ONBOOT=yes
+ IPADDR=133.133.135.33
+ NETMASK=255.255.0.0
+ GATEWAY=133.133.133.40
+ DNS1=133.133.133.110
+ DNS2=8.8.8.8

然后重启网卡:

systemctl restart network

注意: 配置文件的名称和配置文件内的 NAMEDEVICE 字段保持一致,否则重启网卡可能失败,可以用 ip a 命令查看网卡名称:

$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
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 90:b1:1c:8c:c8:80 brd ff:ff:ff:ff:ff:ff
inet 133.133.133.114/16 brd 133.133.255.255 scope global noprefixroute eno1
valid_lft forever preferred_lft forever
inet6 fe80::ecf9:1f4e:3b04:2763/64 scope link noprefixroute
valid_lft forever preferred_lft forever