查看当前IP地址
在命令行中输入:
可以查看当前的ip地址。
ip地址文件位置
默认情况下ubuntu22.04 server的net配置文件在它的/etc/netplan下
我们可以看到里面有个文件50-cloud-init.yaml
(前面的序号可能不同)
如果你的ip地址是通过DHCP自动获取的,那么它的内容应该如下:
1
2
3
4
5
6
7
8
9
10
|
# This file is generated from information provided by the datasource. Changes
# to it will not persist across an instance reboot. 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:
ens18:
dhcp4: true
version: 2
|
如果你想使用静态ip地址,请先备份原先的文件,然后修改本文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# This file is generated from information provided by the datasource. Changes
# to it will not persist across an instance reboot. 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:
version: 2
renderer: networkd
ethernets:
ens18:
dhcp4: false
dhcp6: false
addresses:
- 192.168.101.11/24 # 修改为你的静态ip地址
routes:
- to: default
via: 192.168.101.1 # 配置网关
nameservers:
addresses: [192.168.101.1] # 配置DNS
|
文件生效
当我们将前面的文件修改完成之后,我们要让它生效:
这时候再查看ip地址ip addr
,我们发现它的ip改变了
但是还有个问题,当我们重启server之后,IP地址又会变回去,这因为是cloud-init
重新配置了网络,覆盖了手动设置的静态 IP。cloud-init 是云环境下用于初始化虚拟机的工具,默认情况下它会尝试自动配置网络。
按照配置文件中的提示,可以创建一个配置文件来禁用 cloud-init 的网络配置功能,具体步骤如下:
- 创建 /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg 文件
1
|
sudo vim /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
|
- 输入如下内容:
1
|
network: {config: disabled}
|
- 再次应用网络配置
sudo netplan apply
这样就解决了。