hostname --fqdn Name or service not known

If your host name does not resolve correctly you can get an annoying Name or Service not known error when you ask for your fully qualified domain name - even if you have correctly set your full host name. Here's why and what to do about it.

Normally when we setup a new server we set the hostname:

  • On Redhat systems (Fedora, CentOS, etc.,) the hostname is set in /etc/sysconfig/network like this:

    /etc/sysconfig/network:

    NETWORKING=yes
    HOSTNAME=myhost.name.tld
    GATEWAY=my.gateway.name.tld

  • On Debian systems (Ubuntu, Knoppix, Xandros) the hostname is set in /etc/hostname (a simple text file with only the hostname of the server in it.)

During the boot process the system startup scripts will read the hostname and set it in the system. It will then be possible to query the hostname:

$ hostname
myhost.name.tld

Software (such as sendmail,) will get the hostname in a slightly different way. In some cases this variation does not work:

$ hostname --fqdn
Name or service not known

The documentation for the hostname command hints at the problem. It explains that:

The FQDN of the system is the name that the resolver(3) returns for the host name.

Technically: The FQDN is the name gethostbyname(2) returns for the host name returned by gethostname(2).

If we read the above literally the solution is simple: Go into /etc/hosts and add the host name along with the external IP for the server:

/etc/hosts

...
12.34.56.78 myhost.name.tld
...

Sadly, this may not work as expected. It seems to me that the system is trying to find the short host name. Add it like this:

/etc/hosts

...
12.34.56.78 myhost.name.tld myhost
...

This worked for me Amazon EC2 where the external IP of the server does not appear on any of the local network devices.