Tuesday, July 8, 2008

Changing your Ubuntu hostname and dnsdomain name at the command line

Changing your hostname and dnsdomainname at the command line on Ubuntu is easy but you have to be careful not to lock yourself out while you're doing it.

To change it safely, follow these steps carefully. Varying from these can leave your system in an awkward state:
  1. Enter:

    sudo su

    Enter your password if/when prompted. You should at now have a ‘#’ prompt. The sudo command may stop working during this process so it’s important that you have a privileged shell already open from which to fix it.

  2. Edit the /etc/hosts file and replace the hostnames on the line starting with 127.0.1.1 with your FQDN and unqualified host name. This may look something like this:

    127.0.1.1 myhost.example.com myhost

  3. Edit the /etc/dnsdomainname file and replace the contents there (if any) with your desired domain name (eg “example.com”).

  4. Use the hostname command to set the hostname to your desired value (eg “myhost”):

    hostname myhost

  5. Edit /etc/resolv.conf and add a “search” line for your new domain name. Eg:

    search example.com

    You may also wish to remove the search line for the old domain.

  6. Verify that the sudo command works by typing:

    sudo ls

    You should get a directory listing. If you get a message saying that sudo is unable to resolve something, go back and check your work. You must be able to run sudo successfully before pressing ^D to exit from the root shell.