fbpx NTP on Linux: Clock Sync with ntpdate, ntpd and chrony | Certificação Linux

NTP on Linux: Synchronize System Clock with Time Servers

📅 01/01/2019 ⏱ 11 min ✍️ Uira Ribeiro
Linuxcommands
NTP on Linux: Synchronize System Clock with Time Servers
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

Linux maintains two clocks: one is battery-powered, known as the "Real Time Clock", RTC, "CMOS clock", "Hardware clock" or machine clock. It keeps time when the system is shut down and is not used when the system is active. NTP on Linux is an implementation that keeps the clock updated.

The other clock called "system clock", "kernel clock", "software clock" or system clock is a software that counts time based on processor interrupts. It needs to be initialized by the RTC during system boot.

Generally there may be differences between the time shown on these two clocks, the real time and date. We will see the commands to adjust the system clock.

Time on Earth is measured in seconds, which is a unit of the International System of Units. Since 1967 the second has been defined based on the measurement of atomic clocks, which is the duration of 9,192,631,770 periods of the radiation corresponding to the transition between two hyperfine levels of the ground state of the cesium 133 atom.

An important characteristic of time is its monotonicity, which means that time always moves forward. This characteristic is difficult to maintain by clocks implemented in software, as in Operating Systems.

Thus, computer systems need to have their clocks frequently adjusted.

To solve this problem, NTP - Network Time Protocol was created, which implements, in addition to a protocol, a network of servers with atomic clocks that serve to adjust the clocks of other computers around the world.

These clocks are coordinated by the Bureau International des Poids et Mesures (BIPM) which comprises more than 260 atomic clocks located in metrology institutes and observatories around the world, including in Brazil.

NTP is a protocol for synchronizing computer clocks, based on some reliable time source, such as the atomic clocks of the National Observatory, which define the Official Brazilian Time. With NTP it is easy to keep the computer clock always on time.

Thus, NTP accesses one or more time servers, and adjusts the local system time based on these servers.

The latest version of the NTP software can be obtained at the address http://www.ntp.org/downloads.html or downloaded as a package from the Linux distribution.

The NTP package installs a service called ntpd, which runs in the background, and makes time adjustments from time to time keeping the system clock updated.

ntp.conf file

NTP has a configuration file called ntp.conf that usually resides in the /etc directory.

See the CentOS 7 ntpd.conf configuration file:

# arquivo de “memoria” para o escorregamento de frequência do computador
driftfile /var/lib/ntp/drift
# restringe o acesso somente ao localhost
restrict 127.0.0.1 
restrict ::1
# servidores
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst

In addition to synchronizing the local system clock with the NTP server clock selected in the configuration file, NTP also disciplines the clock through system phase and frequency, continuously, even during periods when it is not possible to query time servers.

Thus, the characteristics of the local clock are measured and become known to NTP, which makes it possible for it to make time corrections independently. The file indicated by the driftfile directive stores the expected frequency error for the clock.

The restrict directive allows restricting NTP access only to localhost or local network addresses.

It is not necessary for all computers to remotely connect to an external time server. A Linux operating as a network gateway can connect to an external NTP server, and serve as a synchronization source for other computers on the network.

The server parameter followed by the server name or address indicates which servers NTP will fetch the time from. It is also recommended to additionally use the iburst parameter in the command, which serves to speed up the initial synchronization.

It is common to specify more than one server with the server parameter, so that the client can fetch the time simultaneously from more than one server.

By default, the NTP configuration file already contains a list of NTP servers. It is not necessary to modify the file, unless you wish to.

After installing and configuring, to use the NTP service it is necessary to start the service with the command:

# systemctl start ntpd

And then enable the service for startup at system boot:

# systemctl enable ntpd

The ntpd service uses port 123 of the UDP transport protocol to talk to its clients or connect to servers. The "ss" command with the "-lup" option can show the listening status of port 123:

# ss -lup | grep ntpUNCONN    *:ntp    *:*    users:(("ntpd",pid=7744,fd=16))

Time Zone

Even if NTP fetches the time from a specific server, from a country or region that is in another time zone, Linux still makes the local time zone adjustment using one of the following methods:

Adjustment MethodObservation
/etc/localtimeSymbolic link to some time zone in /usr/share/zoneinfo. Usually used to configure the Time Zone of Red Hat-based distributions.
/etc/timezoneFile containing the name of the Time Zone used by Linux. Usually used to configure the Time Zone of Debian-based distributions.
TZEnvironment variable containing the name of the Time Zone. Works on any Linux and can be customized for each user.
timedatectlSystemd service that can be used to configure the Time Zone in distributions that use Systemd.

pool.ntp.org

The pool.ntp.org project is a large virtual cluster of time servers providing a reliable and easy-to-use NTP service for millions of clients.

pool.ntp.org is being used by tens of millions of systems worldwide. It is the default "time server" for most Linux distributions and many network appliances.

Its use is very simple, just use their servers as reference in the configuration:

server 0.pool.ntp.orgserver 1.pool.ntp.orgserver 2.pool.ntp.orgserver 3.pool.ntp.org

ntpdate command

The ntpdate command can also be used to synchronize the clock at a specific moment, even if the NTP service is not running:

$ ntpdate  -q a.ntp.brserver 2001:12ff::8, stratum 2, offset 0.004601, delay 0.04297server 200.160.0.8, stratum 2, offset 0.003794, delay 0.0447520 Oct 14:50:02 ntpdate[10902]: adjust time server 2001:12ff::8 offset 0.004601 sec

The "-q" option only queries the server, without changing the local clock. To change the local clock with ntpdate, the ntpd service cannot be running.

ntpq command

The ntpq utility can be used to query NTP servers. It can be used in interactive mode, where a prompt will be presented, or using parameters.

The "-p" option shows the list of peer servers and the status of each one:

# ntpq -p     remote       st t when poll reach   delay   offset  jitter===================================================================+gps.ntp.br      2 u   86  256  217   19.648   -1.463 1059.39*b.st1.ntp.br    1 u  198  256  307   31.605    4.667 828.577 2001:440:1880:5 16 -  52m 1024    0    0.000    0.000   0.000 b.ntp.br        2 u   63  256  237   55.025    0.950 732561.+a.ntp.br        2 u   81  256  217   20.002   -1.437 1057.36+a.st1.ntp.br    1 u   56  256  217   21.052   -1.931 1065.28+gps.jd.ntp.br   1 u   96  256  217   21.140   -1.688 1055.66+d.st1.ntp.br    1 u  121  256  217   23.940    0.083 1058.75

hwclock command

The hwclock command can be used to read the hardware clock or to set the hardware clock from the system clock and vice versa.

As mentioned at the beginning of the chapter, computers keep two clocks. One called the hardware clock, which is powered when the system is off, and is maintained by a quartz crystal and a battery when the computer is powered off. This battery is capable of keeping the clock running even when disconnected from the power grid for a long time.

When the computer is powered on, Linux reads the hardware clock to update its system clock. It's common for there to be a small difference between these two clocks.

The hwclock command has the following options:

  • -r: displays the hardware clock time in the local timezone;
  • -s: sets the system clock from the hardware clock;
  • -w: sets the hardware clock from the system clock;
  • -c: compares the hardware clock and system clock every 10 seconds;
  • --adjust: adds or subtracts time from the hardware clock to adjust for frequency drift;

Examples:

# hwclock -chw-time      system-time         freq-offset-ppm   tick1571594417   1571594417.0114231571594427   1571594427.012649               123      1

To set the hardware clock from the system clock:

# hwclock -w

The Chrony Package

Chrony is a versatile implementation of the Network Time Protocol (NTP). It can synchronize the system clock with NTP servers.

It can also operate as an NTPv4 (RFC 5905) server and provide a time service for other computers on the network.

It can be installed through the Linux distribution packages:

$ sudo apt install chrony

The chrony.conf File

Chrony uses the configuration file called chrony.conf which can reside in the /etc/ or /etc/chrony directory.

Its configuration is similar to ntpd.conf, with the only difference being that the server key is called pool:

$ cat /etc/chrony/chrony.conf pool ntp.ubuntu.com        iburst maxsources 4pool 0.ubuntu.pool.ntp.org iburst maxsources 1pool 1.ubuntu.pool.ntp.org iburst maxsources 1pool 2.ubuntu.pool.ntp.org iburst maxsources 2driftfile /var/lib/chrony/chrony.drift

The chrony service can be started and enabled with the systemctl command:

$ sudo systemctl start chrony

To enable the service at system boot:

$ sudo systemctl enable chronyExecuting: /lib/systemd/systemd-sysv-install enable chrony

chronyc Command

chronyc is a utility used to monitor chronyd performance and to change its operation while it is running.

If no command is specified on the command line, chronyc will wait for user input through the chronyc> prompt.

It accepts several commands, both in interactive mode and directly as an argument:

$ chronycchronyc> sources210 Number of sources = 8MS Name/IP address     Stratum Poll Reach LastRx Last sample               =========================================================================^- golem.canonical.com     2   6   373    70  -9241us[-9241us] +/-  143ms^- pugot.canonical.com     2   6   377    77    -11ms[  -11ms] +/-  135mschronyc> quit

The sources command does the same thing as "ntpq -p".

The tracking command shows the system clock status:

$ chronyc trackingReference ID    : C814BA4C (d.st1.ntp.br)Stratum         : 2Ref time (UTC)  : Sun Oct 20 20:15:10 2019System time     : 0.000793245 seconds slow of NTP timeLast offset     : -0.000647185 secondsRMS offset      : 0.001815075 secondsFrequency       : 4.009 ppm slowResidual freq   : -0.191 ppmSkew            : 3.915 ppmRoot delay      : 0.031462338 secondsRoot dispersion : 0.002590907 secondsUpdate interval : 129.0 secondsLeap status     : Normal

Communication between the chronyd server and the chronyc client is done through UDP port 323:

$ sudo ss -lunp | grep chronyUNCONN  [::1]:323    [::]:*     users:(("chronyd",pid=18869,fd=6))     

timedatectl Command

The timedatectl command is able to identify that Linux is using some system clock synchronization service, such as ntpd or chronyd:

$ timedatectl                Local time: Sun 2019-10-20 17:17:34 -03           Universal time: Sun 2019-10-20 20:17:34 UTC                 RTC time: Sun 2019-10-20 20:17:34                Time zone: America/Buenos_Aires (-03, -0300)System clock synchronized: yes              NTP service: active          RTC in local TZ: no

Because chrony is faster to update the date and time on the system, it is ideal for desktop systems and laptops, which are frequently powered off. NTP, on the other hand, is suitable for computers that stay permanently powered on.

Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.

Like it? Share

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp