How-To Geek

How to set the default gateway in linux.

What's a gateway even for?

Quick Links

The default gateway, configuring the default gateway, discovering the default gateway, removing the default gateway, adding a default gateway, making routing changes persistent, you might not change it often.

Access to the internet---or any other network---is governed by the default gateway. We explain what a default gateway is, and how to set and change it on your Linux computer .

All of the devices in your home that are connected to the internet such as laptops, desktop computers, cell phones, tablets, and smart devices are actually connected to your local area network (LAN) .

Because they're on the same network, these devices can talk to one another if they need to. Most are happy to do their own thing and operate in isolation but if you have a printer , for example, or a network-attached storage device , then some of your other devices will want to be able to connect to them.

All of your network-enabled appliances connect to your router over Wi-Fi or via a network cable . Your router is the traffic controller for your network. It directs network traffic from device to device. The traffic from each device goes to the router, the router determines which device the data is going to, and sends it on to the target device.

Related: How Does the Internet Work?

Your router is the only part of your network that is actually connected to the internet . Everything else talks to your router and the router brokers connections out to the internet. Responses from internet-based services such as mail servers or websites are received by the router. It then forwards them to the appropriate device inside your network.

So, as well as directing traffic around your network, your router also controls the data flow to and from the internet. It's a traffic controller and it's a gateway to other networks. For most people, the only other network they're concerned with is the internet.

The device that is sending traffic is called the originating device. On larger networks, the originating device decides which router to use. If it doesn't specify a preference---or if there is only one router---the default gateway is used. On most home networks, there is usually a single router containing one gateway.

Normally, the gateway is configured when your operating system is installed. Sometimes you might take ownership of a computer that has been used on a different network that you need to reconfigure the gateway on, or you might have a need to point a particular machine to a different gateway. Perhaps you have a network with different sub-networks and you have a gateway acting as an intermediary.

Related: How to Use the ip Command on Linux

The preferred method of working with routes in Linux is via the ip command . Other commands such as

are considered deprecated.

With the ip command you can find out what the default gateway setting is, and you can add or delete default gateways.

To see the routes configured on a Linux computer use the ip command with the route object. You can add the

option, but as

is the default action it can be omitted. And to further save keystrokes, "r" can be used instead of the word "route".

ip route list

One of the routes will have the word "default" in it. That's the default route to the default gateway.

Sometimes routes can be added and removed automatically. Using the ip r command on the same computer produces a different result when we've opened a VPN connection. That creates a private tunnel for that network traffic.

We can see the new entry has a "dev" device name of "tun0", meaning tunnel zero.

If you have many routes set up, it can be easier to extract the default route using grep .

ip r | grep default

Related: What Is a VPN Tunnel, and How Does It Work?

Actually, what we're doing is removing the route that guides traffic to the default gateway. We can use the ip command with the route object and the delete option. To make changes to the routing table we need to use sudo . We'll delete the default route and then list the routes.

sudo ip route delete default

The default gateway entry has been removed.

To add a default gateway we use the add option with the route object.

We're going to add a route called "default" that directs traffic to the router at 192.168.1.1, and we're going to send that traffic through network interface "enp0s3."

sudo ip route add default via 192.168.1.1 dev enp0s3

The changes we've made so far take instant effect, but they don't survive a reboot of the computer . To make your changes permanent requires modifying some configuration files. The techniques differ from Linux distro to Linux distro.

In Ubuntu , you can use the netplan command and configuration file.

sudo gedit /etc/netplan/01-network-manager-all.yaml

Add the text starting at "ethernets" to the configuration file. Note that whitespace is important. Make sure each successive level of indentation is two spaces, and take care to include the hyphen " - " in the "- to:" line. This will set a default route to the router at 192.168.1.1. Replace this with the IP address for your network .

Save the file and close your editor.

To apply the changes, use the netplan command with the apply option:

sudo netplan apply

Being silently returned to the command line means the changes were accepted. If you want to test the changes before they are applied, use the netplan command with the try option.

sudo netplan try

This gives you time to test your changes. Press the "Enter" key to commit the changes. If you don't press the "Enter" key within two minutes the process will time out and your edits will not have been applied. They're still in the config file, but they haven't been applied to your network settings.

In Fedora , we need to edit the "/etc/sysconfig/network" file, and either add or edit the "GATEWAY=" line.

sudo gedit /etc/sysconf/networks

The file might be empty or it might contain other settings. Either find and edit the "GATEWAY=" line or add it. Substitute the IP address for the one that is correct for your network.

Save the file and close the editor.

With Manjaro we need to edit or create a file named after the network interface you're setting the default gateway for. The file has an extension of ".network", and the filename is the same as the network interface.

First, we need to stop the network manager daemon:

sudo systemctl stop NetworkManager.service

We can find the name of the interface using the ip addr command:

Our interface name is "enp0s3".

We'll need to use this in the next command.

sudo gedit /etc/systemd/network/enp0s3.network

There may already be entries in the file, or it might be completely empty. Make sure these two lines appear in the file. Substitute the IP address of the gateway and the name of the network interface to suit your computer and network.

Save the file and close the editor, and then restart the network manager daemon.

sudo systemctl start NetworkManager.service

But when you need to you'll find it is easy. Making the changes persistent across reboots is slightly more involved, but still not too difficult.

Related: How to Find Your Router's IP Address on Any Computer, Smartphone, or Tablet

Set static IP in Ubuntu using Terminal

Everything you need to know about setting static IP on an Ubuntu machine using the command line.

Dec 5, 2022 — Pratham Patel

Normally, the router's DHCP server handles assigning the IP address to every device on the network, including your computer.

The DHCP server may also give you a new IP address occasionally. This could cause a problem if you have a home lab or server setup that works on a fixed IP address.

You need to set a static IP address on your Ubuntu system to avoid problems.

Step 1: Identify the correct network interface

The first step is always to know the name of your network interface.

"But why?" you might ask. That is because since Ubuntu 20.04, the network interfaces are named using predictable network interface names . This means your one and only ethernet interface will not be named 'eth0'.

Ubuntu Server and Ubuntu Desktop use different renderers for 'netplan', they are 'systemd-networkd' and 'NetworkManager', respectively. So let's go over their differences.

Ubuntu Server

To see available network interfaces on Ubuntu Server, run the following command:

Doing so will show a similar result:

The output enumerates network interfaces with numbers.

From this, I can see that the ethernet interface is 'enp1s0'.

Ubuntu Desktop

The advantage (at least in my opinion) of having Ubuntu Desktop is having NetworkManager as the renderer for netplan .

It has a pretty CLI output :)

Run the following command to view the available network interfaces:

That will give you the device name, type, state and connection status.

Here is what it looks like on my computer:

This is more readable at first glance. I can make out that my ethernet interface is named 'enp1s0'.

how to change ip address and gateway in ubuntu

Step 2: See current IP address

Now that you know which interface needs to be addressed, let us edit a file .

Before I change my IP address/set a static one, let us first see what my current IP address is .

Nice! But let's change it to '192.168.122.128' for demonstration purposes.

Step 3: See the gateway

A gateway is a device that connects different networks (basically what your all-in-one router is). To know the address of your gateway, run the following command:

The gateway address will be on the line that begins with "default via".

Below is the output of running the ip command on my computer:

On the line that starts with "default via", I can see that my gateway address '192.168.122.1'

Make a note of your gateway address.

Step 4: Set static IP address

Now that you have detail like interface name and gateway address, it is time to edit a config file.

Step 4-A: Disable cloud-init if present

The easiest way to know if cloud-init is present or not is to check if there is a package with that name.

Run the following command to check:

If you get an outupt, you have 'cloud-init' installed.

Now, to disable could-init, create a new file inside the /etc/cloud/cloud.cfg.d directory. The name does not matter, so I will call it '99-disable-cloud-init.cfg'.

Add the following line to it:

Please reboot your Ubuntu system now so that cloud-init does not interfere when we set our static IP address in the next step. :)

Back to Step 4

Once the 'cloud-init' related configuration is complete, we must now edit the netplan configuration to add our static IP address.

Go to the /etc/netplan directory. It is better if there is one file (easier to know which one to edit), but in some cases, there might also be more than one file with the extension '.yml' or '.yaml'.

When in doubt, grep for the name of your network interface. Use the following command if you are not comfortable with grep:

Since the name of network interface for my ethernet is 'enp1s0', I will run the following command:

running this command shows that the file I am looking for is '00-installer-config.yaml'. So let us take a look at it.

You might have noticed a line that says 'ethernet' and our network interface name under that. Under this is where we configure our 'enp1s0' network interface.

Since we do not want DHCP assigned IP address, let us change that field from true to no .

Add a field called addresses . Write the IP address you wish to assign your computer along with the network prefix. So I will write 192.168.122.128/24 in the addresses field.

Finally, we also need to specify DNS nameservers. For that, create a new field called nameservers and under that, create a field called addresses which contains the IP address for your DNS servers . I used Cloudflare's DNS servers but you can use whatever you want.

This is what my '00-installer-config.yaml' file looks like after editing it to my liking.

To apply the settings, run the following command:

This will take only a few seconds, and the IP address will be updated once it is done.

You can check the IP address using the hostname -I command.

Perfect! The IP address has now changed successfully.

how to change ip address and gateway in ubuntu

I know that it feels complicated but this is the proper procedure when you are trying to assign static IP via the command line in Ubuntu.

Let me know if you are stuck at some point or encounter any technical issues.

Pratham Patel

Fell in love with Ubuntu the first time I tried it. Been distro-hopping since 2016.

On this page

Setting a Static IP in Ubuntu – Linux IP Address Tutorial

Zaira Hira

In most network configurations, the router DHCP server assigns the IP address dynamically by default. If you want to ensure that your system IP stays the same every time, you can force it to use a static IP.

That's what we will learn in this article. We will explore two ways to set a static IP in Ubuntu.

Static IP addresses find their use in the following situations:

  • Configuring port forwarding.
  • Configuring your system as a server such as an FTP server, web server, or a media server.

Pre-requisites:

To follow this tutorial you will need the following:

  • Ubuntu installation, preferably with a GUI.
  • sudo rights as we will be modifying system configuration files.

How to Set a Static IP Using the Command Line

In this section, we will explore all the steps in detail needed to configure a static IP.

Step 1: Launch the terminal

You can launch the terminal using the shortcut Ctrl+ Shift+t .

Step 2: Note information about the current network

We will need our current network details such as the current assigned IP, subnet mask, and the network adapter name so that we can apply the necessary changes in the configurations.

Use the command below to find details of the available adapters and the respective IP information.

The output will look something like this:

image-14

For my network, the current adapter is eth0 . It could be different for your system

  • Note the current network adapter name

As my current adapter is eth0 , the below details are relevant.

It is worth noting that the current IP 172.23.199.129 is dynamically assigned. It has 20 bits reserved for the netmask. The broadcast address is 172.23.207.255 .

  • Note the subnet

We can find the subnet mask details using the command below:

Select the output against your adapter and read it carefully.

image-15

Based on the class and subnet mask, the usable host IP range for my network is: 172.23.192.1 - 172.23.207.254 .

Subnetting is a vast topic. For more info on subnetting and your usable IP ranges, check out this article .

Step 3: Make configuration changes

Netplan is the default network management tool for the latest Ubuntu versions. Configuration files for Netplan are written using YAML and end with the extension .yaml .

Note: Be careful about spaces in the configuration file as they are part of the syntax. Without proper indentation, the file won't be read properly.

  • Go to the netplan directory located at /etc/netplan .

ls into the /etc/netplan directory.

If you do not see any files, you can create one. The name could be anything, but by convention, it should start with a number like 01- and end with .yaml . The number sets the priority if you have more than one configuration file.

I'll create a file named 01-network-manager-all.yaml .

Let's add these lines to the file. We'll build the file step by step.

The top-level node in a Netplan configuration file is a network: mapping that contains version: 2 (means that it is using network definition version 2).

Next, we'll add a renderer, that controls the overall network. The renderer is systemd-networkd by default, but we'll set it to NetworkManager .

Now, our file looks like this:

Next, we'll add ethernets and refer to the network adapter name we looked for earlier in step#2. Other device types supported are modems: , wifis: , or bridges: .

As we are setting a static IP and we do not want to dynamically assign an IP to this network adapter, we'll set dhcp4 to no .

Now we'll specify the specific static IP we noted in step #2 depending on our subnet and the usable IP range. It was 172.23.207.254 .

Next, we'll specify the gateway, which is the router or network device that assigns the IP addresses. Mine is on 192.168.1.1 .

Next, we'll define nameservers . This is where you define a DNS server or a second DNS server. Here the first value is   8.8.8.8 which is Google's primary DNS server and the second value is 8.8.8.4 which is Google's secondary DNS server. These values can vary depending on your requirements.

Step 4: Apply and test the changes

We can test the changes first before permanently applying them using this command:

If there are no errors, it will ask if you want to apply these settings.

Now, finally, test the changes with the command ip a and you'll see that the static IP has been applied.

image-17

How to Set a Static IP Using the GUI

It is very easy to set a static IP through the Ubuntu GUI/ Desktop. Here are the steps:

  • Search for settings .
  • Click on either Network or Wi-Fi tab, depending on the interface you would like to modify.
  • To open the interface settings, click on the gear icon next to the interface name.
  • Select “Manual” in the IPV4 tab and enter your static IP address, Netmask and Gateway.
  • Click on the Apply button.

image-16

  • Verify by using the command ip a

image-18

In this article, we covered two methods to set the static IP in Ubuntu. I hope you found the article useful.

What’s your favorite thing you learned from this tutorial? Let me know on Twitter !

You can read my other posts here .

I am a DevOps Consultant and writer at FreeCodeCamp. I aim to provide easy and to-the-point content for Techies!

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

It's FOSS

How to Assign Static IP Address on Ubuntu Linux

Dimitrios

Brief: In this tutorial, you’ll learn how to assign static IP address on Ubuntu and other Linux distributions. Both command line and GUI methods have been discussed.

IP addresses on Linux Systems in most cases are assigned by Dynamic Host Configuration Protocol (DHCP) servers. IP addresses assigned this way are dynamic which means that the IP address might change when you restart your Ubuntu system . It’s not necessary but it may happen.

Dynamic IP is not an issue for normal desktop Linux users in most cases . It could become an issue if you have employed some special kind of networking between your computers.

For example, you can share your keyboard and mouse between Ubuntu and Raspberry Pi . The configuration uses IP addresses of both system. If the IP address changes dynamically, then your setup won’t work.

Another use case is with servers or remotely administered desktops. It is easier to set static addresses on those systems for connection stability and consistency between the users and applications.

In this tutorial, I’ll show you how to set up static IP address on Ubuntu based Linux distributions. Let me show you the command line way first and then I’ll show the graphical way of doing it on desktop.

Method 1: Assign static IP in Ubuntu using command line

Static IP set up Ubuntu

Note for desktop users : Use static IP only when you need it. Automatic IP saves you a lot of headache in handling network configuration.

Step 1: Get the name of network interface and the default gateway

The first thing you need to know is the name of the network interface for which you have to set up the static IP.

You can either use ip command or the network manager CLI like this:

In my case, it shows my Ethernet (wired) network is called enp0s25:

Next, you should note the default gateway IP using the Linux command ip route :

As you can guess, the default gateway is 192.168.31.1 for me.

Step 2: Locate Netplan configuration

Ubuntu 18.04 LTS and later versions use Netplan for managing the network configuration. Netplan configuration are driven by .yaml files located in /etc/netplan directory.

By default, you should see a .yaml file named something like 01-network-manager-all.yaml, 50-cloud-init.yaml, 01-netcfg.yaml.

Whatever maybe the name, its content should look like this:

You need to edit this file for using static IP.

Step 3: Edit Netplan configuration for assigning static IP

Just for the sake of it, make a backup of your yaml file.

Please make sure to use the correct yaml file name in the commands from here onward.

Use nano editor with sudo to open the yaml file like this:

Please note that yaml files use spaces for indentation . If you use tab or incorrect indention, your changes won’t be saved.

You should edit the file and make it look like this by providing the actual details of your IP address, gateway, interface name etc.

In the above file, I have set the static IP to 192.168.31.16.

Save the file and apply the changes with this command:

You can verify it by displaying your ip address in the terminal with ‘ip a’ command.

If you don’t want to use the static IP address anymore, you can revert easily.

If you have backed up the original yaml file, you can delete the new one and use the backup one.

Otherwise, you can change the yaml file again and make it look like this:

Method 2: Switch to static IP address in Ubuntu graphically

If you are on desktop, using the graphical method is easier and faster.

Go to the settings and look for network settings. Click the gear symbol adjacent to your network connection.

Assign Static IP address in Ubuntu Linux

Next, you should go to the IPv4 tab. Under the IPv4 Method section, click on Manual.

In the Addresses section, enter the IP static IP address you want, netmask is usually 24 and you already know your gateway IP with the ip route command.

You may also change the DNS server if you want. You can keep Routes section to Automatic.

Assigning static IP in Ubuntu Linux

Once everything is done, click on Apply button. See, how easy it is to set a static IP address graphically.

If you haven’t read my previous article on how to change MAC Address , you may want to read in conjunction with this one.

More networking related articles will be rolling out, let me know your thoughts at the comments below and stay connected to our social media.

Dimitrios is an MSc Mechanical Engineer but a Linux enthusiast in heart. His machines are powered by Arch Linux but curiosity drives him to constantly test other distros. Challenge is part of his per

Meet DebianDog - Puppy sized Debian Linux

Reduce computer eye strain with this nifty tool in linux, install open source dj software mixxx version 2.0 in ubuntu, install adobe lightroom alternative rawtherapee in ubuntu linux, complete guide to installing linux on chromebook, become a better linux user.

With the FOSS Weekly Newsletter, you learn useful Linux tips, discover applications, explore new distros and stay updated with the latest from Linux world

It's FOSS

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to It's FOSS.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

How to Configure Static IP Address on Ubuntu 22.04 LTS and 22.10

Switching from dynamic IP allocation to static IP addresses is easy on Ubuntu 22.04 "Jammy Jellyfish" and 22.10.

The IP addresses of most devices today are generated by Dynamic Host Configuration Protocol (DHCP) servers. A DHCP server assigns a dynamic IP address to your device when it's connected to a network. Thus, you have the chance to change this IP address from time to time.

On the other hand, a static IP refers to a fixed, immutable address, different from dynamic IPs. You can set static IP settings for Ubuntu 22.04 LTS and 22.10 in three different ways. Here's how to get started.

Understanding IP Configuration in Ubuntu

Ubuntu's progression in network management has made configuring settings like the static IP more user-friendly. The feature to set a static IP in Ubuntu 22.04, in particular, has advantages in terms of network efficiency and stability.

Unlike dynamic IPs, which might vary over sessions, a static IP in Ubuntu remains consistent. This is especially advantageous for servers where consistent address recognition is paramount. For these servers, static IP configurations can become a necessity.

While the graphical interface offers a more intuitive way to handle IP configurations, using the static IP command line can offer more precision. For users who want granular control over their network configurations, command-line methods are a preferred choice. By mastering this method, users can ensure optimal Ubuntu IP configuration for their needs.

However, the benefits of a static IP in Ubuntu, especially in the 22.04 version, come with responsibilities. Ensuring that these IPs are correctly set up is crucial, as misconfigurations can lead to network vulnerabilities.

So follow the steps below to configure a static IP address on your Ubuntu machine correctly.

Set a Static IP on Ubuntu With the nmcli Command

It's pretty easy to configure Ubuntu 22.04 static IP settings using the nmcli command . nmcli is a text-based utility used to check the status of the wired connections you are using on your device.

With this command, you can access additional networking information such as your connection status, the name of your host device, and general permissions in your network configuration. If you're aiming to set a static IP on an Ubuntu server, this command proves invaluable.

You can get information about your connection with:

The output of this command will be as follows:

Create a static link with the command given below. Then, manually configure the enp0s3 and ipv4 settings with the appropriate parameters in the nmcli command:

If you use the nmcli connection show command again, you can see that the static link has been added.

After this process, add the static connection you created to the DNS IP:

Now use the command below to activate the connection:

If the output displays "connection successfully activated," you've successfully set up a static IP address on your machine.

You can consider using static IP addresses to avoid connection problems caused by dynamic IP addresses. A static IP address allows you to have a fixed identity and location when connected to the internet.

You can verify the static IP you want to assign to your device by running:

Using netplan for Static IP Settings on Ubuntu

Just like nmcli, another command you can use for setting a static IP on Ubuntu is netplan. You can easily make Ubuntu static IP settings using the netplan command in 22.04 LTS and 22.10 versions. To do this, follow the steps below.

First, find out the name of your network interface using:

What you see here is your network interface name. This name may be different on each device.

Now, create a file named 01-netcfg.yaml in the /etc/netplan folder. Edit it with your favorite text editor.

Add the following lines to the file:

As you can see, you have disabled the DHCP IP setting with the dhcp4: no statement. You've then added the IP address and DNS settings assigned by Google.

After saving this file, run the following to apply the changes:

Configure Static IP Settings on Ubuntu Graphically

The graphical network interface in Ubuntu 22.04 is quite useful if you don't want to use the command line. So much so that you can easily set the Ubuntu static IP address using this interface.

To do this, click on the Network icon in the upper right corner of your desktop. Then, select Wired Settings from the drop-down menu. Click on the Gear icon to open the settings window.

Then, switch to the IPv4 tab in the window that opens.

As you can see, DHCP is enabled by default. Change the IPv4 Method to Manual as you want to use a static IP instead of a dynamic one. Next, change your address, netmask, and gateway settings. Finally, modify your DNS setting and click the Apply button.

You must restart this wired connection for all these actions to take effect. To do this, simply toggle the switch next to the network name on and then off.

Why Should You Use Static IP Addresses on Ubuntu?

You've now understood how to configure a static IP in Ubuntu, especially in the "Jammy Jellyfish" 22.04 LTS version and 22.10, using both graphical and command-line methods with nmcli and netplan.

Due to insufficient IP addresses, some service providers may assign the same address to two different users. In this case, connection problems can occur. Using static IP addresses instead does not cause such problems as it is user-specific, but beware as someone can misuse your IP address in several ways.

How to Configure Static IP Address on Ubuntu 24.04 (Desktop)

In this article, we will show you how to configure static ip address on Ubuntu 24.04 desktop step by step.

When you want a persistent IP address on your Ubuntu 24.04 desktop, then you must a configure a static IP address. Whenever we install Ubuntu then DHCP is enabled by default, and it will try to fetch the IP address from DHCP server if it is available over the network.

In Ubuntu Desktop 24.04, there are two ways to configure static IP address:

  • Graphical User Interface
  • Command Line

We will cover both the methods in this article.

Prerequisites

  • Pre-Install Ubuntu 24.04
  • Regular user with sudo rights
  • Basic understanding of networks

Configure Static IP Address on Ubuntu 24.04 Using GUI

Login to your desktop, click on the network icon and then choose Wired option as shown below:

Wired-Network-Settings-Ubuntu-24-04

We will get the following window, click on “ gearbox” icon

Gearbox-Icon-Ubuntu-24-04-Network-WiredSettings

Go to IPv4 tab, there you will see that DHCP is enabled for automatic IP allocation.

Automatic-DHCP-Option-Ubuntu-24-04-Network-Settings-GUI

Choose Manual option to configure static IP address and specify IP details (IP address, netmask, gateway and DNS IP) as show below:

Note: Change the IP details that suits to your network

Configure Static IP Address On Ubuntu 24.04

Click on Apply .

Next, disable and enable the interface to make above changes into effect.

Above screen confirms that we have successfully configured static IP address on our Ubuntu 24.04 desktop.

Configure Static IP Address on Ubuntu 24.04 Using Command Line

We can use netplan utility and its configuration file to assign the static ip on the interface (like ep0s3 or eth0).

Netplan configuration file are placed in /etc/netplan directory. Under this directory there should be a file with name 01-netcfg.yaml , 50-cloud-init.yaml or may be else depending on your environment.

Netplan-Configuration-file-Ubuntu-24-04-Desktop

Edit netplan configuration file, in our case it is 01-netcfg.yaml

save and close the file.

Note: In above file, replace the IP address details and interface according to your setup. We have also used renderer as “ NetworkManager ” which instructs netplan to use NetworkManager as its backend. It is used for desktops and for the servers and headless environments use “ networkd ” instead of NetworkManager.

Configure Static IP Address On Ubuntu 24.04 Command Line

Set the permission on this file using chmod command,

To make above changes into the affect, run below netplan apply command.

Next, verify the IP address and network connectivity.

Verify-IP-Details-Ubuntu-24-04-Desktop

Perfect, output above shows that we have successfully configure static ip address using netplan utility.

That’s all from this article. We hope you have found it informative and useful, feel free to post your queries and feedback in below comments section.

Read Also : How to Install Git on Ubuntu 24.04

Leave a Comment Cancel reply

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How can I find the default gateway of a machine?

I'm trying to find the default Gateway of a machine, but I see multiple interfaces.

Also, when I find my IP address from the below website, it gives me a different IP address. I thought the default Gateway and external IP would be the same? Correct me if I'm wrong.

Dan's user avatar

3 Answers 3

destination 0.0.0.0 and genmask 0.0.0.0 matches any other packet which is not defined in routing tables (last way out), so your default gateway is: 10.0.2.2 .

You can also use:

I thought the default Gateway and external ip will be same.

Not true, for example you can forward your traffic to your router with an internal IP address but your the router will replace the source address with its own public IP (NAT).

Ravexina's user avatar

  • 5 Or to get just the IP: ip route | awk '/default/ {print $3; exit}' –  Pablo Bianchi Sep 27, 2020 at 8:02
  • To find out the default ipv6 gateway (or gateway6), use this command ip -6 r | grep ^def –  user585571 Aug 19, 2021 at 11:59
  • ip r did it for me. Thanks! –  ttt Oct 23, 2021 at 22:06

1st Method:

ip route show or ip route or ip r

enter image description here

You will get some rows , the row where it says 'default' is the row that gives you information on default router ip.

To narrow down the result and finding/displaying only 'default' row you can filter it like this.

ip r | grep ^def

enter image description here

2nd Method:

enter image description here

Under Gateway column you can see your desired gateway ip.

3rd Method:

netstat -rn

enter image description here

Same as above, you can find your gateway ip under Gateway column.

Result: In my case, Gateway ip address is 192.168.0.1

Shamsail's user avatar

The easiest way is to pull down the network menu and select Connection Information and look at the gateway address there.

Otherwise, in terminal you can type netstat -rn and the first line which says default is where you'll see the gateway address.

heynnema's user avatar

  • netstat -r does not give default gateway address .. netstat -rn does –  Shamsail Jun 11, 2021 at 6:45

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged networking ..

  • The Overflow Blog
  • Reshaping the future of API platforms
  • Between hyper-focus and burnout: Developing with ADHD
  • Featured on Meta
  • Our Partnership with OpenAI
  • Imgur image URL migration: Coming soon to a Stack Exchange site near you!

Hot Network Questions

  • Windows War Strategy Game
  • Are there large-range variable capacitors?
  • Stress pattern in "Little Red Riding Hood"
  • If the Earth stopped spinning, what's the ideal point for it to stop to ensure the most people survive?
  • How realistic is a communist hardboiled detective?
  • Is there any explanation or discussion regarding the change in the Bard class from its AD&D1ed orignal implementation?
  • Why do the Trisolarans have to come to Earth and not any other planet?
  • Morphisms in the category of elements
  • Meaning of gold border around Steam achievement
  • Interpretation of "right" and "left"
  • Origin and grammaticality of "I like me ..."
  • How to make this kind of list 1., 1.1, 1.1.1, ... and 1.2, 1.2.1, 1.2.1.1, ...?
  • What is the difference between a model and an interpretation in logic?
  • Would you correct grading mistakes downwards if there is a mistake in grading?
  • Quickest return from stable Earth orbit to ground?
  • What is an argument (in philosophy)?
  • Java interpreter
  • Advice on designing an inconsistent magic system
  • When to use ascensions in Cookie Clicker
  • Double numbers on all matching lines containing text pattern
  • Got roped into (what I’m pretty sure is) a scam conference. What now?
  • Efficient C Tokenizer/Lexer in C++
  • Why is the reliability of Stormy Daniels testimony relevant in Trump's hush money process?
  • Try Triling ("Triangular-Tiling")

how to change ip address and gateway in ubuntu

how to change ip address and gateway in ubuntu

How to change the hostname on Ubuntu

I f you've ever set up a Linux distribution like Ubuntu , you may have noticed the installer prompts you to enter a name for your machine. Commonly called the hostname, it's the name that identifies your Linux system every time you connect to another device over a network or Bluetooth connection.

After reviewing all the settings, toggles, and options during the installation procedure, you may have accidentally entered the wrong hostname. But don't worry — Ubuntu lets you change your system's hostname via GUI and a variety of terminal commands .

These steps will be for Ubuntu 23.04, but should be pretty similar to other versions of Ubuntu.

Best laptops for Linux in 2024

How to change the hostname on ubuntu with the settings app.

Similar to the process on Windows 11, if you want to change the hostname of an Ubuntu system, you can just head into the Settings app. The GUI makes it easy, which is the method we suggest most people use.

  • Click on the power button and choose Settings .
  • Scroll down to About and click the arrow next to the Device Name.
  • Enter the new hostname and press the Rename button. .

You don't need to restart your system after changing the hostname. The change should take effect right away. Some apps might not see the name change, though, and if this is the case, simply reboot your PC.

How to change the hostname on Ubuntu with the terminal

More advanced Ubuntu users might want to change the hostname using the terminal. This method requires you to enter a few commands. You won't have to reboot your system, either.

  • Press Ctrl+Alt+T to open the terminal.
  • Type the command: hostnamectl set-hostname new-hostname Be sure to replace new-hostname with the actual hostname you want to use.

You won't see any results or be prompted for passwords. This is totally normal. You can confirm the hostname was indeed changed with the command hostnamectl.

How to run an Ubuntu virtual machine on Apple Silicon for free

How to change the hostname on ubuntu via configuration files.

Since Ubuntu uses the hostname and host configuration files to store the name of your PC, you can rename it by replacing the old hostname with the name you wish to give your system.

  • Inside the terminal, type the following command to open the hostname file using the nano editor: sudo nano /etc/hostname
  • Overwrite the older name with the new hostname.
  • Press Ctrl+X to exit the file. Be sure to tap Y when prompted to save the changes.
  • Open the hosts config file using this command: sudo nano /etc/hosts
  • Rename the string adjacent to the 127.0.1.1 IP address to the new hostname.
  • Hit Ctrl+X followed by Y to save and exit the hosts file.
  • (Optional) If you're running Ubuntu as a cloud instance with the help of the cloud-init utility, you'll need to modify a third config file called cloud.cfg. Simply open the file with this command and ensure the preserve_hostname string has the value true assigned to it. sudo nano /etc/cloud/cloud.cfg

After using this method, you'll need to restart your system for Ubuntu to reflect the hostname changes.

How to temporarily change the hostname on Ubuntu

If you don't want the hostname change to be permanent and just want to change for one time only, you can head into the terminal to swap names. Of course, you can check the actual hostname first, too, which we'll cover here. As a reminder, you'll have to press Enter after each command.

  • Open a terminal session.
  • To change the hostname temporarily, type the command: sudo hostname new-hostname Again, don't forget to replace new-hostname with the actual hostname you want to use.
  • Enter your password when prompted by Ubuntu.

Once you finish, you can confirm the hostname was changed with the hostname command.

What hostname did you pick for your Ubuntu PC?

Those are all the ways you can change the hostname on Ubuntu. Apart from the last method, every other procedure results in a permanent change in the hostname, though you can modify it as many times as you wish.

If you're curious about Ubuntu, be sure to check out our detailed setup guide for the OS . We also have other articles that may interest developers, such as those on configuring environment variables and installing Anaconda and AWS CLI on Ubuntu .

How to change the hostname on Ubuntu

Change the hostname of your AL2 instance

When you launch an instance into a private VPC, Amazon EC2 assigns a guest OS hostname. The type of hostname that Amazon EC2 assigns depends on your subnet settings. For more information about EC2 hostnames, see Amazon EC2 instance hostname types in the Amazon EC2 User Guide for Linux Instances .

A typical Amazon EC2 private DNS name for an EC2 instance configured to use IP-based naming with an IPv4 address looks something like this: ip-12-34-56-78.us-west-2.compute.internal , where the name consists of the internal domain, the service (in this case, compute ), the region, and a form of the private IPv4 address. Part of this hostname is displayed at the shell prompt when you log into your instance (for example, ip-12-34-56-78 ). Each time you stop and restart your Amazon EC2 instance (unless you are using an Elastic IP address), the public IPv4 address changes, and so does your public DNS name, system hostname, and shell prompt.

This information applies to Amazon Linux. For information about other distributions, see their specific documentation.

Change the system hostname

If you have a public DNS name registered for the IP address of your instance (such as webserver.mydomain.com ), you can set the system hostname so your instance identifies itself as a part of that domain. This also changes the shell prompt so that it displays the first portion of this name instead of the hostname supplied by AWS (for example, ip-12-34-56-78 ). If you do not have a public DNS name registered, you can still change the hostname, but the process is a little different.

In order for your hostname update to persist, you must verify that the preserve_hostname cloud-init setting is set to true . You can run the following command to edit or add this setting:

If the preserve_hostname setting is not listed, add the following line of text to the end of the file:

To change the system hostname to a public DNS name

Follow this procedure if you already have a public DNS name registered.

For AL2: Use the hostnamectl command to set your hostname to reflect the fully qualified domain name (such as webserver.mydomain.com ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the fully qualified domain name (such as webserver.mydomain.com ).

Reboot the instance to pick up the new hostname.

Alternatively, you can reboot using the Amazon EC2 console (on the Instances page, select the instance and choose Instance state , Reboot instance ).

Log into your instance and verify that the hostname has been updated. Your prompt should show the new hostname (up to the first ".") and the hostname command should show the fully-qualified domain name.

To change the system hostname without a public DNS name

For AL2: Use the hostnamectl command to set your hostname to reflect the desired system hostname (such as webserver ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the desired system hostname (such as webserver ).

Open the /etc/hosts file in your favorite text editor and change the entry beginning with 127.0.0.1 to match the example below, substituting your own hostname.

You can also implement more programmatic solutions, such as specifying user data to configure your instance. If your instance is part of an Auto Scaling group, you can use lifecycle hooks to define user data. For more information, see Run commands on your Linux instance at launch and Lifecycle hook for instance launch in the AWS CloudFormation User Guide .

Change the shell prompt without affecting the hostname

If you do not want to modify the hostname for your instance, but you would like to have a more useful system name (such as webserver ) displayed than the private name supplied by AWS (for example, ip-12-34-56-78 ), you can edit the shell prompt configuration files to display your system nickname instead of the hostname.

To change the shell prompt to a host nickname

Create a file in /etc/profile.d that sets the environment variable called NICKNAME to the value you want in the shell prompt. For example, to set the system nickname to webserver , run the following command.

Open the /etc/bashrc (Red Hat) or /etc/bash.bashrc (Debian/Ubuntu) file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/bashrc and /etc/bash.bashrc are owned by root .

Edit the file and change the shell prompt variable ( PS1 ) to display your nickname instead of the hostname. Find the following line that sets the shell prompt in /etc/bashrc or /etc/bash.bashrc (several surrounding lines are shown below for context; look for the line that starts with [ "$PS1" ):

Change the \h (the symbol for hostname ) in that line to the value of the NICKNAME variable.

(Optional) To set the title on shell windows to the new nickname, complete the following steps.

Create a file named /etc/sysconfig/bash-prompt-xterm .

Make the file executable using the following command.

Open the /etc/sysconfig/bash-prompt-xterm file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/sysconfig/bash-prompt-xterm is owned by root .

Add the following line to the file.

Log out and then log back in to pick up the new nickname value.

Change the hostname on other Linux distributions

The procedures on this page are intended for use with Amazon Linux only. For more information about other Linux distributions, see their specific documentation and the following articles:

How do I assign a static hostname to a private Amazon EC2 instance running RHEL 7 or Centos 7?

Warning

To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions.

Thanks for letting us know we're doing a good job!

If you've got a moment, please tell us what we did right so we can do more of it.

Thanks for letting us know this page needs work. We're sorry we let you down.

If you've got a moment, please tell us how we can make the documentation better.

  • HTTP Errors

What is HTTP Error 502 Bad Gateway & How to Troubleshoot It

' src=

  • May 9, 2024

502 Bad Gateway

Website errors can be a real test of patience. One common culprit is the 502 bad gateway error. Known for its ubiquity across the web, it doesn’t discriminate between small WordPress sites or well-known services like Gmail, Twitter, or Instagram.

You may encounter a 502 Bad Gateway error when a server upstream (i.e. one closer to the website than the client’s end) either fails to receive a valid response from another server or encounters an issue while trying to fulfill a request. Although these errors are generally related to server-side issues, in some cases, they can be triggered by problems with internet connections or website elements stored on your browser.

In this article, we will dive into the nature of a 502 Bad Gateway error and its possible triggers. We’ll also provide a systematic approach to diagnosing and fixing the error to keep your website up and running.

What is a 502 Bad Gateway error?

  • How does a 502 error differ from other 5xx errors?
  • What triggers a 502 error?

Can a 502 error impact SEO?

How to fix a 502 error.

A 502 Bad Gateway error is a server-side error that indicates one server, acting as a gateway or proxy, received an invalid response from another server upstream. This usually happens when a server (for example, a website’s host or CDN provider) is unable to forward the client’s request correctly.

Example of a 502 bad gateway error in Google Chrome. 

502 Bad Gateway errors can present in an assortment of ways. Some of the common variations include:

  • 502 Bad Gateway
  • 502 Service Temporarily Overloaded
  • HTTP Error 502 – Bad Gateway
  • 502 Proxy Error
  • 502 Server Error: The server encountered a temporary error and could not complete your request
  • Temporary Error (502)
  • 502. That’s an error

These are just a few examples of messages you might encounter with a 502 error. Many systems and website hosts even have their own custom error messages for 502.

How are 502 errors different from other 5xx errors?

To provide a clearer understanding of the differences between a 502 error and other types of server-side errors, we’ve compiled an overview of usual 5xx responses you might come across on your website.

Each of these server-side errors provides specific information that can help you diagnose the problem and find a solution accordingly.

What triggers a 502 Bad Gateway error?

A 502 Bad Gateway error can occur for various reasons, such as problems with server configurations, network issues, problematic plugins or third-party applications, or firewall setup.

These issues are known to result in a 502 error:

  • Unstable server. If the server takes too long to respond due to heavy loads or disturbances, a 502 error can occur.
  • Network problems. Internet connectivity issues or difficulties connecting to an upstream server may result in a 502 error.
  • Faulty programming. Errors in website code or configurations can often lead to a 502 error.
  • Plugin conflicts. If a plugin in WordPress is incorrectly configured, conflicts with other plugins, or is compromised by malware, this can lead to 502 errors.
  • Proxy server issues. Problems with proxy servers can result in a 502 bad gateway error.
  • Firewall configuration issues. Your firewall could be erroneously identifying threats and consequently blocking certain internet service providers or IP addresses.
  • Server software timeouts. If the server software doesn’t receive a timely response from an upstream server it refers to, this can trigger a 502 error.
  • Incorrect DNS settings. If the domain name’s DNS records are incorrectly assigned, a 502 error may arise.
  • Server capacity reached. The server may exhaust its available resources and crash, prompting a 502 error message. This could happen due to an unexpected surge in web traffic or constrained memory capacity.
  • Issues with your browser. It’s possible that there might be corrupted files within your browser cache that are causing problems.

A 502 error creates problems by displaying a bad gateway message to users when they attempt to access specific areas of a website. This typically occurs when the server, acting as a gateway or proxy, receives an invalid response from an upstream server.

Yes – a persisting 502 error can negatively influence SEO if left unresolved. If a short downtime of say, 10 minutes occurs, and frequent crawling is happening, the crawler often retrieves the page from cache. In instances where Google hasn’t yet got the opportunity to re-crawl before the site is restored, your SEO is typically unaffected.

Nevertheless, if your site experiences extended downtime, such as over 12 hours, Google might perceive the persisting 502 error as a site issue needing resolution. This could unfavorably affect your rankings over time.

If recurring 502 errors concern you, it’s crucial to understand why they’re happening in the first place. Some of the subsequent solutions provided can help to troubleshoot and fix the issue.

A 502 bad gateway error often signals a network or server problem, but it can also be due to a client-side issue. Let’s explore various ways to fix this error and get your website running again.

1. Reload the web page

This is the most straightforward method to deal with a 502 bad gateway error. If your server or host is bombarded with simultaneous requests, it might temporarily be unable to handle the load, causing the error.

Reloading the page is as simple as clicking the “ Refresh ” button on your web browser or pushing the F5 key on your keyboard (for Windows users), or Cmd + R (for Mac users). Alternatively, some users prefer doing a hard refresh, which you can perform by hitting Ctrl + F5 (Windows) or Cmd + Shift + R (Mac).

Performing a hard refresh ignores cached content and forces the browser to reload the fresh page from the server. This process might take longer but could be more effective in bypassing the error.

When you receive a 502 bad gateway error, the issue might not be with your site directly. Instead, it could be a result of server overload. By waiting a few moments and then attempting to reload your page, you give the server time to catch up with all its ongoing requests.

However, if you’re continuously encountering a 502 error even after repeated attempts at reloading, it implies a deeper issue and you may need to move on to the next troubleshooting steps.

2. Assess the site’s status

When facing a 502 error, the issue can either be localized to your device or network, or it might be that the website or server itself is down. To differentiate between the two, you can use online tools that evaluate whether a website is actually experiencing issues.

One popular tool is https://geopeeker.com/. To use this tool, copy the URL of the website you are trying to access and paste it into the search box. Then, hit Go!

This tool then checks the site from various geographical locations to determine if the website is down universally or the problem is only on your end.

There are other online tools like isitdownrightnow.com and sitecheck.sucuri.net that work in a similar manner. These tools provide insights about the website’s operational status  – and in the case of SiteCheck, may even help you identify a malware infection or security issue.

3. Access the page in incognito mode

When you use your browser in incognito or private mode, it doesn’t load your existing cookies, cached content, or run all extensions. Many times, these are elements that can cause issues with how a website is loaded. So, the 502 bad gateway error you’re experiencing may disappear in this mode.

To access incognito mode:

  • In Google Chrome and Microsoft Edge, press Ctrl+Shift+N .
  • In Mozilla Firefox and Safari, press Ctrl+Shift+P .

If loading the website in incognito mode solves the problem, then it’s likely a browser extension responsible for the error.

In such a case, you need to find out which extension is causing the problem:

  • Return to your browser’s normal mode.
  • Disable your extensions one by one. After disabling each extension, refresh the page to see if the problem still persists.
  • If the website loads without the 502 error, you’ve identified the problematic extension.

You can typically manage extensions from your browser’s settings. For example, in Google Chrome, you click More Tools -> Extensions .

4. Clear your browser cache

Clearing your browser cache is a basic but effective troubleshooting strategy. Your browser stores temporary files on your computer to help quickly load webpages. However, these files sometimes lead to conflicts, including triggering a 502 error.

The process of clearing cache varies slightly with each browser. Below is a basic breakdown of the steps needed for popular browsers:

Google Chrome:

  • Open your browser and click on the three dots in the top right-hand corner.
  • Navigate to Settings > Privacy & Security .
  • Click Clear browsing data .
  • Ensure that Cached Web Content is checked.
  • Choose the time range or select All time to clear everything, then click Clear data .

Mozilla Firefox:

  • Click on the hamburger menu (three stacked lines) in the top right-hand corner.
  • Go to Settings > Privacy & Security .
  • In the Cookies and Site Data section, click Clear Data .
  • Ensure that Cached Web Content is checked, then click Clear .
  • From the menu at the top, click Safari > Preferences .
  • Click on the Advanced tab.
  • Check the box that says Show Develop menu in menu bar .
  • From the menu bar, click Develop > Empty Caches .

Microsoft Edge:

  • Click the three horizontal dots at the top right of the browser.
  • Click Settings > Privacy, search, and services .
  • Under the Clear browsing data heading, click on Choose what to clear .
  • Check the box next to Cached images and files , then hit Clear .

You can ensure that you are not seeing a cached page on the website by reloading the URL with an appended variable like this: example.com ?nocache

5. Test the page with a different device

If your browser checks don’t indicate a problem, try switching to a different device. Sometimes, specific settings, extensions, or software on the device you’re using may cause conflict with the website you’re trying to access, leading to a 502 error.

You can choose another computer or a mobile device for this purpose. If you opt to use a mobile device, be sure to disconnect it from your Wi-Fi and use your mobile data instead. This action will bypass your usual internet connection and can sometimes solve your issue if the problem is related to your network configuration.

If using another device resolves the problem and allows you to access the website, there might be something on your original device that’s causing the interference. This could be a problematic browser extension, corrupted system files, specific security settings, or even malware.

In this case, restart your initial device and also reboot your networking equipment, like router or modem. The golden rule of tech troubleshooting is to unplug your device, wait for a few moments, and plug it in again. This simple reset can often clear up any temporary software glitch or memory issue that may be causing the problem.

6. Check for DNS problems

DNS, or Domain Name System, is what links your website’s domain name to its IP address. If there’s a problem with your DNS, this could cause a 502 error, as your domain may not be directing to the correct IP address.

There are several potential DNS issues that could cause this problem:

  • The primary issue could be that your domain isn’t resolving to the correct IP address. This could occur if there has been a recent change or error in setting up your DNS records.
  • You could be dealing with a non-responsive DNS server. The server responsible for translating your domain to the correct IP may be down or unavailable.
  • If you’ve migrated your website to a new host, there can be a delay before your updated DNS records fully propagate across the internet. This delay could be up to 24 hours in some cases – depending on your DNS records’ Time to Live (TTL) value.

To fix these issues, here are some methods you could use:

  • If you believe that your problems are due to recently changed DNS records, you may want to wait until the new records have had time to propagate.
  • You might want to check your DNS settings in your domain registrar’s panel to ensure they’re correct.
  • You could try flushing your local DNS cache – clearing old data and forcing your computer to get new, fresh data. If your computer has outdated or incorrect DNS information stored, this could cause a 502 error. In Windows, you can do this by opening Command Prompt and typing in ipconfig /flushdns . For macOS users, you can clear DNS cache by typing dscacheutil -flushcache in Terminal.
  • Lastly, you might consider temporarily changing your DNS servers. By default, these servers are set by your Internet Service Provider (ISP). But there are also public DNS servers, such as those provided by Google, which can be used. Some people even choose to use Google’s public DNS servers permanently as propagation (the updating of DNS information across the internet) can be faster.

Keep in mind that solving DNS issues can sometimes be a bit technical, and you might opt to get professional help. If you’re unsure, reaching out to your domain registrar, web host, or a knowledgeable professional can be a wise decision.

If you’re using a WAF or CDN, be sure to check that the correct Origin IP is set. This would very much mimic the effect of having the wrong DNS A record set.

7. Check with your host

A potential culprit of the 502 bad gateway error could be an issue stemming from your web hosting service. This problem often occurs when a script, query, or request is taking an excessive amount of time to execute and is subsequently canceled or killed by the server.

This scenario typically occurs with shared hosting environments, where multiple websites are hosted on the same server. To maintain site performance and prevent one site from using all the server’s resources, these hosts often implement what’s known as a “kill script”. This script terminates a request that has been running for too long to avoid it impacting other websites on the same server.

Another reason for a 502 error could be server unavailability due to a downtime or connectivity issue. In such cases, it’s recommended to check your host’s status page or raise a support ticket to understand and resolve the problem.

8. Check your CDN or Firewall

Content Delivery Networks (CDN) and firewalls are common elements in web infrastructure designed to increase speed and security. However, they can occasionally interfere, leading to a 502 bad gateway error.

A CDN is a globally distributed network of servers that provides faster delivery of your web content by serving it from the location nearest to your visitor. However, sometimes configurations or errors in a CDN can cause access issues, such as a 502 bad gateway error.

If you’re using a standalone CDN provider, try disabling it temporarily to test if it’s causing the problem. If the error doesn’t occur when the CDN is turned off, then the CDN might be at fault. You might need to delve into the CDN configurations or contact technical support for the CDN service to resolve the issue.

Similar to a CDN, a web application firewall (WAF) can also cause a 502 error. The firewall sits between the user’s network and server, examining web traffic for any malicious activity. If the firewall incorrectly blocks legitimate traffic, it might trigger a 502 error.

A firewall might also be configured to block certain types of requests that are perfectly valid for your website’s functioning. Any misconfigurations can result in a 502 error.

HTTP 502 Sucuri Firewall Error

If you’re a Sucuri Firewall user and looking to troubleshoot a 502, try a firewall bypass and attempt to load the website again. If it loads successfully but you continue to receive 502’s, then either you need to set Hostname over TLS on the WAF security panel or your hosting server needs to allow the WAF IPs. But, there could also be some other issues such as the host header being too large.

How to bypass the firewall with hosts.txt

First, you must find and copy your hosting IP address by accessing the Hosting IP Address page of the WAF dashboard.

The next steps depend on your operating system.

Microsoft Windows

Follow these instructions to modify your hosts file in Windows.

  • Press the Windows key, search for “notepad”, right-click on Notepad and select the option Run as administrator .
  • Once the Notepad is open, go to File -> Open and type c:\windows\system32\drivers\etc on the path field. The “ c:\ ” disk could be another letter, just make sure you’re accessing the primary disk of your system, which is usually where Windows was installed.

Open Notepad

  • The ‘hosts’ file won’t show right away because Notepad usually lists only text files, so you need to select “ All Files ” on the bottom of the window. Make sure you click on the ‘hosts’ file that shows as “File” on the Type column as there are two files named “hosts”.

Click on hosts file

  • At the very end of the file add a line following this structure:
  • Replace awesomewebsite.com with your domain and 208.104.52.26 with your hosting IP.
  • Save the file and exit Notepad.

Updated hosts file

  • Just like you did before to run Notepad as administrator, now search for cmd.exe on the Start Menu, right-click select the option Run as administrator .
  • Type ipconfig /flushdns on the command prompt window and press “Enter” so the changes take effect. You can close the command prompt window after.

ipconfig /flushdns in the command prompt window

macOS & Linux

Follow these instructions to modify your hosts file in Mac and Linux.

  • Open the Terminal – if you are running a distro similar to Ubuntu, press Ctlr + Alt + T . On macOS, you can search on Spotlight or find the Terminal in the Applications -> Utilities folder.
  • Type sudo nano /etc/hosts on the Terminal window and enter your password to open Nano Text Editor as root.

sudo nano /etc/hosts in the Terminal window

If you see Command ‘nano’ not found message, your Linux distribution may not have Nano Text Editor installed, therefore you can either choose a different editor such as Vim, Gedit, etc. You can also install Nano with your distribution package manager. If you are running a distro similar to Ubuntu, run the command sudo apt install nano on Terminal to install Nano Text Editor.

Setting up hosts file

  • Press “ Ctrl + X “, then “ Y ” and then “ Enter ” to confirm saving the file with the same name.

That’s it. You should now be able to view your website directly from your hosting server. Please, use the incognito mode of the browser to make sure it didn’t cache the DNS.

In other cases, hosting security software may be blocking your firewall IP addresses. To resolve this, you will need to contact your hosting provider or system administrator and ask them to allowlist the following IP addresses:

If this doesn’t resolve the issue, move on to the next step.

9. Check for large HTTP headers

In rarer cases, your application may be sending giant HTTP headers (larger than 16 KB) which cause the request to time out. To verify if this is the culprit, open your browser’s Developer Tools and inspect the size of the response headers.

The most common issue we find for large HTTP headers occurs when applications use multiple “ Set-Cookies ” headers for tracking purposes or repeatedly send the same HTTP headers.

9. Disable problematic plugins or themes

Plugins and themes are essential components of any WordPress website. They add functionality, design elements, and can enhance the user experience. However, they can also occasionally be sources of problems, causing errors such as a 502 bad gateway error. This is especially likely if the code within a plugin or theme is poorly written or outdated.

When a 502 error happens, one way to determine if it is caused by a plugin or theme is to temporarily deactivate all of them on your site. Don’t worry, you won’t lose any data by simply deactivating a plugin or theme.

If you can access your admin area, go to “ Plugins “, select all the plugins, and pick “ Deactivate ” from the bulk actions drop-down menu.

how to change ip address and gateway in ubuntu

Do the same for your themes. If this resolves the issue, the problem lies with one of your plugins or themes.

When you reactivate a plugin or theme and the 502 error reoccurs, you have found the troublesome component.

At this point, you should contact the plugin or theme developer for assistance or post a support ticket in the WordPress repository.

10. Check your logs

Log files are essential components of troubleshooting. They record events and transactions that occur while software or an operating system is running. By providing a historical record of operations, error logs are instrumental in diagnosing and rectifying issues like the 502 bad gateway error.

If you are using a hosting service that features a logging tool, use that to check for errors. If your host is not equipped with a logging tool but you have a WordPress site, you can check your error logs in Apache and NGINX.

These are usually located at the following paths:

  • Apache: /var/log/apache2/error.log
  • NGINX: /var/log/nginx/error.log

11. Check for PHP Timeout Issues

PHP timeout issues often manifest as a 502 bad gateway error. These occur when a single PHP process is running for longer than the set `max_execution_time` or `max_input_time` in the PHP configuration on your server.

For example, if you’re conducting large WordPress imports or running complex scripts, your PHP processes might exceed the maximum execution time. It might cause the server to terminate the process prematurely, resulting in a 502 bad gateway error message.

To address this, you’ll have to increase these time limits. It involves editing your PHP configuration settings.

There are a few ways to do this:

  • Edit your php.ini file: Try finding your php.ini file in your website’s root directory and adjust the max_execution_time or max_input_time values. For instance, to increase the limit to 300 seconds, you can set max_execution_time = 300 .
  • Use your .htaccess file: If you’re running on Apache, you can modify the .htaccess file in your website root directory. Add the lines ` php_value max_execution_time 300 ` and ` php_value max_input_time 300 ` to increase the time limits.

Remember, making these changes can have an impact on your server’s resources. Increasing the PHP processing time allows scripts to execute longer, potentially taking up more server resources.

After you’ve fixed the issue, you’ll still need to optimize your website to address the root cause of the problem. No website visitor wants to wait 5 minutes for a page to load (and Google won’t like it, either)!

You can consult with your hosting provider about the appropriate values suitable for your specific hosting plan.

And always remember to monitor your website’s performance after making these changes to ensure that it continues to run efficiently! If you continue facing issues, it would be best to consider optimizing your PHP code or talking to a PHP developer to address complex code issues.

Chat with Sucuri

Marc Kranat

CISM CISSP Marc Kranat is Sucuri’s Enterprise Firewall Supervisor who joined the company in 2014. Marc’s main responsibilities include providing support to high-value clients. His professional experience covers over 20 years in cyber and IS security and project management. When Marc isn’t checking firewall logs and configurations, you might find him acting as an assistant to his photographer wife, or wranging his Husky. Connect with him on Twitter .

Related Tags

  • Best Practices ,
  • Secure Development ,
  • Sucuri Firewall

Related Categories

You may also like.

HTTP Error 429

  • Security Education

What is HTTP Error 429: Too Many Requests

' src=

  • May 7, 2024

What is 503 Service Unavailable & How to Fix It

What is the 503 Service Unavailable Error & How to Fix It

  • October 18, 2022

How to fix 404 errors on a website

Error 404: How to Fix & Troubleshoot 404’s On Your Site

  • August 2, 2023

What is a 403 error and how to fix it

  • Website Security

What is HTTP Error 403 & How to Fix It

  • February 9, 2024

Sucuri Cookie Policy See our policy>>

Our website uses cookies, which help us to improve our site and enables us to deliver the best possible service and customer experience.

IMAGES

  1. How to change the IP address on Ubuntu

    how to change ip address and gateway in ubuntu

  2. Configuring static and dynamic IP Addresses in Ubuntu using Netplan

    how to change ip address and gateway in ubuntu

  3. How to change the IP address on Ubuntu

    how to change ip address and gateway in ubuntu

  4. How to change the IP address on Ubuntu

    how to change ip address and gateway in ubuntu

  5. How to Change the IP Address in Ubuntu

    how to change ip address and gateway in ubuntu

  6. How to set the default gateway on Ubuntu

    how to change ip address and gateway in ubuntu

VIDEO

  1. How to Set Static IP in Ubuntu Server 20.04. Change and configure ip adress using putty

  2. How to set a static IP Ubuntu 22.04 LTS (3 ways)

  3. Configuring IP address on an Ubuntu Server

  4. How To Change DNS (Ubuntu 14)

  5. Inseego

  6. How Check IP Address on Ubuntu Easily

COMMENTS

  1. How to Configure Static IP Address on Ubuntu 20.04

    Depending on the interface you want to modify, click either on the Network or Wi-Fi tab. To open the interface settings, click on the cog icon next to the interface name. In "IPV4" Method" tab, select "Manual" and enter your static IP address, Netmask and Gateway. Once done, click on the "Apply" button.

  2. How to Set a Static IP Address in Ubuntu

    Set a Static IP in Ubuntu with the GUI. Click the icons at the far-right end of the system bar to show the system menu, then click on the "Wired Connected" menu option. If you're using a wireless connection, instead click the name of your Wi-Fi network. The available connections are displayed.

  3. Change IP address on Ubuntu Server

    You have two options when configuring the IP address on your Ubuntu Server, and that is either a static IP address or DHCP. A static IP address allows you to manually select your IP address by configuring it on the Linux system, whereas DHCP relies on the router or DHCP server to lease you an IP address - either a reserved one or the next available one that is currently free, depending on ...

  4. How to Set the Default Gateway in Linux

    To add a default gateway we use the add option with the route object. We're going to add a route called "default" that directs traffic to the router at 192.168.1.1, and we're going to send that traffic through network interface "enp0s3." sudo ip route add default via 192.168.1.1 dev enp0s3. ip r.

  5. Set static IP in Ubuntu using Command Line

    On the line that starts with "default via", I can see that my gateway address '192.168.122.1' Make a note of your gateway address. Step 4: Set static IP address. Now that you have detail like interface name and gateway address, it is time to edit a config file. Step 4-A: Disable cloud-init if present. The easiest way to know if cloud-init is ...

  6. Configuring networks

    To configure a default gateway, you can use the ip command in the following manner. Modify the default gateway address to match your network requirements. sudo ip route add default via 10.102.66.1. You can also use the ip command to verify your default gateway configuration, as follows: ip route show.

  7. Setting a Static IP Address in Ubuntu 24.04 via the Command Line

    Configuring a static IP address on your Ubuntu server is essential for various reasons, such as ensuring consistent network configuration, facilitating server management, and improving network security. ... Adjust the IP address, subnet mask, default gateway, and DNS servers as necessary for your network. ... Change IP address on Ubuntu Server ...

  8. Ubuntu Network Configuration Guide

    First, we will cover the instructions to configure one from Ubuntu GNOME GUI. Start by opening Settings and click on Network menu and hit the gear wheel of the desired network interface. Next, click the IPv4 tab, and then the manual configuration option. Fill out your desired IP address, subnet mask, and default gateway.

  9. Setting a Static IP in Ubuntu

    Here are the steps: Search for settings. Click on either Network or Wi-Fi tab, depending on the interface you would like to modify. To open the interface settings, click on the gear icon next to the interface name. Select "Manual" in the IPV4 tab and enter your static IP address, Netmask and Gateway.

  10. Ubuntu Linux Configure Gateway / Default Routing IP Address

    How do I configure default router or gateway IP address under Ubuntu Linux / Debian Linux? How do I change default router / gateway IP under Ubuntu Linux? A. ... OpenBSD Set / Change Default Gateway; 2 comments… add one. john Aug 4, 2009 @ 5:05. Dear all,

  11. How to Assign Static IP Address on Ubuntu Linux

    Method 2: Switch to static IP address in Ubuntu graphically. If you are on desktop, using the graphical method is easier and faster. Go to the settings and look for network settings. Click the gear symbol adjacent to your network connection. Next, you should go to the IPv4 tab.

  12. How to Change IP Address in Linux

    The ip command is available on most Linux distributions. For setting an IP address, use it like this: ip addr add [ip_address] dev [interface] For example, add an IP address to the eth1 interface as: sudo ip addr add 192.168.56.21/24 dev eth1. You now have two IP addresses: one from the old configuration and one from the new command:

  13. How can I change the IP and gateway addresses permanently?

    To enable internet connection I needed to change my IP and Gateway address. I did the following as a root user. # ifconfig eth0 "my ip address here" netmask 255.255.255. up. # route add default gw " gw address here". It works fine for a couple of minutes but then goes back to the previous settings every time.

  14. networking

    Get the IP address from the server using: sudo dhclient eth0; Assign the first ip addresses like this: sudo ip addr add 192.168.20.222/24 dev eth0, and repeat for other IP addresses. Add the default route using: sudo route add default gw <internet gateway ip address> If you do step 2, step 4 is not required. Hope that helps.

  15. How to Configure Static IP Address on Ubuntu 22.04 LTS and 22.10

    A DHCP server assigns a dynamic IP address to your device when it's connected to a network. Thus, you have the chance to change this IP address from time to time. On the other hand, a static IP refers to a fixed, immutable address, different from dynamic IPs. You can set static IP settings for Ubuntu 22.04 LTS and 22.10 in three different ways.

  16. networking

    The gateway is usually an interface on a remote device which the local node is relying on for routing decisions. A route statement itself can refer to a local interface or not, but the routing destination has to be discoverable from a recursive lookup, connected interface, or default route.

  17. Setting Up Static IP Address on Ubuntu 22.04 LTS

    Method 1: Set up Static IP Address Using Command Line. Follow the instructions provided below to configure a static IP address on Ubuntu 22.04 using the command line. Step 1: Check Current IP Address. First, open up the terminal using " CTRL+ALT+T" and execute the " ip " command with " a " option to check the current IP address of ...

  18. How to Set a Static IP Address On Ubuntu 22.04

    To assign a static IP address or Wi-Fi interface, click on the gear icon on the Wi-Fi interface page and then IPv4 tab >> Manual >> Enter IP address, Netmask, Gateway, DNS (Toggle to disable Automatic DNS configuration) >> Apply. Set IP for Wired Wi-Fi. Finally, disable and enable the Wi-Fi interface to apply the IP address.

  19. Debian / Ubuntu Linux Setting a Default Gateway

    My router IP is 192.168.1.254 and I'd like to setup this as a default gateway for Debian Linux. A. You can use command line tool such as. a] ip command - show / manipulate routing, devices, policy routing and tunnels. b] route command - show / manipulate the IP routing table. c] Save routing information to a configuration file so that ...

  20. Ubuntu Static IP configuration

    Open network settings Ubuntu Desktop. Click on the settings icon to start IP address configuration. Start network configuration to set static IP address. Select IPv4 tab. Static IPv4 IP address Ubuntu Desktop. Select manual and enter your desired IP address, netmask, gateway and DNS settings. Once ready click Apply button.

  21. How to Configure Static IP Address on Ubuntu 24.04 (Desktop)

    When you want a persistent IP address on your Ubuntu 24.04 desktop, then you must a configure a static IP address. Whenever we install Ubuntu then DHCP is enabled by default, and it will try to fetch the IP address from DHCP server if it is available over the network. In Ubuntu Desktop 24.04, there are two ways to configure static IP address:

  22. How can I find the default gateway of a machine?

    1st Method: ip route show or ip route or ip r. You will get some rows , the row where it says 'default' is the row that gives you information on default router ip. To narrow down the result and finding/displaying only 'default' row you can filter it like this. ip r | grep ^def. 2nd Method: route -n.

  23. How to change the hostname on Ubuntu

    Hit Ctrl+X followed by Y to save and exit the hosts file. (Optional) If you're running Ubuntu as a cloud instance with the help of the cloud-init utility, you'll need to modify a third config file ...

  24. What is 192.168.0.1? A Guide to the Default IP Address

    How to change the default admin IP address. Network administrators can easily change the router's LAN IP address to something non-standard. Here is a step-by-step guide: Access the router's configuration settings; Locate the WAN (Wide Area Network) port settings; Assign a static public IP address to the WAN port (You may need to contact ...

  25. Change the hostname of your AL2 instance

    Change the system hostname. If you have a public DNS name registered for the IP address of your instance (such as webserver.mydomain.com), you can set the system hostname so your instance identifies itself as a part of that domain.This also changes the shell prompt so that it displays the first portion of this name instead of the hostname supplied by AWS (for example, ip-12-34-56-78).

  26. How to Implement Network and Client Isolation

    Gateway Features Network Isolation. Network Isolation is the easiest way to completely Isolate one network/VLAN from all other networks/VLANs. It works by automatically creating Firewall Rules when you enable it. To implement: Navigate to Settings > Networks; Select the desired network; Enable Isolate Network; Traffic & Firewall Rules

  27. How to configure static IP address on Ubuntu 20.04 Focal Fossa Desktop

    Hence, the configuration of your IP address is dynamic. In many scenarios, simply configuring your router or local DHCP server is a preferred way to set a static address to any host regardless of the operating system in use. Check your router manual and assign the static IP address to your host based on its MAC address using the DHCP service.

  28. What is HTTP Error 502 Bad Gateway & How to Troubleshoot It

    First, you must find and copy your hosting IP address by accessing the Hosting IP Address page of the WAF dashboard. The next steps depend on your operating system. Microsoft Windows. Follow these instructions to modify your hosts file in Windows.