How to Change the Time Zone for a Docker Container

In this post we will change the timezone of dokcer.

Method 1: Via Dockerfile.

Add below lines in Dockerfile to chnage the timezone to IST.

1RUN date
2ENV TZ=Asia/Calcutta
3RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
4RUN date

Example of Docker file:

1From tomcat:9.0
2RUN date
3ENV TZ=Asia/Calcutta
4RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
5RUN date

Note: You can change the timezone to any, just change the TZ="Your-time-Zone".

List of TZ database name: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Method 2: Via date command. To change the time in a Docker container is to change the time using ‘date’ command after connecting to the container.

1docker exec -it container-name /bin/bash
2date +%T -s "10:00:00"

Though the time zone change usually reflects immediately. In some cases, the container needs a restart for the time to change.

Method 3: Via environment variables

set using an environment variable in the docker container when it is created.

1docker run -e TZ=America/New_York ubuntu date
2 

Note: The time zone data package tzdata needs to be installed in the container for setting this timezone variable.

Method 4: Using Via volumes

A major issue with Docker containers is that the data in the container is not persistent over restarts. To work around this, we use Docker data volumes.

The directory ‘/usr/share/zoneinfo’ in Docker contains the container time zones available. The desired time zone from this folder can be copied to /etc/localtime file, to set as default time.

This time zone files of the host machine can be set in Docker volume and shared among the containers by configuring it in the Dockerfile as shown.

1volumes:
2	- "/etc/timezone:/etc/timezone:ro"
3	- "/etc/localtime:/etc/localtime:ro"

The containers created out of this Dockerfile (docker-compose.yml) will have the same timezone as the host OS (as set in /etc/localtime file) .

I :heart: AWS! :smile: Enjoy