How to set system time dynamically in a Docker container
Is there any way to set a Docker containers system time dynamically (at run time) without effecting the host machine?
Using
hwclock --set --date "Sat Aug 17 08:31:24 PDT 2016"
gives the following error:
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.
Using
date -s "2 OCT 2006 18:00:00"
gives the following error:
date: cannot set date: Operation not permitted
Use case:
I need to test time sensitive software (behaviour depends on the date).
Other common use cases:
- running legacy software with y2k bugs
- testing software for year-2038 compliance
- debugging time-related issues, such as expired SSL certificates
- running software which ceases to run outside a certain timeframe
- deterministic build processes.
It is possible
The solution is to fake it in the container. This lib intercepts all system call programs use to retrieve the current time and date.
The implementation is easy. Add functionality to your Dockerfile as appropriate:
WORKDIR /
RUN git clone https://github.com/wolfcw/libfaketime.git
WORKDIR /libfaketime/src
RUN make install
Remember to set the environment variables LD_PRELOAD
before you run the application you want the faked time applied to.
Example:
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]
You can now dynamically change the servers time:
Example:
import os
def set_time(request):
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())
Here's docker-compose
solution:
Add /etc/localtime:/etc/localtime:ro
to the volumes
attribute.
Check this link for getting an example.