Setting Timezone in Alpine-based Docker Image

17-Feb-2024

When creating a Docker image using the Alpine Linux distribution, you may need to set the timezone to match your specific requirements. In this post, we'll look at how to set the timezone in an Alpine-based Docker image using the Dockerfile.

Determine the time zone you wish to set, a list of time zones supported by the operating system can be found in the /usr/share/zoneinfo directory. Once you have found the correct time zone, set the /etc/localtime symbolic link to point to the appropriate file under /usr/share/zoneinfo.

Docker file

Let's translate this into a Dockerfile:

FROM alpine:latest

ENV TZ=Europe/Belgrade

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:

  1. Using the latest alpine image.
  2. Setting the TZ environment variable to the desired time zone (Europe/Belgrade in this case).
  3. Installing the tzdata package which contains time zone definitions.
  4. Creating a symbolic link from /etc/localtime to the correct time zone file under /usr/share/zoneinfo.
  5. Echoing the time zone into /etc/timezone. This is for software that uses this file to determine the local time.

Important Note

It's important to note that setting the TZ environment variable will only affect the time reported by date and used by software that uses this variable. It will not affect system log files, for example. For that reason, we also create a symbolic link for /etc/localtime.

Building and Running the Docker Image

To create a Docker container with this Dockerfile, save the contents of the Dockerfile to a file named Dockerfile in an empty directory, navigate to that directory, and run 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/bash
/ # date
Fri Feb 18 20:00:00 CET 2024