Monday, September 18, 2006

How to synchronize time with NTP servers on an ubuntu machine

Update: Thanks to Ben Dodd for pointing this out, this blog post is now obsolete. NTP synchronization is now built into Ubuntu. Just install ntp using the command:
sudo apt-get install ntp
and you're done.



After the last two power failures in my area, I realized that the server loses its time after every hard restart. Its BIOS battery is totally exhausted. The time is now erroneous, systemwide! I remember Ubuntu includes a tool with which it can (and does, by default) synchronize time with its NTP servers. In my case, it isn't working well. So here's how I made it work:

1. First, make sure NTP is intstalled.

sudo apt-get install ntpdate

2. Then, run ntpdate, specifying an NTP server:

sudo ntpdate ntp.ubuntulinux.org

This should set the time correctly for that session. Note that superuser previleges are necessary to set the time, because setting time is really an "administrative task".

3. Now you shall want this to run this regularly, right? Since it's a server, I'd prefer to run it at startup. To do this, we shall add a little script to the startup.

First, open a terminal, and pass this command:

sudo nano /etc/init.d/ntpdate

In the blank file that comes up, copy and paste this:

#! /bin/sh
echo "Synchronizing system time with Ubuntu Servers..."
ntpdate ntp.ubuntu.com
echo "Setting hardware clock to updated time..."
hwclock --systohc

Note the last line: It resets the hardware time ("BIOS time") to the system time. Press Ctrl+O to write out this file, and Ctrl+X to quit nano. Now we shall make this little script executable. To do this,

sudo chmod 700 /etc/init.d/ntpdate

And finally, let's inform the system about this new startup script we just added:

sudo update-rc.d ntpdate defaults 90

And you're done.

To test this, you must restart your system, and keep a close watch on the messages being shown on the system. Alternatively, you could also read the system log files later (/var/log/syslog)

3 comments:

movrshakr said...

I followed these instructions, but after reboot, syslog showed: "ntpdate[5308]: the NTP socket is in use, exiting"

ntpd did not start until a few lines later, so ntp was not using the port at that time.

Ben Dodd said...

This is a very outdated article now. I would recommend people 'sudo apt-get install npd' ONLY.

The time will take a short while to update to the time servers, I went away for lunch and aftewards my server was sync'd! No configuration needed :)

Anil said...

I think you meant "sudo apt-get install ntp"