Permanent hostname change on Ubuntu
26,469
Solution 1
I followed [these instructions] and it worked even after restart the machine.
Summary:
sudo hostname NEW_NAME_HERE
sudo nano /etc/hostname # change OLD_NAME by NEW_NAME
sudo nano /etc/hosts # change OLD_NAME by NEW_NAME
sudo systemctl restart systemd-logind.service
hostnamectl set-hostname NEW_NAME_HERE
Also you should recreate your ssh keys on your machine:
sudo rm /etc/ssh/ssh_host_*
sudo dpkg-reconfigure openssh-server
Just in case, check references of your old hostname on /etc and fix it:
sudo grep -R OLD_NAME /etc/ 2>/dev/null
Solution 2
Edit the file /etc/hostname
.
From man 5 hostname
:
It should contain a single newline-terminated hostname string.
Related videos on Youtube
Author by
Veeresh123
Updated on September 18, 2022Comments
-
Veeresh123 over 1 year
I have successfully changed the hostname of my Ubuntu machine, though whenever I restart it, I need to run this command to access it using host name
sudo /etc/init.d/hostname.sh start
This is what I used to do the change:
# take care of "hostname" command and editing "/etc/hostname" hostnamectl set-hostname <new.hostname> # Edit "/etc/hosts" 127.0.1.1 <new.hostname>
How can I make this permanent?
-
anonymous2 over 7 yearsYou could simply add that line to your sudo crontab.
-
Veeresh123 over 7 yearsYeah, I could do that. I was wondering if there was a "right" way to persist this setting. Thanks.
-
user4556274 over 7 yearsWell, it should already be persistent. Now the question is why your system is not setting the hostname from
/etc/hostname
at boot without manually (re-)runninghostname.sh
. -
Veeresh123 over 7 yearsThat's what I am wondering :)
-
Terrance over 7 yearsAfter running the
hostnamectl
command, have you checked what the contents of/etc/hostname
are? -
Veeresh123 over 7 yearsyes.
/etc/hostname
is correct. -
Terrance over 7 yearsTo add that command to your startup, you would need to edit the
/etc/crontab
file and add at the bottom@reboot root /etc/init.d/hostname.sh start
that way every time it starts up it will run that command.
-
-
Veeresh123 over 7 yearsI've already done that. Added details to the question.
-
Veeresh123 over 7 yearsAs I have mentioned in the question, the
hostnamectl set-hostname
takes care of that. Here: manpages.ubuntu.com/manpages/trusty/man1/hostnamectl.1.html -
user4556274 over 7 yearsWhich version of ubuntu are you running? Is the initialization via
systemd
orinit
? -
Veeresh123 over 7 yearsGood point. 16.04. Updated question. Not sure I know how to check how the system is being initialized.
-
user4556274 over 7 yearsDo you have a symlink
/etc/rcS.d/S02hostname.sh -> ../init.d/hostname.sh
? (or similar) -
Veeresh123 over 7 yearsyes indeed, I do have that link.
-
Roger Dueck over 3 yearsI've always used the first 3 commands, but the
grep
was helpful - I found the OLD_NAME in/etc/mailname
and/etc/exim4/update-exim4.conf.conf
.