83

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 sometimes need to see what happens in a few days or months later. Is it possible in docker? I read that if I change date in container, date will get changed on the host system. But it is a bad idea for me. I need to have a few instances of this application on one server and have possibilities of setting up different time for each instance.

But when I try to change date inside the container I get the error:

sudo date 04101812
date: cannot set date: Operation not permitted
Fri Apr 10 18:12:00 UTC 2015
2

9 Answers 9

82

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())
9
  • 2
    This works inside a Docker container. I docker exec'd in to install the library and used export set the variables.
    – roman
    Commented Mar 6, 2017 at 19:22
  • 5
    This solution worked perfectly for me as well. I did what Roman suggested above, entered the container, checked out the code using git, ran the make install, then committed my change to the image, and restarted the container using the following method docker run -it --rm [various options omitted] spooforbrains/image1 /bin/bash -c "export LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1; export FAKETIME_NO_CACHE=1; export FAKETIME=\"2016-05-01 12:00:00\"; node nodeimage" Commented May 9, 2017 at 16:41
  • 1
    No, I use the function in a webserver running in a Docker container. The example has nothing to do with the set up. Its just an example of how to use the lib after the configuration.
    – Vingtoft
    Commented Jun 1, 2017 at 17:10
  • 4
    This won't work with golang apps and other statically linked stuff
    – Sentinel
    Commented Oct 16, 2018 at 11:46
  • 4
    For Debian and Ubuntu, there is also a libfaketime package available in the repositories. So you do not need to download the source code and compile it yourself. For Debian Buster, e.g., see here: packages.debian.org/buster/libfaketime Commented Dec 2, 2019 at 12:07
19

That's not possible with Docker. Docker uses the same clock as the outside kernel. What you need is full virtualization which emulates a complete PC.

The sudo fails because it only makes you root of the virtual environment inside of the container. This user is not related to the real root of the host system (except by name and UID) and it can't do what the real root could do.

If you use a high level language like Python or Java, you often have hooks where you can simulate a certain system time for tests or you can write code which wraps "get current time from system" and returns what your test requires.

Specifically for Java, use joda-time. There you can inject your own time source using DateTimeUtils.setCurrentMillis*().

3
  • Docker uses the same clock as the outside kernel. Does this mean changing the host date & time will do?
    – otong
    Commented Mar 14, 2019 at 2:03
  • 1
    @otong Yes but it will affect all running containers and the host system itself. Commented Mar 15, 2019 at 9:29
  • 3
    See Vingtoft's answer for how this is possible with Docker - stackoverflow.com/a/41548434/149428 Commented Mar 2, 2022 at 18:12
10

I created a Docker image containing libfaketime for use with Alpine but the process can be done in other distributions.

Here's an example of using it Java using Groovy as an example. But Tomcat can be used as well.

FROM groovy:alpine
COPY --from=trajano/alpine-libfaketime  /faketime.so /lib/faketime.so
ENV LD_PRELOAD=/lib/faketime.so \
    DONT_FAKE_MONOTONIC=1

Then build and pass the FAKETIME environment variable when doing a docker run for example

docker build -f fakedemo-java.Dockerfile . -t fakedemo
docker run --rm -e FAKETIME=+15d fakedemo groovy -e "print new Date();"

Source is in trajano / alpine-libfaketime | Github and the docker image is in trajano/alpine-libfaketime | dockerhub

I also created a variant of it based on Ubuntu: trajano / ubuntu-faketime | Github

4

For me, I actually needed to set the actual date for testing. I found the following options work on Mac, but you have to realize you'll be changing the date for all of your containers because you're changing the date of the underlying Alpine VM that Docker uses for all of its containers.

OPTION 1: Change the date of your host machine & restart docker

Use this when:

  • You can restart docker.
  • You can change the date of your host machine

Steps:

  1. Stop your containers.
  2. Change the date of your machine via the Date & Time Preferences
  3. Restart docker.
  4. Start your containers.

Run this sequence again to get back to the right date & time.

OPTION 2: Change the date of the Alpine VM

Use this when:

  • You can't restart docker.
  • You can't set the date of your host machine

Steps:

  1. screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
    • The screen starts blank, hit enter a few times.
  2. date -s [hh:mm]
    • All of your docker containers will now have your new time. You can also use other formats, look for documentation on “busybox date” as it’s not quite the same as other date implementations.
  3. To exit hit control-a : and type d
    • This detaches the screen session, but leaves the tty running.

To reset the time:

  1. screen -r
    • This resumes your tty.
  2. ntpd -q
    • This uses the server defined in /etc/ntp.conf (this looks like a magic bridge back to the host clock)
  3. To exit hit control-a : and type quit
    • This terminates your screen and tty session.
0
3

This worked for me, maybe you could try it:

dpkg-reconfigure tzdata

Edit: Execute it inside the container you are having problems. An interface will appear. There you can edit the timezone and localtime for example, and set it correctly, that fixed my problem, that was the same as yours.

Good luck!

3
  • @zwolin You need to install the package debconf in your container (if you're using a Debian base image). For other distributions, you need to look into their documentation) Commented Mar 15, 2019 at 9:35
  • 29
    This is to configure the timezone, This not answer the question
    – FAjir
    Commented Feb 26, 2020 at 10:02
  • 5
    How have 14 people upvoted an answer which does not answer the question? Commented Mar 17, 2021 at 16:51
2

My solution: I run docker on top of a virtualbox vm via vagrant.

This is not as complex as it sounds. The Vagrantfile below resets the datetime of the vm to a specific one, before the machine goes up. The corresponding docker-compose provisioner takes care of automatically running the docker-compose.yml.

Vagrantfile:

Vagrant.configure("2") do |config|
  config.vm.define "ubuntuvm" do |ubuntuvm|
    config.vm.box = "ubuntu/focal64"
    config.vm.provision :docker

    ubuntuvm.trigger.before :up do |trigger|
      trigger.info = "changing time"
      trigger.ruby do |env,machine|
        require 'time'
        machineTime = "2022/07/02 00:20:00"
        offset = DateTime.parse(machineTime).strftime("%Q").to_i - DateTime.now.strftime("%Q").to_i
        puts "Updating machine time to: #{machineTime} by shifting biossystemtime #{offset} ms"
        puts `VBoxManage setextradata #{machine.id} "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled" 1`
        puts `VBoxManage modifyvm #{machine.id} --biossystemtimeoffset #{offset}`
      end
    end
  end


  config.vm.hostname = "ubuntuvm"
  # config.vm.network "forwarded_port", guest: 80 host: 8080
  # config.vm.synched_folter "../data"", "/vagrant_data"

  config.vm.provider "virtualbox" do |vb|
      # vb.memory = "1024"
  end
  config.vm.provision :docker_compose, yml: "/vagrant/docker-compose.yml", rebuild: true, run: "always"
end

Then I just need to do a the following:

# start the machine and run the docker-compose
vagrant up

Everytime I start the machine I see the messages:

ubuntuvm: Updating machine time to: 2022/07/02 00:20:00 by shifting biossystemtime -212710744 ms
ubuntuvm: Running docker-compose up...

other commands:

# get inside the machine with ssh to check its time and also check the container's time (docker commands already exist inside there due to the provisioner).
vagrant ssh ubuntuvm
# stop the machine
vagrant halt
# destroy the machine
vagrant destroy

prerequisites

Known issues:

On the first run only, vagrant up will fail to update the time because for some reason the before-up trigger is executed even before the machine is created. On all other executions the machine is already there, so the time is reset as expected.

0

docker exec -it [Container Id] /bin/bash (exec into container)

rm /etc/localtime (see time zone)

ln -s /usr/share/zoneinfo/Asia/Karachi /etc/localtime (set new time zone)

3
  • 5
    please add a description to your code, and what your code is actually doing. Commented Jan 30, 2021 at 8:42
  • 4
    The original question is to set the date not the timezone
    – jdtommy
    Commented Mar 25, 2021 at 2:27
  • It maybe docker container that build on top of Alpine have not any timezone data. Install with apk add tzdata. wiki.alpinelinux.org/wiki/Setting_the_timezone
    – EsmaeelE
    Commented Sep 4, 2022 at 11:48
0

If you want to change the date of a container, you would need to relax security on your container by adding the --cap-add SYS_TIME flag to your container at startup.

ie:

docker run --rm -it --cap-add SYS_TIME alpine date -s 2020-08-25

This will provide you more permissions on the container, without need be a root.

Here's a link for reference

You can also do this in kubernetes:

apiVersion: v1
kind: Pod
metadata:
  name: hello-world
spec:
spec:
  containers:
  - name: friendly-container
    image: "alpine:3.4"
    command: ["/bin/echo", "hello", "world", "date -s 2020-08-25"]
    securityContext:
      capabilities:
        add:
        - SYS_TIME
1
  • 1
    This will also change the date of the host machine. Commented May 7 at 8:40
-2

I was having the same problem with my jenkins docker instance following steps fixed my problem

  1. exec into container

    docker exec -it 9d41c699a8f4 /bin/bash

  2. See time zone cat /etc/timezone : out put Etc/UTC

  3. set new time zone, with nano : Asia/Colombo (your timezone here)

  4. Restart the container

2
  • 4
    The original question is to set the date not the timezone
    – jdtommy
    Commented Mar 25, 2021 at 2:27
  • 1
    I get: bash: /etc/timezone: Permission denied
    – Ryan w
    Commented Sep 30, 2021 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.