How to set system time dynamically in a Docker container

Solution 1:

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:

RUN git clone
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.


CMD ["/bin/sh", "-c", "LD_PRELOAD=/usr/local/lib/faketime/ FAKETIME_NO_CACHE=1 python /srv/intercept/ runserver]

You can now dynamically change the servers time:


import os
def set_time(request):
    os.environ["FAKETIME"] = "2020-01-01"  # Note: time of type string must be in the format "YYYY-MM-DD hh:mm:ss" or "+15d"

Solution 2:

Jenny D is correct in that by default Docker container doesn't allow access to system clock.

However, on Linux, if you're fine with your container having access to this capability, you can allow this capability using "--cap-add=SYS_TIME" option of "docker run" command when creating you container:

# docker run --cap-add=SYS_TIME -d --name teamcity-server-instance -v /opt/teamcity/data:/data/teamcity_server/datadir -v /opt/teamcity/logs:/opt/teamcity/logs -p 80:8111 jetbrains/teamcity-server

Then, you can change the time from inside the running container:

# docker exec -it teamcity-server-instance /bin/bash
# date +%T -s "15:03:00"

Reference documentation: