Changing Timezone in Docker

Background

I created a script and it ran well in my local environment. But after it was built in the docker container the string of time was not shown as I expected.

Solution

The difference of timezone between the docker container and host make the problem. Time is always a problem in digital world it always causes problems. So let us resolve it in docker container with dockerfile.

  • changing the environment value TZ
  • changing localtime and timezone in image
1
2
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

Note

When I searched the solution, I found some difference in alpine base images.

Note: if you are using an alpine based image you have to install the tzdata first. (see this issue here)

Looks like this:

1
2
RUN apk add --no-cache tzdata
ENV TZ America/Los_Angeles

Reference