Setting Timezone in Alpine-based Docker Image
When creating a Docker image using the Alpine Linux distribution, you may need to set the timezone to match your specific requirements. This is important for accurate timestamps in logs, scheduled tasks, and other time-sensitive operations. In this post, we’ll look at how to set the timezone in an Alpine-based Docker image using the Dockerfile.
First, determine the time zone you wish to set. A list of supported time zones can be found in the /usr/share/zoneinfo directory. Once you’ve identified the correct time zone, configure /etc/localtime to point to the appropriate file in this directory.
Dockerfile
Let’s translate this into a Dockerfile:
FROM alpine:latest
ENV TZ=Europe/Belgrade
# Install timezone data and set the desired time zone
RUN apk add --no-cache tzdata \
&& ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
&& echo $TZ > /etc/timezone
Explanation of the Dockerfile
In the Dockerfile above, we are:
- Using the latest Alpine image.
- Setting the
TZenvironment variable to the desired time zone (Europe/Belgradein this case). - Installing the
tzdatapackage, which contains time zone definitions. - Creating a symbolic link from
/etc/localtimeto the correct time zone file under/usr/share/zoneinfo. - Writing the time zone to
/etc/timezone. While not all software relies on this file, it can be useful for applications that read the timezone from it.
Important Note
Keep in mind that setting the TZ environment variable affects the time reported by the date command and software that uses this variable. However, it does not influence system log timestamps or other software that relies solely on /etc/localtime. This is why we create a symbolic link to /etc/localtime in addition to setting TZ.
Building and Running the Docker Image
To create a Docker container with this Dockerfile:
- Save the contents of the Dockerfile to a file named
Dockerfilein an empty directory. - Navigate to that directory.
- Run the following command to build the image:
$ docker build -t my-alpine .
This will build an image named my-alpine with your specified timezone settings.
Check the Timezone
To verify that the timezone has been set correctly, you can run the date command inside the container. The output should reflect the timezone you set in the Dockerfile:
$ docker run -it my-alpine /bin/sh
/ # date
Fri Feb 18 20:00:00 CET 2024