How do I change timezone in a docker container?

You can override as suggest by @LinPy during the run stage, but if you want to set at your Dockerfile you can set using ENV as tzdata is already there in your base image.

FROM postgres:10
ENV TZ="Africa/Lusaka"
RUN date

Build

docker build -t dbtest .

RUN

docker run -it dbtest -c "date"

Now you can verify on DB side by running

show timezone;

You will see Central Africa Time in both container and Postgres

in the alpine base image, the environment variable will not work. You will need to run

 RUN ls /usr/share/zoneinfo && \
cp /usr/share/zoneinfo/Europe/Brussels /etc/localtime && \
echo "Africa/Lusaka" >  /etc/timezone && \

There's a few ways to do it .

  1. You can declare the time zone directly as an environment variable in the docker compose file
   environment:
      - TZ=Asia/Singapore
      - DEBIAN_FRONTEND=noninteractive
  1. You can map the container's time zone and local time files to use that of the host machine in the docker compose file
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro

I personally prefer to use the second method, in this way , all of my containers will have the same time configuration as my host machine


Simply change the /etc/localtime to the time zone in the /usr/share/zoneinfo directory.

follow these steps:

first log into bash of your container:

docker exec -u 0 -it mycontainer bash

then remove the symbolic link file (/etc/localtime):

sudo rm -rf /etc/localtime

Identify the timezone you want to configure and create the symbolic link for it:

For instance, I would like to set Asia/Tehran timezone:

ln -s /usr/share/zoneinfo/Asia/Tehran /etc/localtime

Now verify it by:

date

and the output would be your timezone:

Sat Jan 30 14:22:17 +0330 2021