How to Change Default Gateway on Ubuntu 20: Easy Guide

How to Change Default Gateway on Ubuntu 20: Easy Guide
how to change default gateway on ubuntu 20

Navigating the complexities of network configurations on Linux systems, particularly Ubuntu, can seem daunting to newcomers and even seasoned administrators at times. Among the fundamental components of any network setup, the default gateway stands as a pivotal element, acting as the primary exit point for all network traffic destined for external networks, including the vast expanse of the internet. Understanding how to correctly configure and, crucially, how to change this default gateway on an Ubuntu 20.04 system is an essential skill for anyone managing servers, workstations, or even personal computers within a larger network infrastructure. This comprehensive guide will meticulously walk you through the various methods of altering your default gateway on Ubuntu 20.04, ensuring you gain a deep understanding of the underlying principles, the practical steps involved, and the best practices for maintaining a stable and secure network connection.

The journey of a data packet from your Ubuntu machine to a server on the internet is orchestrated by a series of rules, with the default gateway rule being the most critical for outbound traffic. When your computer needs to send data to an IP address that isn't on its local network segment, it consults its routing table. If no specific route is defined for that destination network, the data packet is invariably sent to the default gateway. This gateway then assumes the responsibility of forwarding the packet to its next hop, continuing this process until the packet reaches its final destination. Therefore, a correctly configured default gateway is not just an option but a necessity for seamless internet access and inter-network communication.

Ubuntu 20.04, codenamed "Focal Fossa," relies primarily on Netplan for network configuration, especially in server environments, while desktop installations often leverage NetworkManager in conjunction with Netplan. This guide will delve into both approaches, offering detailed instructions for temporary modifications using command-line tools and permanent changes through Netplan configuration files, along with considerations for NetworkManager users. Our aim is to demystify the process, providing you with the knowledge and confidence to manage your Ubuntu system's network settings effectively, ensuring optimal performance and connectivity.

Understanding the Fundamentals: What is a Default Gateway?

Before we delve into the "how-to," it's imperative to establish a clear understanding of what a default gateway is and why it holds such significance in networking. At its core, a gateway is a network node that connects two different networks, essentially acting as a bridge or a portal. In the context of your local area network (LAN), the default gateway is typically a router – a device responsible for forwarding packets between your local network and other networks, most commonly the internet.

Imagine your local network as a closed community where all houses (devices) know how to talk to each other directly. However, if a resident (your Ubuntu machine) wants to send a letter (data packet) to someone outside the community (an external server on the internet), they need to know where the post office (the default gateway) is. All letters destined for outside the community are handed over to this post office, which then takes care of forwarding them to the correct external address. Without a post office, your letters would have nowhere to go once they leave your internal community.

Specifically, the default gateway is the IP address of the router or device that your computer uses to send all traffic that is not explicitly routed elsewhere. Every device on your local network needs to know the IP address of this gateway to communicate with anything beyond its immediate network segment. If this address is incorrect, your Ubuntu system will be unable to reach external resources, resulting in a frustrating lack of internet connectivity and communication breakdowns with remote servers.

The default gateway is defined as a specific entry in your operating system's routing table. The routing table is like a directory that tells your system how to reach various destinations. For example, it might contain entries like: "To reach network X, send packets via interface Y" or "To reach host Z, send packets via gateway A." The default gateway entry is special because it's a catch-all: "For any destination not explicitly listed, send packets to this gateway." This "default route" is what makes global communication possible for your device.

Why Would You Need to Change Your Default Gateway?

The default gateway is usually set automatically when your Ubuntu system receives its network configuration via DHCP (Dynamic Host Configuration Protocol). However, there are several scenarios where you might need to manually change this crucial setting:

  1. Router Replacement or Upgrade: If you replace your existing router with a new one, or if your Internet Service Provider (ISP) changes your network configuration, the IP address of the default gateway might change. Your Ubuntu system will need to be updated to reflect this new gateway address to restore internet connectivity.
  2. Network Reconfiguration: In larger or more complex network environments, administrators might re-segment networks, change subnet schemes, or introduce new routing policies. As a result, the default gateway for a specific subnet or device might need to be altered to align with the new network topology.
  3. Specific Routing Requirements: You might have a specialized network setup where certain traffic needs to be routed through a different gateway for performance, security, or policy reasons. For instance, you might have a dedicated gateway for VPN traffic or a secondary gateway for specific services, separate from the primary internet gateway.
  4. Troubleshooting Network Issues: Sometimes, network connectivity problems can stem from an incorrect or malfunctioning default gateway. Changing the gateway to an alternative, known-good router (if available) can be a troubleshooting step to isolate the problem.
  5. Setting up a Statically Configured IP: While DHCP automatically assigns a gateway, if you're configuring your Ubuntu machine with a static IP address, you must manually specify the default gateway as part of the static configuration. This is common for servers that require a consistent IP address.
  6. Performance Optimization: In advanced network setups, a network administrator might wish to direct traffic through a gateway that offers better performance, lower latency, or higher bandwidth for certain types of data.
  7. Security Enhancements: In some cases, a network might be designed with multiple gateway devices, perhaps with one gateway having more stringent firewall rules or intrusion detection systems. Directing certain traffic through such a gateway can enhance network security.

Understanding these reasons not only justifies the need to change the default gateway but also highlights the importance of correctly implementing these changes to maintain network integrity and functionality. Each of these scenarios underscores the critical role of the default gateway in dictating how your Ubuntu system communicates with the broader network landscape.

Prerequisites and Important Considerations Before You Begin

Before you embark on modifying your Ubuntu system's network configuration, especially the default gateway, it is crucial to ensure you have the necessary information and take precautionary steps. Incorrect network settings can lead to complete loss of network connectivity, potentially locking you out of a remote server or rendering your local machine unable to access the internet.

Essential Information You Will Need:

  1. Current Default Gateway IP Address: Knowing your current gateway is important for verification and as a reference point. You can find this using ip route show or route -n.
  2. New Default Gateway IP Address: This is the most critical piece of information. Ensure you have the correct IP address of the router or device that will serve as the new default gateway. Double-check this address to avoid connectivity issues.
  3. Your Ubuntu System's IP Address: If you are configuring a static IP, you will need a free and valid IP address within your network's subnet.
  4. Subnet Mask: This defines the range of IP addresses within your local network. Common subnet masks are /24 (255.255.255.0) or /16 (255.255.0.0).
  5. DNS Server Addresses: While not directly related to the gateway, you'll likely need to configure DNS servers to resolve domain names to IP addresses (e.g., Google's 8.8.8.8 and 8.8.4.4, or your ISP's DNS). Without correct DNS, you won't be able to browse websites by name, even if you have internet connectivity.
  6. Network Interface Name: You need to know the name of the network interface you intend to configure (e.g., eth0, enp0s3, ens33). You can find this using ip a or ifconfig.

Important Considerations and Best Practices:

  1. Administrative Privileges: You will need sudo privileges to modify network configurations. All commands in this guide assume you are operating with sudo or as the root user.
  2. Physical Access (for remote servers): If you are changing the gateway on a remote server, strongly consider having a fallback plan. An incorrect configuration can sever your SSH connection. If possible, have someone with physical access to the server who can revert changes or a console access (e.g., KVM over IP) to avoid being locked out.
  3. Backup Configuration Files: Before making any permanent changes, especially to Netplan configuration files, always back up the original files. This allows for easy reversion if something goes wrong. For Netplan, this often means backing up /etc/netplan/*.yaml.
  4. Understand Your Network Topology: Be aware of how your network is structured. Are there multiple routers? Is there a specific VLAN you need to be on? A clear understanding prevents misconfigurations.
  5. Test Thoroughly: After making changes, verify connectivity immediately. Ping external IP addresses (e.g., 8.8.8.8), then try pinging a domain name (e.g., google.com) to confirm DNS resolution is also working.
  6. Temporary vs. Persistent Changes: Be mindful of whether your changes are temporary (valid until reboot) or persistent (survive reboots). We will cover both methods.
  7. Consult Documentation: If you're working in an enterprise environment, always consult your organization's network documentation and policies before making changes.

By meticulously gathering this information and adhering to these considerations, you can minimize risks and ensure a smoother, more successful process when changing your default gateway on Ubuntu 20.04.

Method 1: Temporary Changes Using the ip Command

The ip command is a powerful, modern utility for managing network interfaces, routing tables, and various other network settings on Linux. It is the successor to the older ifconfig and route commands and is generally preferred for its comprehensive capabilities. Changes made with the ip command are temporary, meaning they will be lost upon system reboot or network service restart. This makes it an ideal method for quick tests, troubleshooting, or for configurations that are only needed for a short period.

Understanding the ip Command for Routing

The core of changing the default gateway with ip lies in manipulating the routing table. Specifically, we'll be adding and deleting routes.

  • ip route show: Displays the current routing table.
  • ip route add: Adds a new entry to the routing table.
  • ip route del: Deletes an entry from the routing table.

The default gateway is represented by a default route entry, typically default via <gateway_ip> dev <interface>.

Step-by-Step Guide to Temporarily Change the Default Gateway:

Step 1: Identify Your Current Default Gateway

First, let's see what your current default gateway is. This command will show you the entire routing table. Look for the line that starts with default.

ip route show

You might see output similar to this:

default via 192.168.1.1 dev enp0s3 proto dhcp metric 100
192.168.1.0/24 dev enp0s3 proto kernel scope link src 192.168.1.100 metric 100

In this example, 192.168.1.1 is the current default gateway, and enp0s3 is the network interface.

Step 2: Delete the Existing Default Route

To avoid conflicts and ensure your new gateway is used, you should first delete the existing default route.

sudo ip route del default

This command removes the entry that directs all non-local traffic to the old gateway. If you omit this step and just add a new default route, you might end up with two default routes, leading to unpredictable routing behavior.

Step 3: Add the New Default Route

Now, add the new default gateway. You will need the IP address of your new gateway and the name of your network interface. Let's assume your new gateway is 192.168.1.254 and your interface is enp0s3.

sudo ip route add default via 192.168.1.254 dev enp0s3
  • default: Specifies that this is the default route (the catch-all route).
  • via 192.168.1.254: Specifies the IP address of the next-hop router, which is your new default gateway.
  • dev enp0s3: Specifies the network interface through which packets should be sent to reach the gateway. Ensure this matches your actual network adapter.

Step 4: Verify the Change

After adding the new route, immediately verify that the change has been applied correctly by inspecting the routing table again.

ip route show

You should now see the new default gateway listed:

default via 192.168.1.254 dev enp0s3
192.168.1.0/24 dev enp0s3 proto kernel scope link src 192.168.1.100 metric 100

Step 5: Test Connectivity

Finally, test your internet connectivity by pinging an external IP address and then a domain name.

ping -c 4 8.8.8.8      # Ping Google's DNS server by IP
ping -c 4 google.com   # Ping Google's website by domain name

If both pings are successful, your default gateway change was successful for the current session. If pinging the IP works but the domain name fails, it indicates a DNS resolution issue, not a gateway problem. If neither works, you might have entered an incorrect gateway IP or there's another network issue.

Limitations of the ip Command Method:

As mentioned, changes made using ip route are temporary. This means:

  • System Reboot: The changes will be lost after a system reboot.
  • Network Service Restart: Restarting the network service (e.g., systemctl restart systemd-networkd or systemctl restart NetworkManager) might also revert these changes, depending on how your system is configured.

For permanent changes, you must modify the network configuration files, which we will explore in the next section using Netplan. However, for quick diagnostic work or on-the-fly adjustments, the ip command is an indispensable tool.

Method 2: Persistent Changes Using Netplan (Ubuntu 20.04 Standard)

Ubuntu 20.04, like its immediate predecessors, primarily uses Netplan for configuring network interfaces. Netplan acts as an abstraction layer, allowing you to define network configurations in YAML files, which it then translates into configurations for underlying renderers like systemd-networkd or NetworkManager. This method is the recommended way to make permanent changes to your network settings, including the default gateway, on server editions of Ubuntu and often on desktop editions where NetworkManager is not preferred for primary network interfaces.

Understanding Netplan's Role

Netplan configuration files are located in /etc/netplan/ and typically end with the .yaml extension. When Ubuntu boots, Netplan reads these files, generates the necessary configuration for the chosen backend (e.g., systemd-networkd), and applies them. This ensures that your network settings, including your default gateway, are persistent across reboots.

Step-by-Step Guide to Change Default Gateway with Netplan:

Step 1: Identify Your Existing Netplan Configuration File

Navigate to the /etc/netplan/ directory. You will typically find one or more YAML files. Common names are 01-netcfg.yaml, 50-cloud-init.yaml, or a custom name.

ls /etc/netplan/

Identify the primary configuration file for your network interface. If there are multiple, inspect them to determine which one is active or contains the relevant interface configuration. You can do this by opening them with a text editor like nano or vi.

sudo nano /etc/netplan/01-netcfg.yaml # Replace with your file name

Step 2: Back Up Your Current Netplan Configuration

Before making any modifications, always create a backup of your existing Netplan file. This is a critical step that allows you to easily revert to a working configuration if your changes lead to connectivity issues.

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

Step 3: Edit the Netplan Configuration File

Now, open the Netplan configuration file using your preferred text editor.

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

The content of the file will vary depending on whether your interface is currently configured for DHCP or a static IP. We will cover both scenarios.

Scenario A: Changing Gateway for a DHCP-Configured Interface

If your interface is set to obtain an IP address via DHCP, you typically won't explicitly see a gateway entry, as DHCP automatically provides it. However, you can force a specific gateway even with DHCP, though this is less common and usually not recommended unless you have a specific network setup where the DHCP-assigned gateway is incorrect.

A typical DHCP configuration looks like this:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: true

To override the DHCP-provided gateway (which is unusual, as DHCP is meant to manage this), or to add a static gateway while still getting an IP from DHCP (which can be problematic), you would need to add a routes section. However, a more robust approach if you need a specific gateway that DHCP doesn't provide is to switch to a static IP configuration. If you must use DHCP for the IP but a different gateway, it suggests a non-standard network setup.

For most cases, if you want to change the gateway, you're likely moving to a static IP setup.

Scenario B: Changing Gateway for a Statically Configured Interface

If your interface is statically configured, the gateway is explicitly defined. A typical static configuration might look like this:

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

To change the default gateway, you simply need to modify the via address under the routes section. For example, to change the gateway to 192.168.1.254:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: false
      addresses:
        - 192.168.1.100/24 # Your static IP and subnet mask
      routes:
        - to: default
          via: 192.168.1.254 # Your NEW default gateway IP
      nameservers:
        addresses:
          - 8.8.8.8 # Primary DNS server
          - 8.8.4.4 # Secondary DNS server

Important Notes on YAML Syntax:

  • Indentation is Crucial: YAML is highly sensitive to indentation. Use spaces, not tabs, for indentation, typically two spaces per level. Incorrect indentation will lead to syntax errors.
  • Correct Syntax: Ensure routes and nameservers are correctly aligned under ethernets and their respective sub-keys.
  • to: default: This specifies that the route is for all destinations not explicitly defined, i.e., the default route.
  • via: <IP_ADDRESS>: This is where you specify the IP address of your default gateway.

Step 4: Apply the Netplan Configuration

After saving your changes to the YAML file, you need to apply the new configuration. Netplan provides two commands for this:

  1. sudo netplan try: This command applies the changes and starts a countdown timer. If network connectivity is lost or not re-established within the timer (usually 120 seconds), Netplan automatically reverts to the previous working configuration. This is the safest way to test changes on a remote server or critical system.bash sudo netplan tryIf everything works, press Enter to confirm the changes before the timer runs out. If connectivity breaks, just let the timer expire, and Netplan will revert.
  2. sudo netplan apply: This command applies the changes immediately without a rollback mechanism. Use this only when you are very confident in your changes, or when you have physical access to the machine.bash sudo netplan applyIt's generally recommended to run sudo netplan generate first, which checks your YAML syntax for errors and generates the backend configuration files without applying them. This can catch basic syntax issues before apply or try.bash sudo netplan generate sudo netplan apply

Step 5: Verify the Change

After applying the configuration, verify that the default gateway has been updated in the routing table.

ip route show

You should see your new gateway listed as the default route.

Step 6: Test Connectivity

Finally, confirm full network connectivity:

ping -c 4 192.168.1.254 # Ping your new gateway to ensure it's reachable
ping -c 4 8.8.8.8      # Ping an external IP address
ping -c 4 google.com   # Ping an external domain name

If these tests are successful, your default gateway has been persistently changed using Netplan. This method is robust and ensures your settings survive system reboots, making it suitable for servers and production environments.

Netplan for Multiple Gateways / Advanced Routing

While this guide focuses on changing the default gateway, Netplan is capable of defining more complex routing scenarios. For instance, you might have specific routes for certain subnets that go through a different gateway.

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: false
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.254 # Default gateway for general internet traffic
        - to: 10.0.0.0/8    # Route for the 10.0.0.0/8 network
          via: 192.168.1.2 # A different gateway for internal network segments
      nameservers:
        addresses:
          - 8.8.8.8
          - 8.8.4.4

This example demonstrates how you can direct traffic for a specific internal network (10.0.0.0/8) through a different internal router (192.168.1.2), while all other traffic (the default route) goes through 192.168.1.254. This flexibility is one of Netplan's strengths, allowing for sophisticated network configurations.

When dealing with more intricate network architectures, especially those involving multiple services and different network segments, robust management of API calls across these segments becomes crucial. For example, in an environment where AI models and REST services are deployed across various network gateways or internal subnets, a tool like APIPark can be invaluable. APIPark serves as an open-source AI gateway and API management platform, designed to simplify the integration, deployment, and management of hundreds of AI models and REST services, centralizing authentication, cost tracking, and standardizing API formats across complex infrastructures. While Netplan handles the fundamental network routing, APIPark addresses the higher-level concerns of intelligent service communication and governance, demonstrating how specialized gateways play a vital role beyond basic internet connectivity in modern enterprise environments.

APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! πŸ‘‡πŸ‘‡πŸ‘‡

Method 3: Persistent Changes Using nmcli (NetworkManager CLI)

For Ubuntu desktop installations, and sometimes on servers where NetworkManager is installed and active, the nmcli (NetworkManager Command Line Interface) tool provides a powerful and convenient way to manage network connections. NetworkManager is a dynamic network configuration and management utility that aims to make network configuration straightforward. Changes made through nmcli are persistent and survive reboots.

Understanding NetworkManager and nmcli

NetworkManager manages network interfaces and connections by creating "connection profiles." Each profile contains the configuration for a specific network setup (e.g., Wi-Fi, Ethernet, VPN). nmcli allows you to interact with these profiles from the command line, offering granular control over settings like IP addresses, DNS servers, and, of course, the default gateway.

Step-by-Step Guide to Change Default Gateway with nmcli:

Step 1: List Existing NetworkManager Connections

First, identify the active connection you want to modify and its connection name.

nmcli con show

You'll see a list of connections, their UUIDs, types, and devices. Look for the ethernet type that is active and associated with your network interface (e.g., enp0s3). Note down the NAME of this connection (e.g., "Wired connection 1").

NAME                UUID                                  TYPE      DEVICE
Wired connection 1  a1b2c3d4-e5f6-7890-1234-567890abcdef  ethernet  enp0s3
# ... other connections ...

Step 2: Display Current Connection Details

Before making changes, it's good practice to view the current configuration of your chosen connection.

nmcli con show "Wired connection 1" | grep "ipv4.gateway"

This command will show you the current gateway configured for that connection. You might also want to see other IP-related settings:

nmcli con show "Wired connection 1" | grep "ipv4"

Step 3: Change the Default Gateway

The command to change the gateway depends on whether your connection uses DHCP or a static IP.

Scenario A: Changing Gateway for a DHCP-Configured Interface (Less Common for nmcli)

If your connection is configured for DHCP (ipv4.method auto), NetworkManager typically gets the gateway from the DHCP server. You can't directly "change" the DHCP-assigned gateway while keeping the ipv4.method auto without potentially causing conflicts or overriding DHCP's intent.

If you need a specific gateway, the most reliable approach is to switch to a static IP configuration, as detailed in Scenario B. If you still want to try to set a static gateway with DHCP for the IP, it's possible but can be complicated and often indicates a misconfigured network. A common approach to set a static gateway is to first configure the IP method to manual, then assign the IP, gateway, and DNS.

Scenario B: Changing Gateway for a Statically Configured Interface

If your connection is configured with a static IP (ipv4.method manual), you can directly modify the gateway IP. Let's assume your connection name is "Wired connection 1", and your new gateway is 192.168.1.254.

sudo nmcli con mod "Wired connection 1" ipv4.method manual
sudo nmcli con mod "Wired connection 1" ipv4.addresses 192.168.1.100/24 # Your static IP
sudo nmcli con mod "Wired connection 1" ipv4.gateway 192.168.1.254     # Your NEW gateway
sudo nmcli con mod "Wired connection 1" ipv4.dns "8.8.8.8,8.8.4.4"    # Your DNS servers
  • nmcli con mod "Wired connection 1": This targets the specific connection profile.
  • ipv4.method manual: Ensures the IP configuration is managed manually. If it was auto, changing the gateway will likely override the DHCP assignment.
  • ipv4.addresses 192.168.1.100/24: Sets your static IP address and subnet mask.
  • ipv4.gateway 192.168.1.254: This is the crucial part that sets your new default gateway.
  • ipv4.dns "8.8.8.8,8.8.4.4": Specifies DNS servers, which are essential for name resolution.

Step 4: Reactivate the Connection

After making the changes, you need to bring the connection down and then up again for the new settings to take effect.

sudo nmcli con down "Wired connection 1"
sudo nmcli con up "Wired connection 1"

Step 5: Verify the Change

Verify that the new gateway is active by checking the routing table.

ip route show

Look for the default route to confirm your new gateway IP.

Step 6: Test Connectivity

As always, test your network connectivity.

ping -c 4 192.168.1.254 # Ping your new gateway
ping -c 4 8.8.8.8      # Ping an external IP
ping -c 4 google.com   # Ping an external domain

If these tests are successful, your default gateway has been persistently updated using nmcli. This method is particularly useful on desktop systems or servers where NetworkManager is the primary network configuration service. It offers dynamic management without requiring direct editing of YAML files, making it flexible for on-the-fly adjustments that persist.

Method 4: Using the Graphical User Interface (GUI)

For Ubuntu desktop users, changing the default gateway can often be accomplished through the graphical user interface (GUI) provided by the desktop environment, typically GNOME for Ubuntu 20.04. This method is generally the most user-friendly for those who prefer visual interaction over command-line tools. The GUI interacts with NetworkManager in the background, making persistent changes.

Step-by-Step Guide to Change Default Gateway with GUI (GNOME):

Step 1: Open Network Settings

Click on the top-right corner of your screen (usually where the Wi-Fi/Ethernet icon is, or power/volume icons). From the dropdown menu, select "Wired Connected" (for Ethernet) or "Wi-Fi Connected" (for Wi-Fi) and then click on "Wired Settings" or "Wi-Fi Settings" respectively.

Alternatively, you can go to the "Activities" overview, search for "Settings," and then navigate to the "Network" section in the left-hand sidebar.

Step 2: Access Connection Settings

In the Network settings window, you'll see a list of network connections. For a wired connection, you should see an "Ethernet" section. Click on the gear icon (βš™οΈ) next to the active connection (e.g., Wired or the specific network name) that you wish to modify.

Step 3: Configure IPv4 Settings

A new window will appear with details for your chosen network connection. Navigate to the "IPv4" tab.

Step 4: Change the Default Gateway

Within the IPv4 tab, you will typically see three options for "IPv4 Method":

  • Automatic (DHCP): If your current setting is "Automatic (DHCP)," the system is obtaining its IP address, subnet mask, gateway, and DNS servers automatically from a DHCP server. To manually set a gateway, you need to change this method to "Manual."
  • Manual: This option allows you to explicitly define your IP address, Netmask, Gateway, and DNS servers.
  • Change Method to "Manual": If it's set to "Automatic (DHCP)," switch the "IPv4 Method" dropdown to "Manual."
  • Enter IP Address: In the "Addresses" section, click the + button. Enter your desired static IP address (e.g., 192.168.1.100), the Netmask (e.g., 255.255.255.0 or 24 in CIDR notation), and crucially, your Gateway address (e.g., 192.168.1.254).
  • Enter DNS Servers (Optional but Recommended): In the "DNS" section, toggle "Automatic" off and enter your preferred DNS server IP addresses, separated by commas (e.g., 8.8.8.8, 8.8.4.4).
  • Remove Old Gateway (if applicable): If you had an existing static configuration, ensure the old gateway entry is removed or overwritten.

Refer to the table below for a quick reference on typical network settings:

Setting Description Example Value (for a static IP)
IPv4 Method How the IP address is obtained. Manual
Addresses Your device's static IP address and subnet mask. 192.168.1.100/24
Gateway The IP address of the router that connects to external networks. 192.168.1.254
DNS Servers IP addresses of servers that resolve domain names to IP addresses. 8.8.8.8, 8.8.4.4
Search Domains Domains appended to hostnames for lookup (e.g., example.com). (Optional)

Step 5: Apply Changes

After entering all the details, click the "Apply" or "Done" button at the top right of the window. This will apply the new network settings. The network connection might momentarily disconnect and then reconnect.

Step 6: Verify and Test Connectivity

  1. Verify via GUI: Go back to the network settings. Click the gear icon again, and confirm the IPv4 tab now shows your new manual configuration, including the updated gateway.
  2. Verify via Command Line: Open a terminal and use ip route show to confirm the default gateway in the routing table.
  3. Test Connectivity: bash ping -c 4 192.168.1.254 # Ping your new gateway ping -c 4 8.8.8.8 # Ping an external IP ping -c 4 google.com # Ping an external domain Ensure that you can successfully ping both your new gateway and external addresses/domains.

This GUI method is excellent for desktop users who prefer a visual approach and ensures that the changes are persistent across reboots. It streamlines the process by abstracting the underlying NetworkManager commands.

Verifying Network Configuration and Troubleshooting Common Issues

After making changes to your default gateway, verification is not merely a recommendation but a mandatory step. It ensures that your system can communicate effectively with the local network and the internet. Should issues arise, a systematic troubleshooting approach is essential.

How to Verify Your Network Configuration:

  1. Check the Routing Table: The ip route show command is your primary tool for inspecting the current routing table.bash ip route showLook for the default entry. It should show your newly configured gateway IP address, like default via 192.168.1.254 dev enp0s3. This confirms that your system knows where to send traffic destined for external networks.
  2. Check Network Interface IP Address: Ensure your network interface has the correct IP address and subnet mask.bash ip a show enp0s3 # Replace enp0s3 with your actual interface nameVerify that the inet address matches what you intended to set for your system's IP.
  3. Ping Your Gateway: The first connectivity test should be to ping your new default gateway. This checks if your Ubuntu machine can reach the router.bash ping -c 4 192.168.1.254 # Replace with your gateway IPIf this fails, it indicates an issue with reaching the gateway itself. Potential causes include incorrect gateway IP, physical cabling issues, or the gateway device being offline.
  4. Ping an External IP Address: If you can ping your gateway, the next step is to ping a well-known external IP address, such as Google's DNS server (8.8.8.8) or Cloudflare's (1.1.1.1). This verifies that your system can traverse the gateway and reach the internet.bash ping -c 4 8.8.8.8If this fails but pinging the gateway succeeds, it suggests the issue lies beyond your local network or with the gateway's ability to forward traffic (e.g., ISP problem, gateway firewall).
  5. Ping an External Domain Name: Finally, test DNS resolution by pinging a domain name (e.g., google.com).bash ping -c 4 google.comIf pinging an external IP works but pinging a domain name fails, it indicates a problem with your DNS server configuration, not the gateway itself. Verify your DNS server settings in Netplan or NetworkManager.
  6. Trace Route to an External Host: The traceroute command can help identify where connectivity breaks down by showing the path packets take to a destination.bash traceroute google.comThis will show each hop (router) your packets pass through, starting with your default gateway. If it stops at a certain hop, that might indicate the point of failure.

Troubleshooting Common Issues:

  1. "Destination Host Unreachable" or "Network Unreachable" when pinging gateway:
    • Incorrect Gateway IP: Double-check the IP address of your default gateway. Even a single typo will prevent communication.
    • Incorrect Subnet Mask: Ensure your system's IP address and subnet mask are correct and consistent with your network segment. If your system thinks the gateway is on a different subnet, it won't try to send packets to it directly.
    • Physical Connectivity: Check network cables. For Wi-Fi, ensure you're connected to the correct network.
    • Gateway Offline: The router itself might be turned off, rebooting, or malfunctioning. Check the router's status.
  2. Can ping gateway but not external IP addresses:
    • Gateway Configuration: The issue likely lies with the gateway (router) itself, not your Ubuntu system's configuration. The gateway might not have internet access, or its firewall might be blocking outbound traffic.
    • ISP Issues: Your Internet Service Provider might be experiencing an outage.
    • Incorrect Default Route on Gateway: The router's own routing table might be misconfigured. (This is usually outside the scope of configuring your Ubuntu machine).
  3. Can ping external IP but not domain names:
    • DNS Configuration: This is almost always a DNS issue. Verify the DNS server addresses configured in your Netplan file (under nameservers) or in NetworkManager (under ipv4.dns).
    • DNS Server Unreachable: The DNS servers you've configured might be offline or unreachable from your network. Try using well-known public DNS servers like 8.8.8.8 or 1.1.1.1 as a test.
    • Firewall Blocking DNS: Your local firewall (UFW) might be blocking outbound DNS queries on port 53 (UDP/TCP).
  4. Changes Lost After Reboot:
    • This indicates that you made temporary changes (e.g., using ip route) but did not persist them. For permanent changes, use Netplan or NetworkManager (nmcli or GUI). Double-check your Netplan YAML files for correct syntax and ensure you ran sudo netplan apply (or try and confirmed).
  5. netplan apply or netplan try Fails:
    • YAML Syntax Error: The most common cause. Netplan is very particular about indentation and syntax. Use sudo netplan generate to check for syntax errors before applying. Error messages will often point to the line number.
    • Renderer Issues: Ensure systemd-networkd (the default renderer for servers) is running. sudo systemctl status systemd-networkd.

By methodically following these verification steps and systematically addressing troubleshooting points, you can efficiently diagnose and resolve any connectivity problems that arise after changing your default gateway.

Security Considerations and Best Practices for Network Configuration

Changing your default gateway and managing network configurations are powerful operations that can significantly impact your system's connectivity and security posture. It's not just about getting the internet to work; it's about doing so securely and reliably. Ignoring security aspects can expose your system to various risks.

Security Considerations:

  1. Trustworthiness of the Gateway:
    • Man-in-the-Middle (MITM) Attacks: If you configure your system to use an untrusted or malicious device as its default gateway, all your outbound traffic will pass through that device. A malicious gateway can intercept, log, and even modify your data, leading to severe privacy breaches and potential compromise of sensitive information.
    • Rogue DHCP Servers: In an unsecured network, a rogue DHCP server could assign an attacker's machine as your default gateway. Always verify your gateway IP if you suspect something is amiss.
    • Internal Threat: In corporate environments, an insider threat could attempt to redirect traffic to their own monitoring station by manipulating default gateway settings.
  2. Network Segmentation and Access Control:
    • Changing the gateway might inadvertently place your system on a network segment with different security policies or expose it to unintended internal networks.
    • Ensure that the new gateway enforces appropriate firewall rules and access controls to protect your system from external threats.
  3. Denial of Service (DoS) Risk:
    • An incorrectly configured gateway can lead to network isolation, effectively performing a self-inflicted DoS on your system. While not a direct security attack, it disrupts services and could be exploited by attackers if critical services become unreachable.
  4. Configuration File Security:
    • Netplan .yaml files and other network configuration files contain sensitive information about your network topology. These files should have restricted permissions (-rw-r----- or 640) to prevent unauthorized users from viewing or modifying them. Always use sudo for editing and understand that a compromised root account can modify these settings.

Best Practices for Secure and Reliable Network Configuration:

  1. Always Verify Gateway IP: Before and after making changes, confirm the IP address of your intended default gateway. If you're unsure, consult your network administrator or router documentation.
  2. Use Strong Passwords for Routers/Gateways: Secure the administration interface of your physical router with strong, unique passwords to prevent unauthorized changes to its configuration.
  3. Firewall Configuration: Ensure your Ubuntu system's firewall (e.g., UFW - Uncomplicated Firewall) is correctly configured to allow necessary traffic while blocking unwanted connections. A new gateway might mean new network rules are required.
  4. Principle of Least Privilege: When configuring network services, ensure they only have the necessary permissions and access to the network resources they require.
  5. Backup Network Configurations: Before making any persistent changes, always back up your existing Netplan files or NetworkManager profiles. This is your safety net for quick recovery. bash sudo cp /etc/netplan/01-netcfg.yaml /etc/netplan/01-netcfg.yaml.bak
  6. Test Changes Safely:
    • On remote servers, always use sudo netplan try (if using Netplan) to benefit from the automatic rollback mechanism.
    • Test changes during off-peak hours to minimize disruption.
    • If possible, test configurations in a staging or development environment before deploying to production.
  7. Document Your Network: Maintain clear and up-to-date documentation of your network topology, IP address assignments, default gateways, and other critical network settings. This is invaluable for troubleshooting and for new team members.
  8. Regularly Review Configurations: Periodically review your network configurations to ensure they still meet security and operational requirements. Network environments evolve, and old configurations might introduce vulnerabilities.
  9. Monitor Network Traffic: Implement network monitoring tools to detect unusual traffic patterns or unauthorized attempts to alter network configurations or redirect traffic.
  10. Keep System Updated: Regularly update your Ubuntu system and its network-related packages to patch known vulnerabilities that could be exploited to manipulate network settings.

By integrating these security considerations and best practices into your network configuration workflow, you not only ensure that your default gateway changes are effective but also that your Ubuntu system remains robust, secure, and resilient against potential threats. The default gateway is a critical chokepoint for network traffic, and its secure management is paramount to overall system security.

Conclusion

Changing the default gateway on Ubuntu 20.04, while seemingly a straightforward task, touches upon fundamental aspects of network configuration and requires a meticulous approach to ensure seamless connectivity and system stability. Throughout this comprehensive guide, we've explored various methods, ranging from temporary command-line adjustments to persistent configurations via Netplan and NetworkManager, alongside a practical walkthrough of the graphical user interface.

We began by demystifying the concept of a default gateway, emphasizing its role as the primary exit point for external network traffic and detailing the various scenarios that necessitate its modification – from routine router replacements to advanced network reconfigurations. Understanding these "why" factors is just as crucial as grasping the "how-to."

Our journey then progressed through the practical steps: * Temporary changes with the ip command provide flexibility for troubleshooting and quick tests, ideal for on-the-fly adjustments that don't need to survive a reboot. * Persistent changes with Netplan represent the official and most robust method for Ubuntu servers, leveraging YAML configuration files to ensure settings endure across reboots. This method, while requiring attention to syntax, offers granular control and integrates deeply with the system's network renderer. We also briefly touched upon how this foundational routing, crucial for all network communication, sets the stage for more specialized network functions, like those handled by an advanced AI gateway and API management platform such as APIPark. APIPark, an open-source solution, specializes in managing the complexities of AI and REST service integration, demonstrating how different types of "gateways" cater to varying layers of network and application interaction. * Persistent changes with nmcli offer a command-line alternative for systems running NetworkManager, providing a dynamic yet persistent way to manage connections and their associated gateway settings. * Finally, the Graphical User Interface (GUI) method offers an accessible and intuitive approach for desktop users, abstracting the command-line intricacies into a user-friendly visual experience.

Beyond the configuration steps, we underscored the importance of verification using tools like ip route show and ping, and provided a structured approach to troubleshooting common network issues. We meticulously covered crucial aspects of security considerations and best practices, highlighting the need for trustworthy gateways, secure configuration files, comprehensive backups, and vigilant network monitoring. These practices are not mere recommendations but essential safeguards against connectivity disruptions and potential security vulnerabilities.

By mastering these techniques, you are not just learning to change an IP address; you are gaining a deeper understanding of how your Ubuntu system interacts with the broader network. This knowledge empowers you to confidently manage your network environment, troubleshoot issues effectively, and maintain a secure and reliable connection, regardless of whether you are administering a critical server or optimizing your personal workstation. The default gateway remains a cornerstone of network connectivity, and your proficiency in its management is a testament to your command over your Ubuntu system.


Frequently Asked Questions (FAQs)

1. What is the difference between a temporary and persistent gateway change?

A temporary gateway change, typically made using the ip route command, only lasts until the system is rebooted or the network service is restarted. It's useful for testing or immediate troubleshooting. A persistent gateway change, made through configuration files like Netplan YAML files or NetworkManager profiles (nmcli or GUI), ensures that the new gateway setting survives system reboots and remains active without manual intervention, making it suitable for permanent configurations.

2. My internet stopped working after changing the gateway. What should I do?

First, verify your new gateway IP address for typos. Use ip route show to confirm the default route. Try pinging your new gateway IP. If that fails, check physical cables or Wi-Fi connection. If you're using Netplan, try sudo netplan try if you haven't confirmed, or revert to your backup Netplan file (sudo cp /etc/netplan/01-netcfg.yaml.bak /etc/netplan/01-netcfg.yaml followed by sudo netplan apply). If you're on a remote server, ensure you have console access or a fallback plan before making changes. If pinging the gateway works but external IPs don't, the issue might be with the gateway itself or your ISP. If external IPs work but domain names don't, check your DNS server configuration.

3. Why is Netplan used in Ubuntu 20.04 instead of ifconfig or /etc/network/interfaces?

Ubuntu 20.04, like several recent versions, uses Netplan as a high-level network configuration tool to simplify and standardize network setup. Netplan uses YAML files to define network configurations, which are then rendered by backend tools like systemd-networkd or NetworkManager. This approach offers a consistent syntax across different underlying technologies and allows for more complex configurations to be managed cleanly. The older ifconfig command is deprecated in favor of the ip command, and /etc/network/interfaces is generally replaced by Netplan, especially in server environments.

4. Can I have multiple default gateways on Ubuntu?

In a standard routing scenario, a system typically has only one default gateway. This is because the "default" route is a catch-all, and having multiple "catch-all" routes creates ambiguity for the operating system, leading to unpredictable routing behavior. However, you can configure multiple specific routes for different destination networks, each pointing to a different gateway. This is common in more complex network setups where traffic for certain internal networks is routed through a specific internal router, while all other internet-bound traffic goes through the primary default gateway. Tools like Netplan allow for defining such specific routes alongside a single default route.

5. What are the common IP and network settings I need to know besides the gateway?

Beyond the default gateway, you'll typically need to configure or be aware of the following essential network settings: * IP Address: Your device's unique identifier on the network. * Subnet Mask (or Netmask/CIDR): Defines the range of IP addresses within your local network segment. (e.g., 255.255.255.0 or /24). * DNS Servers: IP addresses of servers that translate human-readable domain names (like google.com) into IP addresses. Without DNS, you can't browse websites by name. * Network Interface Name: The identifier for your network adapter (e.g., enp0s3, eth0, wlan0). * DHCP (Dynamic Host Configuration Protocol): A protocol that automatically assigns IP addresses, subnet masks, gateways, and DNS servers to devices on a network. If not using DHCP, you'll be using a "Static IP" configuration.

πŸš€You can securely and efficiently call the OpenAI API on APIPark in just two steps:

Step 1: Deploy the APIPark AI gateway in 5 minutes.

APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.

curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh
APIPark Command Installation Process

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

APIPark System Interface 01

Step 2: Call the OpenAI API.

APIPark System Interface 02
Article Summary Image