Ошибка unable to resolve host hostname

Recently, I tried to run the command, sudo apt-get update and got the Temporary failure in name resolution error. But, after that the command proceeded and went on to update. Should I worried about the error. Below is the complete log:

sudo apt-get update
sudo: unable to resolve host {hostname}: Temporary failure in name resolution
Hit:1 http://in.archive.ubuntu.com/ubuntu focal InRelease                                                                                                                                                 
Get:2 http://in.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]                                                                                                                                
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]                                                                                                                                 
Fetched 6,581 kB in 6s (1,180 kB/s)                                       
Reading package lists... Done
 

muru's user avatar

muru

192k52 gold badges468 silver badges719 bronze badges

asked Jun 4, 2021 at 6:52

User04's user avatar

3

It seems likely that your computer’s hostname is not configured correctly. There are two files you should check; /etc/hostname contains just your computer’s name, and /etc/hosts will have a line that maps the IP address 127.0.1.1 to your hostname. For example, those files might look like:

username@ubuntu ~ $ cat /etc/hostname
ubuntu

username@ubuntu ~ $ cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       ubuntu

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

If you don’t have those, try adding them — keep in mind that a hostname should only consist of letters, numbers, and hyphens — then reboot and see if you have that error again.

answered Jun 5, 2021 at 23:24

Minneyar's user avatar

MinneyarMinneyar

6243 silver badges13 bronze badges

2

I have a similar issue. I was trying to renew SSL certificate using:
sudo certbot renew
I kept on getting the error: Temporary failure in name resolution. “An unexpected error occurred” while issuing certificate bla bla bla.
The error means there is a missing, wrongly configured or inactive resolve.conf file.

The fix is simple, you need to restart:

$ sudo systemctl restart systemd-resolved.service

   

Then check the status of the file with:

$ sudo systemctl status systemd-resolved.service

Then run the renew SSL command

sudo certbot renew

This resolved my issue

Community's user avatar

answered Jul 26, 2022 at 11:54

user1617947's user avatar

1

I fixed it with:

hostnamectl set-hostname hostname.newdomain.local

cocomac's user avatar

cocomac

2,9273 gold badges15 silver badges45 bronze badges

answered Apr 20, 2022 at 13:16

user15897086's user avatar

I faced this issue in recent times. Please try to edit your /etc/hosts file by using any editor just as vi or nano after that you will see this line
127.0.0.1 localhost
127.0.1.1 ubuntu
remove the line 127.0.1.1 ubuntu
and edit it as 127.0.0.1 yourdomain

It is solved my issue; I hope it is also work for you.

anonymous2's user avatar

anonymous2

4,2586 gold badges32 silver badges61 bronze badges

answered Nov 17, 2022 at 8:09

Prem Patil's user avatar

To test the tutorials on Linux Handbook, I created a new server on UpCloud, my favorite cloud server provider with blazing fast SSD. My Ubuntu 18.04 server was ready within minutes.

I forgot to give it a reasonable name so a few days later, I had to change the hostname and gave it a better name. Now it’s called test-server because that’s what it is used for.

I created a sudo user because I prefer not to be root all the time, specially when I am tinkering with my system.

When I started using commands with sudo, I saw a strange error in the output of the commands:

sudo: unable to resolve host test-server

The command ran with sudo without any problem but this error message was displayed anyway.

Fix sudo: unable to resolve host

The root cause of the error was actually related to the hostname changing. Let me show you how to fix this unable to resolve hostname error.

First, check the hostname of your system with hostname command. In my case, the hostname is test-server.

$hostname
test-server

The hostname is taken from /etc/hostname file.

cat /etc/hostname 
test-server

The same hostname should be listed in the /etc/hosts file as well. But in my case (and I guess in your case as well) this hostname was missing from the /etc/hosts file as you can see in the output below:

127.0.0.1 localhost
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Since it is missing from here, the system is not able to figure out the hostname and thus it throws the error ‘sudo: unable to resolve host’.

To fix this, edit this file and add a new line and set the loopback address with the hostname. You can use Vim to edit files in command line.

127.0.0.1 <hostname>

So now, my /etc/hosts file looks like this:

127.0.0.1 localhost
127.0.0.1 test-server
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Tip: If the old hostname is still present anywhere in your /etc/hosts file, you should replace them with the new hostname.

Immediately after adding the above mentioned line, ‘sudo: unable to resolve host’ error disappeared. I didn’t even need to reboot my Ubuntu server.

I hope this quick little tip helped you to fix this irritating error. Let me know if it worked for you or not in the comment section.

To totally unlock this section you need to Log-in

The error/warning defined in the subject of this article usually can be shown while using, for example, the apt-get tool on Ubuntu/Debian Linux distribution. This could happen after we have (finally) decided to change the hostname of our Linux system giving it a better name. Let’s say that wow it’s called test-server because that is we will use it for. Now, a common scenario would be that, after creating a sudo user because we do not prefer not to be root all the time, we start using commands with sudo, but at some point we see a strange error in the output of the commands:

unable to resolve host {your_hostname}: Name or service not known

The command run with sudo without any problem but this error message will be displayed anyway.

The Fix

The root cause of the error is actually related to the hostname changing. Let’s now show how to fix this unable to resolve hostname error. First, check the hostname of your system with hostname command. For example, let’s say that the hostname is test-server.

$hostname
test-server

The hostname is taken from /etc/hostname file.

cat /etc/hostname 
test-server

The same hostname should be listed in the /etc/hosts file as well. But in our case (and basically in all the cases in which this error appears) the new hostname will miss in the /etc/hosts file as you can see in the output below:

127.0.0.1 localhost
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Since it is missing from here, the system is not able to figure out the hostname and thus it throws the error sudo: unable to resolve host or unable to resolve host {your_hostname}: Name or service not known while using apt-get.

To fix this, edit this file and add a new line and set the loopback address with the new hostname (or just replace the old hostname with the new one). You can use Vim or Nano to edit files in command line.

127.0.0.1 <hostname>

So now, our /etc/hosts file looks like this:

127.0.0.1 localhost
127.0.0.1 test-server
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Again, if the old hostname is still present anywhere in your /etc/hosts file, you should replace them with the new hostname (it is recommended).

Immediately after adding the above mentioned line, sudo: unable to resolve host or unable to resolve host {your_hostname}: Name or service not known errors will disappear.

Summary

Article Name

Unable to resolve host {hostname}: Name or service not known (Linux)

Description

The «Unable to resolve host» on Linux systems, while using sudo or apt-get on Terminal or on headless configurations could be annoying. The fix for this kind of scenario is simple and involves the system hostname.

Author

Publisher Name

Heelpbook.net

Here’s a quick fix to get rid of the «unable to resolve host: Name or service not known» error on Linux.

Linux terminal commands

After changing the hostname on your Linux system, you may encounter the error «unable to resolve host». Here’s what that means, and what you can do to fix it.

What Is a Hostname, and How Do You Change It?

When you set up your Linux system—whether it’s a VPS or a physical machine in your home—you may be asked to provide a hostname. This is a label your computer uses to identify itself to other machines on the network, to the user, and to itself.

Hostnames should be descriptive so that it’s easy to identify machines—even when you’re not sitting directly in front of them. «Kitchen PC», or «David’s tiny laptop» are great names. «racknerd-b7516a» is a terrible name and makes it difficult to work out exactly which machine you’re connected to.

One way of changing the hostname on Ubuntu or other Debian-based Linux distros is with the terminal.

Open a terminal by either pressing Ctrl + Alt + T, or by selecting it from your menu system, then enter:

 sudo hostnamectl set-hostname your-new-hostname 

terminal command to change hostname

Log out and then log back in, and you will see that the hostname has changed.

What Does «unable to resolve host: Name or service not known» Mean?

After changing your system’s hostname, the next time you try to run a command as sudo, you might receive a hostname error. In our case, the error was «unable to resolve host MUOVPS: Name or service not known».

This error does not prevent you from carrying out any tasks, but it can be annoying.

 cat /etc/hostname 

The aforementioned command will show the hostname you just set, but your new hostname is not present as an output of:

 cat /etc/hosts 

terminal output of the above commands

To fix this error, use nano to edit the file:

 sudo nano /etc/hosts 

On a new line, add the hostname of your machine—the hostname of our VPS is MUOVPS as shown below—then save and exit nano with Ctrl + O then Ctrl + X.

hosts open in nano showing MUOVPS on a new line

You Have Fixed the “unable to resolve host” Error!

Hostname errors are not the most serious and are unlikely to significantly disrupt your workflow or your day. But they are annoying and show that you haven’t configured your system properly. For this reason, it’s worth setting the hostname properly.

Fixing this issue requires you to edit the /etc/hosts file. Since it is a critical system file, knowing how to edit it properly is important to prevent any errors.

Некоторые пользователи сталкиваются с ошибкой «sudo unable to resolve host». Обычно, эта ошибка появляется после смены имени компьютера. Это простая проблема, которую можно быстро решить.

В этой статье мы рассмотрим, почему возникает эта ошибка, что она означает, а также как её решить на примере Ubuntu.

Сообщение «unable to resolve host имя_хоста» означает, что утилита не может определить IP-адрес хоста «имя_хоста«. Казалось бы, sudo — это локальная команда для повышения привилегий в системе, и ей незачем определять IP хостов. Но это не совсем так: sudo может использоваться и удалёнными пользователями, например, подключёнными по SSH, а в самом конфигурационном файле /etc/sudoers уровни доступа различных пользователей настраиваются такой строчкой:

пользователь хост=(другой_пользователь:группа) команды 

Подробнее про строку настройки читайте в статье настройка sudo в linux. А сейчас нам интересно, что для каждого запроса утилите нужно определить, какой хост используется на данном компьютере.

Если кратко, то основная идея разработчиков состоит в том, что один универсальный файл /etc/sudoers будет использоваться на множестве компьютеров и на каждом из них нужно определить, какие правила предназначены для него. Таким образом, переменная host в sudoers влияет только на локальные правила.

А теперь вернёмся к нашей ошибке. Как я уже сказал, она означает, что утилита не может определить IP-адрес «имени хоста». Для домена сайта это означало бы, что такой записи нет в DNS. Но поскольку это имя нашего локального компьютера, то вполне естественно, что его нет в глобальной сети.

Как исправить ошибку

1. Решение проблемы в /etc/hosts

Чтобы исправить ошибку, мы можем добавить такую DNS-запись локально в файл /etc/hosts. Поскольку sudo у вас не работает, а этот файл можно редактировать только от суперпользователя, то эта простая задача становится сложнее. Сначала смотрим наше текущее имя хоста:

hostname

Дальше, если у вас установлен пароль root, вы можете авторизоваться от его имени с помощью su:

su -

А затем добавить такую строчку в /etc/hosts:

vi /etc/hosts

127.0.0.1 имя_хоста

Слова «имя_хоста» надо заменить на то имя хоста, которое вы получили с помощью команды hostname. После этого надо перезапустить компьютер или просто перезапустить сеть:

sudo systemctl restart networking

Ещё желательно убедиться, что в системной службе разрешения доменных имён включено использование файла /hosts. Откройте /etc/nsswitch.conf и найдите в строке hosts слово «files». Оно должно быть на первом месте. Если нет, перенесите его на первое место.

Если же у вас пароль для root не установлен, вам нужно загрузиться с LiveCD, примонтировать корневую файловую систему в /mnt/ и исправлять ошибку уже там.

2. Решение с помощью systemd

Есть ещё один путь. В попытках воспроизвести эту проблему в своей Ubuntu 18.04 я обнаружил, что разрешением доменных имён для локальных приложений занимается служба systemd-resolved. Если она запущена, то даже если в файле /etc/hosts нет имени вашего компьютера, всё будет работать. Поэтому, если вы случайно отключили эту службу, верните её на место и всё заработает:

sudo systemctl start systemd-resolved
sudo systemctl enable systemd-resolved

Выводы

В этой статье мы разобрали, как справиться с ошибкой «sudo cannot to resolve host». Как видите, всё достаточно логично и просто. Если у вас остались вопросы, спрашивайте в комментариях!

Понравилась статья? Поделить с друзьями:
  • Ошибка unarc dll вернул код ошибки 12 gta 5
  • Ошибка unable to relay recipient in non accepted domain
  • Ошибка unarc dll вернул код ошибки 1 способы решения
  • Ошибка unable to recover from a kernel exception
  • Ошибка unarc dll в assassins creed black flag