Ubuntu 18.04 Network card with two IP addresses

I would like to learn how to setup my network card with two IP addresses

I tried as bellow, but now

network:
  version: 2
  renderer: NetworkManager
  ethernets:
     enp0s3:
        dhcp4: no
        dhcp6: no
        addresses: [ 192.168.0.2/32, 172.16.0.2/16 ]
        gateway4: 192.168.0.1
        gateway4: 172.16.0.1
        nameservers:
              search: [usp.br]
              addresses: [ 192.168.0.100, 192.168.0.102 ]
        optional: true

Each IP has its own gateway....

Could you please help me how to it?

Thank you


Solution 1:

There are often issues with having multiple gateways set for interfaces. Routing packets over to one and then the other may lead to confusion on the network, so you're often best served by having a single default gateway unless you really know what you are doing.

In short, you usually want only one

gateway4: xx.xx.xx.xx

line in your config.

If you must have multiple routes for the individual IPs of the interface, you can control exactly how they will behave by writing static routes (and setting the metric based on the priority of the addresses), like so:

network:
  version: 2
  renderer: NetworkManager
  ethernets:
     enp0s3:
        dhcp4: no
        dhcp6: no
        addresses: [ 192.168.0.2/32, 172.16.0.2/16 ]
        nameservers:
              search: [usp.br]
              addresses: [ 192.168.0.100, 192.168.0.102 ]
        routes:
          - to: 0.0.0.0/0
            via: 192.168.0.1
          - to: 0.0.0.0/0
            via: 172.168.0.1

You also don't need optional: true: it only stops delaying boot if the interface isn't coming up fast enough, which shouldn't be an issue given that you specific static addresses. Adding optional: true also has the side effect of not blocking for some targets in systemd, which might mean a server will not start all the services it should right away if these services need the network.

Solution 2:

A bit late, but... It makes little sense to have 2 default gateways. Think about it: If i do ping 8.8.8.8, what gateway should it use?

You CAN setup priority, if one line is slower/more expensive/only for backup/... If both have same priority, I suspect it will try to do round-robbin.