有没有办法在不影响主机的情况下dynamic地(在运行时)设置Docker容器系统时间?
运用
hwclock --set --date "Sat Aug 17 08:31:24 PDT 2016"
给出以下错误:
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.
运用
date -s "2 OCT 2006 18:00:00"
给出以下错误:
date: cannot set date: Operation not permitted
用例:
我需要testing时间敏感的软件(行为取决于date)。
其他常见用例:
无法dynamic更改Docker容器中的时间,而不会影响主机操作系统。
解决办法是将其伪装在容器中。 这个lib拦截所有的系统调用程序用来检索当前的时间和date。
实施很简单。 根据需要向Dockerfile添加function:
WORKDIR / RUN git clone https://github.com/wolfcw/libfaketime.git WORKDIR /libfaketime/src RUN make install
请记住在运行要应用伪装时间的应用程序之前设置环境variablesLD_PRELOAD 。
例:
CMD ["/bin/sh", "-c", "LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 FAKETIME_NO_CACHE=1 python /srv/intercept/manage.py runserver 0.0.0.0:3000]
您现在可以dynamic更改服务器时间:
例:
def set_time(request): import os print(datetime.today()) os.environ["FAKETIME"] = "2020-01-01" # Note: time of type string must be in the format "YYYY-MM-DD hh:mm:ss" or "+15d" print(datetime.today())
用另一个环境variables启动容器:
docker run -e "SET_CONTAINER_TIMEZONE=true" \ -e "CONTAINER_TIMEZONE=US/Arizona" [docker image name]