以前在 Ubuntu 设定固定 IP 是修改档案 /etc/network/interfaces, 但从 Ubuntu 17.10 开始在 CLI 要修改网络设定, 便要使用 NetPlan, NetPlan 会读取所有在 /etc/netplan/ 下的 *.yaml 设定档.
以下是在 Ubuntu 18.04 设定固定 IP 的方法, 并假设要设定的网卡名称是 enp0s3.
NetPlan 默认的设定档在 /etc/netplan/ 目录下的 01-netcfg.yaml 或 50-cloud-init.yaml, 默认会自动侦测 DHCP 取得 IP, 内容类似以下:
/ubuntu/netplan
$ sudo vi /etc/netplan/50-cloud-init.yaml
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
ethernets:
enp0s3:
addresses: []
dhcp4: true
version: 2
1
2
3
4
5
6
7
8
9
10
11
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
ethernets:
enp0s3:
addresses:[]
dhcp4:true
version:2
例如我想使用以下的网络设定:
IP: 192.168.0.10
Getway: 192.168.0.1
DNS: 8.8.8.8 及 8.8.4.4
将 /etc/netplan/50-cloud-init.yaml 改成这样:
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
ethernets:
enp0s3:
addresses: [192.168.0.10/24]
gateway4: 192.168.0.1
nameservers:
addresses: [8.8.8.8,8.8.4.4]
dhcp4: no
version: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
ethernets:
enp0s3:
addresses:[192.168.0.10/24]
gateway4:192.168.0.1
nameservers:
addresses:[8.8.8.8,8.8.4.4]
dhcp4:no
version:2
储存盘案后, 可以先检查设定是否正确:
/ubuntu/netplan
$ sudo netplan try
如果设定正确的话便会使用新网络设定, 并会在 120 秒后自动还原成原本的设定。这个措施是为了防止设定网络出错, 不能登入远端主机.
一切没有问题后, 执行以下指令使用新的网络设定:
/ubuntu/netplan
$ sudo netplan apply
你可能感兴趣的内容: