以前在 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, 內容類似以下:
- $ sudo vi /etc/netplan/50-cloud-init.yaml
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 改成這樣:
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 |
儲存檔案後, 可以先檢查設定是否正確:
- $ sudo netplan try
如果設定正確的話便會使用新網路設定, 並會在 120 秒後自動還原成原本的設定。這個措施是為了防止設定網路出錯, 不能登入遠端主機.
一切沒有問題後, 執行以下指令使用新的網路設定:
- $ sudo netplan apply