[Linux][AWS] EC2主機單張網卡(Single Network Interface)有複數第二IP(Second IP)、第三IP(Third IP)的作法
[Linux][AWS] EC2主機單張網卡 (Single Network Interface) 有複數第二IP (Second IP)、第三IP (Third IP) 的作法
OS Version: Ubuntu 16.04.5 LTS
截至目前為止根據官方文件﹐除了AWS自己推出的Linux AMI之外,其他版本的Linux AMI並不會自動掛載 (Auto Mount) 第二或第三IP,另外目前無法簡單的使用多網卡多IP,因為這跟AWS設計的Routing Table有關,如果想掛多網卡多IP的話就必須要調整Routing Table,所以多IP (Multiple IP) 的作法目前還是推薦使用單網卡的形式比較簡單。
臨時貼上的作法
早期的AWS在增加Secondary Private IP (2nd Priv IP)的時候,常會用Shell Scripts的作法來進行,內容如下:
#! /bin/bash
/sbin/ifconfig eth0:1 192.168.2.167 netmask 255.255.255.0 up
/sbin/ifconfig eth0:2 192.168.2.168 netmask 255.255.255.0 up
上述是ifconfig指令的作法,下面是ip指令,
# 格式(Format)
ip address add <ip-address>/<netmask> dev <interface>
# Eample
#! /bin/bash
ip address add 192.168.2.167/24 dev eth0
ip address add 192.168.2.168/24 dev eth0
ifup eth0
上述的作法並不是說不可行,但是每次Instance重開或是服務重啟都有可能IP就會消失,畢竟是暫時把IP貼上去而已,所以早期的作法就會把它變成一個.sh檔案,並且定時排程去執行他以免IP消失,至於要使用哪種方法,就請依照自己的架構來決定最適合你的吧。
設定檔的作法
在來說明一下永久性的設定方法,就是把IP寫進網卡設定檔中,這樣不管他怎麼重開機或重啟服務,IP都會根據你的設定檔來設定
# AWS Ubutnu類的設定檔位置
vim /etc/network/interfaces.d/50-cloud-init.cfg
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# 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}
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
上面是原始設定,下面是修改過後的設定的寫法1:
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# 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}
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
iface eth0 inet static
address 192.168.2.167/24
iface eth0 inet static
address 192.168.2.168/24
下面是修改過後的設定的寫法2:
# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# 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}
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
auto eth0:1
iface eth0:1 inet static
address 192.168.2.167
netmask 255.255.255.0
gateway 192.168.2.1
auto eth0:2
iface eth0:2 inet static
address 192.168.2.168
netmask 255.255.255.0
gateway 192.168.2.1
改完後記得重開機,重啟網路服務當然也是可以。
2種寫法的差異在gateway的設定上,寫法1請不要再加上gateway,不然你會發現你第三個IP加不上去,寫法2則是可以手動加上gateway,
2種寫法都有人用,至於要用那一種就依照自己的習慣就好,以上。
Reference
How can I make my secondary network interface work in my CentOS or RHEL EC2 instance?
Step-by-step configuring 2 ip address on a amazon linux vpc instance
How can I (from CLI) assign multiple IP addresses to one interface?