UbuntuUbuntu Based

How To Set Default Gateway on Ubuntu 24.04 LTS

Set Default Gateway on Ubuntu 24.04

In networking, the default gateway serves as the critical path through which your system communicates with external networks. Think of it as the doorway that connects your local network to the vast internet beyond. For Ubuntu 24.04 LTS users, properly configuring this gateway is essential for maintaining stable network connectivity and ensuring efficient data routing.

Ubuntu 24.04 LTS introduces refinements to its network management system, primarily built around Netplan, a YAML-based configuration utility that simplifies network setup. Whether you’re managing servers in a data center, configuring workstations in an office environment, or setting up your home lab, understanding how to properly set and manage your default gateway is fundamental to network administration.

This comprehensive guide will walk you through everything you need to know about configuring default gateways on Ubuntu 24.04 LTS. We’ll cover both temporary and permanent methods, explore advanced configuration scenarios, and provide troubleshooting tips to help you resolve common issues. By the end, you’ll have the knowledge and confidence to manage network routing effectively on Ubuntu systems.

Table of Contents

Understanding Default Gateways in Linux

A default gateway is essentially the routing device that your system uses to send network traffic when the destination lies outside the local network. In networking terms, it’s the “next hop” for packets that don’t have a more specific route defined.

When your Ubuntu system needs to communicate with a device outside your local network segment, it consults its routing table to determine the appropriate path. If no specific route exists for the destination, the system forwards the packets to the default gateway, which then handles routing them to their intended destination.

Linux handles this process through its kernel’s networking stack, which maintains routing tables that determine packet flow. These tables contain entries that map network destinations to the interfaces and next-hop addresses needed to reach them. The default gateway appears as a special entry in this table, typically denoted by the network “0.0.0.0/0,” which is a catch-all for destinations not matching more specific routes.

In Ubuntu 24.04, as with previous releases, the networking subsystem follows standard Linux routing principles but utilizes modern tools like Netplan to manage configuration. Understanding this relationship between network interfaces, IP addresses, and gateways is crucial for effective network management. Each interface can have its own IP address and subnet mask, which define the local network segment, while the gateway provides the bridge to external networks.

Network Configuration in Ubuntu 24.04 LTS

Ubuntu 24.04 LTS continues to use Netplan as its primary network configuration tool. Netplan represents a significant evolution from the traditional interfaces file approach used in earlier Ubuntu versions. It provides a more structured, declarative method for configuring networks using YAML syntax.

Understanding Netplan in Ubuntu 24.04

Netplan acts as an abstraction layer that generates configuration for either of two backend “renderers”: systemd-networkd or NetworkManager. For server installations, systemd-networkd is typically the default renderer, while desktop installations often use NetworkManager for its user-friendly interface and dynamic configuration capabilities.

The configuration files for Netplan are stored in the /etc/netplan/ directory, usually with names like 01-netcfg.yaml or 50-cloud-init.yaml. The numbering prefix determines the order in which configurations are applied, with lower numbers processed first.

YAML Configuration Format

YAML (Yet Another Markup Language) uses indentation to denote structure, making it readable but also requiring careful attention to spacing. A typical Netplan configuration follows this structure:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]

This example configures an Ethernet interface enp0s3 with a static IP address, sets a default gateway via the routes section, and specifies Google DNS servers.

Default Gateway Configuration Changes

It’s worth noting that Ubuntu 24.04 LTS fully embraces the newer routing syntax in Netplan. The older gateway4 directive has been deprecated in favor of explicitly declaring routes with the to: default and via: parameters. This change ensures better support for complex routing scenarios and provides a more consistent configuration approach.

Checking Your Current Network Configuration

Before making any changes to your gateway configuration, it’s essential to understand your current network setup. Ubuntu provides several command-line tools that allow you to view and analyze your network interfaces and routing tables.

Viewing Network Interfaces

To see all available network interfaces on your Ubuntu 24.04 system, you can use either of these commands:

ip address show

Or the shorter version:

ip a

This command displays detailed information about each interface, including its name (like enp0s3 or wlp2s0), MAC address, and IPv4/IPv6 addresses with subnet masks.

For NetworkManager-managed connections, you can also use:

nmcli d

This command shows device status and the connection profiles assigned to each interface.

Examining Routing Tables

To view your current routing configuration, including the default gateway, use:

ip route

The output typically looks something like this:

default via 192.168.1.1 dev enp0s3 proto static 
192.168.1.0/24 dev enp0s3 proto kernel scope link src 192.168.1.100

The first line indicates your default gateway (192.168.1.1 in this example) and the interface it’s associated with (enp0s3).

An alternative command with a slightly different output format is:

route -n

This shows routing tables with numeric addresses instead of resolving hostnames, which can be useful for troubleshooting.

Understanding Routing Metrics

In the routing table output, you might notice a “metric” value associated with routes. For example:

default via 192.168.1.1 dev enp0s3 proto static metric 100
default via 192.168.2.1 dev enp0s8 proto static metric 200

The metric value determines route priority when multiple routes to the same destination exist. Lower values indicate higher priority. In the example above, traffic would prefer the gateway at 192.168.1.1 because its metric (100) is lower than the alternative (200).

Understanding these metrics becomes especially important when configuring multiple default gateways or failover scenarios.

Setting a Temporary Default Gateway

There are situations where you might need to change your default gateway temporarily, such as during network testing or troubleshooting. Ubuntu provides commands that allow you to modify routing without changing configuration files, but these changes will be lost after a system reboot.

Using the IP Route Command

The ip route command allows you to add, remove, or modify routes in the kernel’s routing table. To add a temporary default gateway, use:

sudo ip route add default via 192.168.1.1

Replace 192.168.1.1 with your desired gateway address.

If you already have a default gateway configured and want to replace it, you’ll need to delete the existing route first:

sudo ip route del default
sudo ip route add default via 192.168.1.1

Specifying Interface and Metrics

For more control, you can specify the network interface and metric for the route:

sudo ip route add default via 192.168.1.1 dev enp0s3 metric 100

This command sets the default gateway to 192.168.1.1, using the enp0s3 interface with a metric of 100.

Testing Connectivity

After changing your default gateway, it’s important to verify that network connectivity works as expected. Use the ping command to test connectivity to both local and external destinations:

ping 192.168.1.1     # Test connectivity to the gateway
ping 8.8.8.8         # Test internet connectivity
ping www.ubuntu.com  # Test DNS resolution and internet connectivity

If these tests succeed, your temporary gateway is working correctly. Remember that these changes will not persist after a system reboot. For permanent changes, you’ll need to update your Netplan configuration, which we’ll cover in the next section.

Configuring a Permanent Default Gateway with Static IP

For a persistent default gateway configuration that survives system reboots, you need to update the Netplan configuration files. This section will guide you through the process of setting up a permanent default gateway alongside a static IP address.

Locating and Backing Up Netplan Configuration

First, identify the Netplan configuration file for your system:

ls -l /etc/netplan/

You’ll typically see files with names like 01-netcfg.yaml, 50-cloud-init.yaml, or 00-installer-config.yaml. Before making changes, create a backup:

sudo cp /etc/netplan/01-netcfg.yaml /etc/netplan/01-netcfg.yaml.bak

Replace 01-netcfg.yaml with the name of your actual configuration file.

Creating a Static IP Configuration with Default Gateway

Now, edit the Netplan configuration file:

sudo nano /etc/netplan/01-netcfg.yaml

For a basic static IP configuration with a default gateway, use the following template:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]

Let’s break down this configuration:

  • enp0s3: Replace this with your actual network interface name
  • addresses: Specifies your static IP address and subnet mask in CIDR notation
  • routes: Defines routing rules, with to: default indicating a default gateway
  • via: Specifies the gateway IP address
  • nameservers: Configures DNS servers

Ensure your indentation is consistent, as YAML is sensitive to spacing. Each level of indentation should use two spaces, not tabs.

Applying and Testing the Configuration

After saving the configuration file, apply the changes:

sudo netplan apply

If there are syntax errors in your YAML file, Netplan will display an error message. Fix any issues and try again.

To verify that your changes have been applied, check your routing table:

ip route

You should see your new default gateway listed. Test connectivity as described in the previous section to ensure everything works correctly.

Verifying Configuration Persistence

To confirm that your configuration persists across reboots, restart your system:

sudo reboot

After the system comes back up, check your IP configuration and routing table again:

ip a
ip route

If your static IP and default gateway are still correctly configured, you’ve successfully set up a permanent default gateway on your Ubuntu 24.04 LTS system.

Configuring Default Gateway with DHCP

DHCP (Dynamic Host Configuration Protocol) automatically assigns IP addresses and other network parameters to devices on your network. By default, DHCP also provides gateway information, but sometimes you may want to use DHCP for IP address assignment while manually specifying your own default gateway.

Understanding DHCP in Netplan

Netplan allows you to configure DHCP for IP address allocation while overriding specific settings, including the default gateway. This is useful in environments where you need to use a gateway different from the one provided by your DHCP server.

Configuring DHCP with a Custom Gateway

To configure DHCP with a custom default gateway, edit your Netplan configuration file:

sudo nano /etc/netplan/01-netcfg.yaml

Use the following template for your configuration:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: true
      dhcp4-overrides:
        use-routes: false
      routes:
        - to: default
          via: 192.168.1.1

In this configuration:

  • dhcp4: true enables DHCPv4 for automatic IP address assignment
  • dhcp4-overrides: use-routes: false tells the system to ignore the gateway provided by DHCP
  • The routes section defines your custom default gateway

If you want to override DNS settings as well, you can add a nameservers section:

nameservers:
addresses: [8.8.8.8, 8.8.4.4]

Applying and Testing DHCP Configuration

Apply the configuration with:

sudo netplan apply

To verify that your system is using DHCP for the IP address but your custom gateway for routing, check:

ip address show enp0s3
ip route

The IP address should be dynamically assigned, but the default gateway should be the one you specified, not the one provided by the DHCP server.

Test connectivity to ensure that your custom gateway is working correctly:

ping 8.8.8.8
ping www.ubuntu.com

Advanced Gateway Configuration Scenarios

Beyond basic single-gateway setups, Ubuntu 24.04 LTS supports a variety of advanced routing configurations. This section explores more complex scenarios that you might encounter in enterprise environments or specialized networking setups.

Configuring Multiple Network Interfaces

Systems with multiple network interfaces often require different routing configurations for each interface. Here’s an example Netplan configuration for a system with two network cards:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
    enp0s8:
      addresses:
        - 10.0.0.100/24
      routes:
        - to: default
          via: 10.0.0.1
          metric: 200
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]

In this configuration, traffic will preferentially use the first interface (enp0s3) for internet access due to its lower metric, while the second interface (enp0s8) serves as a backup.

Load Balancing Across Multiple Gateways

For load balancing traffic across multiple gateways, you can use equal-cost multipath (ECMP) routing. This requires additional configuration at the kernel level:

sudo sysctl -w net.ipv4.fib_multipath_hash_policy=1

To make this persistent, add it to /etc/sysctl.conf:

echo "net.ipv4.fib_multipath_hash_policy=1" | sudo tee -a /etc/sysctl.conf

Then configure multiple default routes with the same metric in Netplan:

routes:
  - to: default
    via: 192.168.1.1
    metric: 100
  - to: default
    via: 192.168.1.2
    metric: 100

Configuring Source-Based Routing

Source-based routing allows you to route traffic differently based on its source address. This can be useful for multi-homed servers. Ubuntu 24.04 supports this through policy routing:

First, create a new routing table in /etc/iproute2/rt_tables:

echo "200 alternate" | sudo tee -a /etc/iproute2/rt_tables

Then create a script to set up the routing policy:

#!/bin/bash
# Set up policy routing for source 10.0.0.100
ip route add default via 10.0.0.1 table alternate
ip rule add from 10.0.0.100 table alternate

Make this script executable and run it on startup:

sudo chmod +x /usr/local/bin/policy-routing.sh

Add it to /etc/rc.local or create a systemd service to ensure it runs at boot.

Gateway Configuration in Containerized Environments

When working with containers, routing becomes more complex. For Docker environments, you might need to adjust the Docker network settings:

sudo nano /etc/docker/daemon.json

Add the following to configure Docker’s default network and gateway:

{
  "default-address-pools": [
    {
      "base": "172.30.0.0/16",
      "size": 24
    }
  ],
  "bip": "172.30.0.1/24"
}

Restart Docker to apply changes:

sudo systemctl restart docker

For Kubernetes clusters, network plugins like Calico or Flannel manage routing between pods and nodes, each with their own gateway configuration approach that integrates with your host’s routing.

Managing Multiple Default Gateways

In complex networking environments, you might need to configure multiple default gateways for redundancy, load balancing, or to route different types of traffic through different paths. Ubuntu 24.04 LTS provides the tools and flexibility to handle these advanced scenarios.

Understanding Routing Metrics in Depth

Routing metrics determine the priority of routes when multiple paths to the same destination exist. In Ubuntu, lower metric values indicate higher priority routes. When a packet needs to be routed, the system will choose the route with the lowest metric value.

Metrics are particularly important for default gateway configuration. Consider this example routing table:

default via 192.168.1.1 dev enp0s3 proto static metric 100
default via 192.168.2.1 dev enp0s8 proto static metric 200

In this scenario, all traffic will normally go through 192.168.1.1 because it has a lower metric (100). The second gateway (192.168.2.1) will only be used if the first gateway becomes unavailable.

Setting Up a Dual-NIC System with Different Gateways

To configure a system with two network interfaces, each with its own gateway, create a Netplan configuration like this:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
        - to: 192.168.1.0/24
          via: 0.0.0.0
          table: 101
      routing-policy:
        - from: 192.168.1.100
          table: 101
    enp0s8:
      addresses:
        - 192.168.2.100/24
      routes:
        - to: default
          via: 192.168.2.1
          metric: 200
        - to: 192.168.2.0/24
          via: 0.0.0.0
          table: 102
      routing-policy:
        - from: 192.168.2.100
          table: 102

This configuration uses policy-based routing to ensure that traffic originating from each network interface returns through the same interface, while also establishing a primary/backup relationship for default routing.

Testing Multi-Gateway Configurations

After setting up multiple gateways, it’s important to test that they work as expected. You can use the ip route get command to see which gateway would be used for traffic to a specific destination:

ip route get 8.8.8.8

To test failover capability, you can temporarily disable the primary interface:

sudo ip link set enp0s3 down

Check that traffic now goes through the secondary gateway:

ip route get 8.8.8.8

Don’t forget to bring the primary interface back up after testing:

sudo ip link set enp0s3 up

For more comprehensive testing, you can use tools like mtr (My Traceroute) to examine the path packets take to reach their destination:

sudo apt install mtr
mtr 8.8.8.8

Troubleshooting Gateway Configuration Issues

Even with careful configuration, network routing problems can still occur. This section covers common issues you might encounter when setting up default gateways on Ubuntu 24.04 LTS and how to resolve them.

Common Gateway Configuration Problems

“Network Unreachable” Errors

If you see “Network Unreachable” errors when trying to connect to external networks, check:

  1. Your default gateway configuration:
    ip route | grep default

    If no default route is listed, you need to configure one.

  2. Connectivity to the gateway itself:
    ping 192.168.1.1  # Replace with your gateway address

    If you can’t ping the gateway, check physical connectivity and IP configuration.

Multiple Conflicting Default Gateways

Having multiple default gateways with the same metric can cause unpredictable routing:

ip route | grep default

If you see multiple default routes with identical metrics, adjust your configuration to use different metrics or remove unnecessary routes.

YAML Syntax Errors in Netplan

A common issue with Netplan is incorrectly formatted YAML files. If netplan apply fails with syntax errors, check:

  1. Indentation: YAML relies on consistent indentation (2 spaces per level, not tabs)
  2. Quoting: Ensure special characters in values are properly quoted
  3. Structure: Verify the hierarchical structure of your configuration

You can validate your Netplan configuration without applying it:

sudo netplan --debug generate

This will show potential issues without changing your active configuration.

Diagnostic Tools

Several tools can help diagnose routing problems:

traceroute

The traceroute utility shows the path packets take to reach a destination:

traceroute 8.8.8.8

This helps identify where in the network path communication fails.

mtr (My Traceroute)

MTR combines the functionality of traceroute and ping, providing continuous updates:

sudo apt install mtr
mtr 8.8.8.8

tcpdump

For more detailed packet analysis, use tcpdump:

sudo apt install tcpdump
sudo tcpdump -i enp0s3 -n icmp

This captures ICMP packets (like ping) on interface enp0s3, showing exactly what’s happening at the packet level.

Resolving Gateway Issues

Step 1: Check Network Interface Status

Ensure your network interface is up and properly configured:

ip link show enp0s3

Look for “UP” in the output to confirm the interface is active.

Step 2: Verify IP Configuration

Check that your interface has the correct IP address:

ip addr show enp0s3

Verify that the address matches your network configuration and is in the same subnet as your gateway.

Step 3: Test Gateway Connectivity

Try pinging your gateway:

ping -c 4 192.168.1.1

If this fails, you may have a physical connectivity issue, incorrect gateway address, or a problem with the gateway device itself.

Step 4: Check DNS Configuration

If you can ping IP addresses but not domain names, check your DNS configuration:

cat /etc/resolv.conf

Ensure that valid nameservers are listed. If needed, add DNS servers to your Netplan configuration.

Step 5: Temporarily Disable Security Measures

Firewalls and security tools can sometimes interfere with routing. Temporarily disable them for testing:

sudo ufw status
sudo ufw disable  # Only for testing; enable it again afterward

Security Considerations for Gateway Configuration

When configuring default gateways, security should be a key consideration. A poorly configured gateway can expose your system to various threats or create vulnerabilities in your network. This section outlines best practices for secure gateway configuration in Ubuntu 24.04 LTS.

Gateway Security Best Practices

1. Use Private IP Ranges for Internal Networks

For internal networks, always use private IP ranges as defined by RFC 1918:

  • 10.0.0.0/8
  • 172.16.0.0/12
  • 192.168.0.0/16

This helps prevent direct exposure of your systems to the internet.

2. Implement Proper Access Controls

Configure firewall rules to control traffic flowing through your gateways. Ubuntu’s Uncomplicated Firewall (UFW) makes this straightforward:

sudo ufw allow from 192.168.1.0/24 to any port 22
sudo ufw enable

This example allows SSH access only from your local network.

3. Regularly Update Your Gateway Devices

If your gateway is a separate hardware device (router, firewall), ensure it receives regular firmware updates to patch security vulnerabilities.

4. Monitor Gateway Traffic

Set up network monitoring to detect unusual traffic patterns that might indicate a security breach. Tools like iftop can help monitor bandwidth usage:

sudo apt install iftop
sudo iftop -i enp0s3

Firewalls and Multiple Gateways

When using multiple gateways, firewall configuration becomes more complex. You need to ensure that your firewall rules account for all possible traffic paths:

# Allow outbound traffic through primary gateway
sudo ufw allow out on enp0s3 to any

# Allow outbound traffic through secondary gateway
sudo ufw allow out on enp0s8 to any

# Be more restrictive with inbound traffic
sudo ufw deny in on enp0s3 from any to any
sudo ufw deny in on enp0s8 from any to any

# Allow specific inbound services as needed
sudo ufw allow in on enp0s3 from 192.168.1.0/24 to any port 22

For more advanced scenarios, consider using iptables directly for greater control over traffic routing and filtering:

sudo apt install iptables-persistent
sudo iptables -A FORWARD -i enp0s8 -o enp0s3 -s 192.168.2.0/24 -d 0.0.0.0/0 -j ACCEPT
sudo iptables -A FORWARD -i enp0s3 -o enp0s8 -s 0.0.0.0/0 -d 192.168.2.0/24 -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -t nat -A POSTROUTING -o enp0s3 -s 192.168.2.0/24 -j MASQUERADE
sudo netfilter-persistent save

This example configures NAT (Network Address Translation) to allow a secondary network (192.168.2.0/24) to access the internet through your primary interface.

Encrypting Network Traffic

Consider using VPNs for sensitive traffic that needs to traverse untrusted networks. Ubuntu 24.04 LTS supports various VPN solutions, including OpenVPN and WireGuard:

sudo apt install wireguard

After setting up the VPN, you can create specific routes to ensure certain traffic types use the encrypted tunnel:

network:
  version: 2
  ethernets:
    enp0s3:
      addresses: [192.168.1.100/24]
      routes:
        - to: default
          via: 192.168.1.1
  wg0:
    addresses: [10.0.0.2/24]
    routes:
      - to: 10.0.0.0/24
        via: 10.0.0.1
      - to: 192.168.5.0/24
        via: 10.0.0.1

This configuration routes traffic to the 192.168.5.0/24 network through the WireGuard VPN.

Gateway Configuration Command Reference

Command Description Example
ip route Show routing table ip route
ip route add Add a temporary route sudo ip route add default via 192.168.1.1
ip route del Delete a route sudo ip route del default
netplan apply Apply Netplan configuration sudo netplan apply
netplan try Test Netplan configuration sudo netplan try
ip addr Show IP addresses ip addr show enp0s3
ping Test connectivity ping -c 4 8.8.8.8
traceroute View network path traceroute 8.8.8.8
mtr Interactive traceroute mtr 8.8.8.8
sysctl Configure kernel parameters sudo sysctl -w net.ipv4.ip_forward=1

Nginx Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “Nginx Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button