Linux 設定靜態 IP 的方式隨發行版與網路管理工具演進而不同。本文涵蓋傳統 ifcfg、NetworkManager nmcli、Ubuntu netplan、systemd-networkd 四大主流方案,並說明驗證與除錯步驟。
DEVICE=eth0
BOOTPROTO=static
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=114.114.114.114
DNS2=8.8.8.8
ONBOOT=yes
TYPE=Ethernet
# NM_CONTROLLED=no # 確保不被 NetworkManager 管理
# IPV6INIT=no
systemctl restart network
# 或
/etc/init.d/network restart
# 查看連線
nmcli con show
# 修改現有連線
nmcli con mod "Wired connection 1" ipv4.method manual \
ipv4.addresses 192.168.1.100/24 \
ipv4.gateway 192.168.1.1 \
ipv4.dns "114.114.114.114 8.8.8.8" \
ipv4.dns-search "example.com" \
connection.autoconnect yes
# 重新載入
nmcli con up "Wired connection 1"
nmcli con add type ethernet con-name eth0-static ifname eth0 \
ipv4.method manual \
ipv4.addresses 192.168.1.100/24 \
ipv4.gateway 192.168.1.1 \
ipv4.dns "114.114.114.114 8.8.8.8"
nmcli con up eth0-static
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: false
addresses:
- 192.168.1.100/24
routes:
- to: default
via: 192.168.1.1
nameservers:
addresses: [114.114.114.114, 8.8.8.8]
search: [example.com]
# 可選:關閉 IPv6
# dhcp6: false
# accept-ra: false
⚠️ YAML 縮排嚴格要求 2 空格,不可用 Tab!
netplan generate # 驗證語法生成後端配置
netplan apply # 應用配置
netplan try # 試用 120 秒,自動回滾(推薦生產環境)
[Match]
Name=eth0
[Network]
Address=192.168.1.100/24
Gateway=192.168.1.1
DNS=114.114.114.114
DNS=8.8.8.8
Domains=example.com
# IPv6 停用
# LinkLocalAddressing=no
# IPv6AcceptRA=no
systemctl enable --now systemd-networkd
systemctl enable --now systemd-resolved # DNS 解析
# 連結 resolv.conf
ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
# 檢查 IP
ip -br a
ip addr show eth0
# 檢查路由
ip route
# default via 192.168.1.1 dev eth0
# 檢查 DNS
cat /etc/resolv.conf
resolvectl status
# 連通性測試
ping -c 3 192.168.1.1
ping -c 3 8.8.8.8
dig @114.114.114.114 example.com
# 網路服務狀態
systemctl status NetworkManager
systemctl status systemd-networkd
systemctl status networking # Debian/Ubuntu 傳統
nmcli con mod eth0-static +ipv4.addresses 192.168.1.101/24
nmcli con up eth0-static
addresses:
- 192.168.1.100/24
- 192.168.1.101/24
- 10.0.0.5/24
[Network]
Address=192.168.1.100/24
Address=192.168.1.101/24
Gateway=192.168.1.1
| 現象 | 原因與解決 |
|---|---|
| 設定後不生效 | NetworkManager 與 network 服務衝突,停用其一;Netplan 語法錯誤;systemd-networkd 未啟用 |
| IP 衝突 | DHCP 伺服器同網段分配相同 IP,設定靜態 IP 排除 DHCP 池範圍 |
| 無法上網 | Gateway 錯誤、DNS 不通、防火牆攔截、缺少預設路由 |
| Netplan apply 失敗 | YAML 縮排錯誤、renderer 不匹配(networkd vs NetworkManager) |
| 容器內無法設定 | 需 --cap-add=NET_ADMIN --network=host 或宿主機配置 macvlan/ipvlan |