温馨提示×

Linux如何配置网络

小樊
44
2026-07-28 15:42:45
栏目: 智能运维

在 Linux 系统中,配置网络的方法取决于发行版网络管理方式(NetworkManager 或 systemd-networkd)以及你使用的是命令行还是图形界面。下面我按常见场景给你一个从基础到进阶的说明。


一、查看当前网络状态

1. 查看网卡信息

ip addr

或(较老系统)

ifconfig

2. 查看路由

ip route

3. 查看 DNS

cat /etc/resolv.conf

二、临时配置(重启失效)

1. 配置 IP 地址

sudo ip addr add 192.168.1.100/24 dev eth0

2. 启动网卡

sudo ip link set eth0 up

3. 配置默认网关

sudo ip route add default via 192.168.1.1

4. 配置 DNS

echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf

✅ 适合临时测试
❌ 重启后失效


三、永久配置(常见发行版)


四、Ubuntu / Debian(传统方式)

文件:/etc/network/interfaces

sudo nano /etc/network/interfaces

静态 IP 示例

auto eth0
iface eth0 inet static
    address 192.168.1.100
    netmask 255.255.255.0
    gateway 192.168.1.1
    dns-nameservers 8.8.8.8

重启网络

sudo systemctl restart networking

五、Ubuntu 18.04+(Netplan,推荐 ✅)

配置文件路径

/etc/netplan/*.yaml

静态 IP 示例

network:
  version: 2
  ethernets:
    eth0:
      dhcp4: no
      addresses:
        - 192.168.1.100/24
      gateway4: 192.168.1.1
      nameservers:
        addresses:
          - 8.8.8.8

应用配置

sudo netplan apply

✅ 新系统推荐
✅ 云服务器常用


六、CentOS / Rocky / AlmaLinux

1. 配置文件

/etc/sysconfig/network-scripts/ifcfg-eth0

2. 静态 IP 示例

BOOTPROTO=static
ONBOOT=yes
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8

3. 重启网络

sudo systemctl restart NetworkManager

七、使用 NetworkManager(通用方式 ✅)

1. 查看连接

nmcli connection show

2. 设置静态 IP

nmcli connection modify eth0 ipv4.method manual \
ipv4.addresses 192.168.1.100/24 \
ipv4.gateway 192.168.1.1 \
ipv4.dns 8.8.8.8

3. 重新激活

nmcli connection down eth0 && nmcli connection up eth0

✅ 桌面 / 服务器都适用
✅ 最通用


八、使用 systemd-networkd(服务器/容器)

1. 配置文件

/etc/systemd/network/20-wired.network
[Match]
Name=eth0

[Network]
Address=192.168.1.100/24
Gateway=192.168.1.1
DNS=8.8.8.8

2. 启用服务

sudo systemctl enable systemd-networkd
sudo systemctl restart systemd-networkd

✅ 容器 / 轻量系统
❌ 不熟悉 systemd 的人略复杂


九、常见故障排查

ping 8.8.8.8        # 看网络通不通
ping www.baidu.com  # 看 DNS 是否可用
ip route            # 检查网关
journalctl -xe      # 查看错误日志

十、快速选择指南

场景 推荐方式
Ubuntu 20.04+ Netplan
CentOS 7/8 NetworkManager
临时测试 ip 命令
容器 / CoreOS systemd-networkd

如果你愿意,可以告诉我:

  • ✅ Linux 发行版和版本
  • ✅ 是服务器还是桌面
  • ✅ 静态 IP 还是 DHCP

我可以直接给你一份可用配置文件

0