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

### 配置静态IP
#### ubuntu 16.04
1. 通过`vi /etc/network/interfaces`命令编辑配置文件,
原内容如下:
```shell
# 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
```
修改后的内容如下:
```shell
# 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`是上面修改的主机名)
```shell
192.168.124.110 kubernetes-master
```
#### ubuntu 18.04
1. 设置静态IP
编辑`vi /etc/netplan/50-cloud-init.yaml` 配置文件,修改内容如下
```shell
network:
ethernets:
ens33:
addresses: [192.168.124.110/24]
gateway4: 192.168.124.2
nameservers:
addresses: [114.114.114.114]
version: 2
```
修改后使用`netplan apply`命令让配置生效
2. 配置主机名
```shell
hostnamectl set-hostname kubernetes-master
```
3. 配置hosts
```shell
cat >> /etc/hosts << EOF
192.168.124.110 kubernetes-master
EOF
```
注意:无论是16.04还是18.04,在修改成功后重启即可生效。

Ubuntu设置静态IP及修改主机名