最近在项目中需要修改docker容器内时间,但是用date命令会显示权限不足,于是百度查到创建容器需要添加--cap-add SYS_TIME 参数(可以创建一个简单的ubuntu容器验证docker run -it --cap-add SYS_TIME --rm --name ubuntu ubuntu /bin/bash),但是测试验证时发现还是不行,后面发现是ntp服务影响,每次修改的时间又被ntp服务给同步了时间,所以需要先把ntp服务停止,在容器中修改时间宿主机时间也会同步过去,因为容器和宿主机是共享linux内核。
在宿主机测试:
root@wateras:~# date
Wed Jul 29 06:19:54 UTC 2020
root@wateras:~# date -s "2016-4-2 18:21:45"
Sat Apr 2 18:21:45 UTC 2016
root@wateras:~# date
Wed Jul 29 06:20:04 UTC 2020
root@wateras:~# timedatectl set-ntp true
root@wateras:~# timedatectl set-ntp false
root@wateras:~# date -s "2016-4-2 18:21:45"
Sat Apr 2 18:21:45 UTC 2016
root@wateras:~# date
Sat Apr 2 18:21:46 UTC 2016
root@wateras:~# date
Sat Apr 2 18:21:49 UTC 2016
root@wateras:~# timedatectl set-ntp true
root@wateras:~# date
Wed Jul 29 06:20:54 UTC 2020
在容器内测试:
root@cde2a0448792:/# date
Mon Apr 2 03:23:45 UTC 2018
root@cde2a0448792:/# date -s "2018-4-2 11:21:45"
Mon Apr 2 11:21:45 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 11:21:47 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 11:21:52 UTC 2018
root@cde2a0448792:/# date -s "2018-4-2 18:21:45"
Mon Apr 2 18:21:45 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 18:21:46 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 18:22:19 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 18:22:43 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 18:23:02 UTC 2018
root@cde2a0448792:/# date
Mon Apr 2 21:37:25 UTC 2018
root@cde2a0448792:/# date -s "2016-4-2 18:21:45"
Sat Apr 2 18:21:45 UTC 2016
root@cde2a0448792:/# date
Sat Apr 2 18:21:47 UTC 2016
|