Is it possible change date in docker container?

前端 未结 6 1141
难免孤独
难免孤独 2020-12-01 02:35

I have a container with a running program inside tomcat. I need to change date only in this container and test my program behaviour. I have time sensitive logic, and sometim

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 03:29

    It is very much possible to dynamically change the time in a Docker container, without effecting the host OS.

    The solution is to fake it. 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:

    def set_time(request):
        import os
        import datetime
        print(datetime.datetime.today())
        os.environ["FAKETIME"] = "2020-01-01"  #  string must be "YYYY-MM-DD hh:mm:ss" or "+15d"
        print(datetime.today())
    

提交回复
热议问题