Sync linux server time ntp server

How to Sync Time in Linux Server using Chrony

Time plays an important role in Linux servers specially when they are used in banking, stock markets and other financial sectors. If we want all our Linux servers should have the correct time, then we must configure some NTP client which will fetch correct time always from remote NTP Servers and if needed makes the required adjustments for syncing the time.

In this article we will demonstrate how we can sync time with NTP servers in Linux Server using Chrony (NTP Client).

Install Chrony on CentOS / RHEL / Fedora System

To Install Chrony on CentOS, RHEL and Fedora System, execute the following yum or dnf command

~]# yum install chrony -y Or ~]# dnf install chrony -y

Install Chrony on Debian / Ubuntu System

To install Chrony on Debian and Ubuntu Systems, run the following apt command,

~]$ sudo apt install chrony -y

Once the chrony is installed on Linux server then it offers two programs,

  • chronyc : It is command line interface of chrony
  • chronyd : It is daemon for chrony which start and enable chrony service across the reboot.

Configuration File of Chrony

Configuration file for Chrony is “/etc/chrony.conf” , sample chrony.conf file is listed below,

Chrony-Conf-Linux-Server

  • pool 0.europe.pool.ntp.org iburst is the remote NTP server from where chrony will fetch the time.
  • driftfile /var/lib/chrony/drift is the drift file which contains drift data
  • makestep 1.0 3 is the parameter which will step system clock (speedup or slow down) if adjustment is larger than 1 second but only for first 3 clock updates
  • keyfile /etc/chrony.keys as the name suggest this file contains keys for NTP authentication.
  • logdir /var/log/chrony , it is the log file which logs of Chrony.

Testing Chrony

Just like ntpdate command in NTP distribution, we can use chronyd to sync time of our Linux server with remote NTP server manually,

Syntax: # chronyd -q ‘server iburst’

~]# chronyd -q 'server 0.europe.pool.ntp.org iburst'

chronyd-sync-linux-server

As we can see in above output, chrony has corrected the system time, before running the chronyd command system time was almost 2 hours behind from accurate time.

Читайте также:  Hybrid graphics arch linux

Start and Enabled Chronyd Service

Run the following commands to start and enable chronyd daemon so that it will be available across the reboots.

Run the beneath command to verify the chronys service status

chronyd-service-status-linux-server

Verify and Track Chrony Synchronization

To verify whether your system’s time is synchronized using chrony, issue the following command,

[[email protected] ~]# chronyc tracking Reference ID : 904C13DD (its.no-fun.de) Stratum : 3 Ref time (UTC) : Sun Jan 12 06:23:26 2020 System time : 0.000174314 seconds slow of NTP time Last offset : -0.000199483 seconds RMS offset : 0.000199483 seconds Frequency : 0.301 ppm fast Residual freq : -40.403 ppm Skew : 0.541 ppm Root delay : 0.172664896 seconds Root dispersion : 0.047364954 seconds Update interval : 64.8 seconds Leap status : Normal [[email protected] ~]#
  • Reference ID is the ID and name of server to which your system’s time currently synced.
  • Stratum , it indicates the number of hops away from the server with an attached reference clock we are.

Check Chrony Sources

To list information about the current time sources that the chronyd is using, run the following command,

chronyc-sources-linux-server

To list more detailed information about sources then run the following command

Check Chrony Source Statistics

To list the information about drift speed and offset estimation of each source that the chronyd is using, run the following command

Chrony-Source-Stats-Linux-Server

Configure Chrony NTP Server

Let’s assume you want to configure your Linux Server as a Chrony NTP server for all internal systems. To accomplish this, we need to uncomment two lines from configuration file “/etc/chrony.conf

Execute the following commands

~]# sed -i "s/#local stratum 10/local stratum 10/g" /etc/chrony.conf ~]# sed -i "s/#allow 192.168.0.0\/16/allow 192.168.0.0\/16/" /etc/chrony.conf

When we uncomment the line “ local stratum 10″ then makes our Linux Server as chrony NTP server and continue to work normally even if it is disconnected from network. Whereas “ allow 192.168.0.0/26 ” indicates that clients from this network is allowed to make connection to our Chrony NTP server for time syncing.

After making changes restart chrony service and track chrony

~]# systemctl restart chronyd ; watch chronyc tracking

Restart-track-chrony-linux-server

Allow NTP Service in firewall using following command,

~]# firewall-cmd --add-service=ntp –permanent ~]# firewall-cmd --reload

That’s all from this article, I hope you get an idea how we can sync our linux system’s time with NTP server using chrony service and apart from this we have also learned how we can configure our own Chrony NTP server. Please do share your valuable feedback and comments.

Читайте также:  Linux права создаваемые файлы

Источник

Синхронизация времени по NTP

NTP — это протокол синхронизации времени по сети. По существу клиенты запрашивают текущее время на сервере и используют его для установки своих собственных часов.

За этим простым описанием скрывается много сложностей — существуют уровни NTP серверов, где первый уровень подключен к атомным часам, а второй и третий уровни серверов распределяют на себя нагрузку по актуальным запросам из интернета. Кроме того клиентское приложение сложнее, чем вы можете подумать — оно компенсирует задержки соединения и регулирует время таким образом, чтобы не навредить другим процессам, запущенным на сервере. Но к счастью вся эта сложность скрыта от вас!

Ubuntu использует ntpdate и ntpd.

ntpdate

Ubuntu стандартно устанавливается с ntpdate и будет запускать его при каждой загрузке один раз для установки времени по NTP серверу Ubuntu.

ntpd

Сервис NTP ntpd вычисляет уход ваших системных часов и постоянно подправляет их, благодаря чему не происходит сильных изменений, что может приводить к непоследовательности в журналах. Ценой этому небольшое расходование мощности процессора и оперативной памяти, но для современного сервера это несущественно.

Установка

Для установки ntpd из терминала введите:

Настройка

Отредактируйте /etc/ntp.conf для добавления/удаления серверов. По умолчанию эти сервера такие:

# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board # on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for # more information. server 0.ubuntu.pool.ntp.org server 1.ubuntu.pool.ntp.org server 2.ubuntu.pool.ntp.org server 3.ubuntu.pool.ntp.org

После изменений конфигурационного файла вам надо перезапустить ntpd:

Просмотр статуса

Используйте ntpq для просмотра дополнительной информации:

# sudo ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +stratum2-2.NTP. 129.70.130.70 2 u 5 64 377 68.461 -44.274 110.334 +ntp2.m-online.n 212.18.1.106 2 u 5 64 377 54.629 -27.318 78.882 *145.253.66.170 .DCFa. 1 u 10 64 377 83.607 -30.159 68.343 +stratum2-3.NTP. 129.70.130.70 2 u 5 64 357 68.795 -68.168 104.612 +europium.canoni 193.79.237.14 2 u 63 64 337 81.534 -67.968 92.792

Источник

About time synchronisation

Network Time Protocol (NTP) is a networking protocol for synchronising time over a network. Basically, a client requests the current time from a server, and uses it to set its own clock.

Behind this simple description, there is a lot of complexity. There are three tiers of NTP servers; tier one NTP servers are connected to atomic clocks, while tier two and tier three three servers spread the load of actually handling requests across the Internet.

Читайте также:  Linux mint системные настройки прокси

The client software is also a lot more complex than you might expect. It must factor in communication delays and adjust the time in a way that does not upset all the other processes that run on the server. Luckily, all that complexity is hidden from you!

By default, Ubuntu uses timedatectl / timesyncd to synchronise time, and they are available by default. See our guide If you would like to know how to configure timedatectl and timesyncd .

Users can also optionally use chrony to serve NTP.

How time synchronisation works

Since Ubuntu 16.04, timedatectl / timesyncd (which are part of systemd ) replace most of ntpdate / ntp .

About timesyncd

timesyncd replaces not only ntpdate , but also the client portion of chrony (formerly ntpd ). So, on top of the one-shot action that ntpdate provided on boot and network activation, timesyncd now regularly checks and keeps your local time in sync. It also stores time updates locally, so that after reboots the time monotonically advances (if applicable).

About timedatectl

If chrony is installed, timedatectl steps back to let chrony handle timekeeping. This ensures that no two time-syncing services can conflict with each other.

ntpdate is now considered deprecated in favor of timedatectl (or chrony ) and is no longer installed by default. timesyncd will generally keep your time in sync, and chrony will help with more complex cases. But if you had one of a few known special ntpdate use cases, consider the following:

  • If you require a one-shot sync, use: chronyd -q
  • If you require a one-shot time check (without setting the time), use: chronyd -Q

While use of ntpd is no longer recommended, this also still applies to ntpd being installed to retain any previous behaviour/config that you had through an upgrade. However, it also implies that on an upgrade from a former release, ntp / ntpdate might still be installed and therefore renders the new systemd -based services disabled.

Further reading

  • ntp.org: home of the Network Time Protocol project
  • pool.ntp.org: project of virtual cluster of timeservers
  • Freedesktop.org info on timedatectl
  • Freedesktop.org info on systemd-timesyncd service
  • Chrony FAQ
  • Feeding chrony from GPSD
  • Also see the Ubuntu Time wiki page for more information.

Источник

Оцените статью
Adblock
detector