前言
最近在学习微服务,搭建利用k8s搭建集群,所以需要开启多台虚拟机,系统默认的IP分配方式是DHCP,也就是动态分配IP地址。如果不设置静态IP,那么每次重启机器的IP可能会发生改变,所以在阅读一些资料以及实操后写下这篇博客,以便帮助需要的人以及后期回顾。另外,ubuntu16.04和ubuntu18.04操作有差异,下面会分别给出详细的操作步骤。
查看IP地址和网卡接口名称
可以通过ip a或ifconfig命令查看所有网卡接口信息。ip a命令打印结果示例:

配置静态IP
ubuntu 16.04
- 通过
vi /etc/network/interfaces命令编辑配置文件,
原内容如下:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto ens33
iface ens33 inet dhcp
修改后的内容如下:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto ens33
iface ens33 inet static
address 192.168.124.110
netmask 255.255.255.0
gateway 192.168.124.2
dns-nameservers 114.114.114.114
主要修改的地方是将dhcp改为了static,并且配置了静态IP地址、子网掩码、网关和DNS服务器地址。其中DNS地址可以换成当地运营商DNS。
注意:其中ens33是通过ip a命令中获取的,名称可能稍有变动,改成自己机器打印的名称即可。
2. 通过vi /etc/hostname命令修改主机名
3. 通过vi /etc/hosts命令配置hosts,添加一行(其中kubernetes-master是上面修改的主机名)
192.168.124.110 kubernetes-master
ubuntu 18.04
- 设置静态IP
编辑vi /etc/netplan/50-cloud-init.yaml配置文件,修改内容如下
network:
ethernets:
ens33:
addresses: [192.168.124.110/24]
gateway4: 192.168.124.2
nameservers:
addresses: [114.114.114.114]
version: 2
修改后使用netplan apply命令让配置生效
- 配置主机名
hostnamectl set-hostname kubernetes-master
- 配置hosts
cat >> /etc/hosts << EOF
192.168.124.110 kubernetes-master
EOF
注意:无论是16.04还是18.04,在修改成功后重启即可生效。