I was recently asked if there was a docker option available to set the timezone in a container. There isn't one, and I started looking into whether it would be a good feature-add. I found several github issues discussing how to best set it. There were recommendations of bind-mounting /etc/localtime, or setting an environment variable (though no one went into much detail on that one). I did a little googling this morning, and came across a new environment variable: TZ.
TZ is available on all POSIX-compliant systems. You can pass in a timezone using Olson Format, e.g. America/Chicago. Read more about TZ here: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html.
To find the timezone, Ubuntu, and RHEL-based systems all seem to sym-link /etc/localtime to a timezone file. If someone has just overwritten it on your system, you'll have to modify accordingly.
On my laptop:
> readlink /etc/localtime
Docker has a flag, -e, to pass in environment variables via the CLI.
Using the two together, all you really need is:
`docker run -it --rm -e "TZ=$(readlink /etc/localtime | cut -d '/' -f5,6 )" centos:7`
You can run it once without specifying the timezone:
> docker run -it --rm centos:7 date +%Z
And again with it to check:
> docker run -it --rm -e "TZ=$(readlink /etc/localtime | cut -d '/' -f5,6)" centos:7 date +%Z
You can also choose a specific timezone:
> docker run -it --rm -e "TZ=Asia/Tehran" centos:7 date +%Z