A bit of a back story
我的用例非常具体-我想对在基于CentOS的Docker容器中运行的Java应用程序进行一些端到端测试。 我要测试的代码依赖于日期比较:
if (happenedYesterday(event)) {
foo();
} else {
bar();
}
鉴于我无法修改测试数据,最简单的方法是以某种方式使应用程序认为它是昨天,使其创建事件,然后恢复原始日期,并使应用程序调用上面的代码。
The setup
Since I would like to show how I got from an idea to a working solution, I need to provide a way to reproduce all the mistakes that I've made as part of this exercise - I need an environment which is as close to the original as possible. To achieve it and also to keep the examples as simple as possible, I'll use fabric8/java-centos-openjdk8-jdk Docker image.
让我们从一个未修改的图像开始一个容器,并打开其外壳:
[me@pc ~]$ docker run --name centos -d -it fabric8/java-centos-openjdk8-jdk /bin/bash
...
[me@pc ~]$ docker exec -u 0 -it centos /bin/bash
[root@centos /]#
注意:-u 0参数使命令以root身份登录到容器(0是root的用户ID)
在本文的所有示例中,我将使用个人电脑如[me@个人电脑 ~]$指示在本地计算机上调用的命令,以及中心如[root@中心 /]#用于在容器内调用的命令。
Setting the system date in Docker - naive approach
在我幼稚的方法中,我认为此步骤就像运行以下命令之一一样简单:
[root@centos /]# date -s "15 Oct 2019 19:05"
date: cannot set date: Operation not permitted
Tue Oct 15 19:05:00 UTC 2019
[root@centos /]# hwclock --set --date "15 Oct 2019 19:05"
hwclock: Cannot access the Hardware Clock via any known method.
hwclock: Use the --debug option to see the details of our search for an access method.
不幸的是,事实并非如此。
I tried to find some workarounds, but as far as I understand, Docker reuses the clock of the host machine, so overriding the date in the container is either not doable or not easily doable123. As I'm just a casual user of Docker, I didn't want to dig deeper. However, w