# Setting Timezone in Alpine-based Docker Image

> How to set the timezone in an Alpine-based Docker image using the Dockerfile.

- URL: https://zeljic.com/blog/docker-alpine-set-timezone/
- Author: Đorđe Zeljić
- Published: 2024-02-17
- Tags: docker, alpine, linux, timezone

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.

*[Image: A container clock linked to one timezone band on the globe, like /etc/localtime pointing into zoneinfo]*

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:

```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:

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. 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:

1. Save the contents of the Dockerfile to a file named `Dockerfile` in an empty directory.
2. Navigate to that directory.
3. Run the following command to build the image:
   ```bash
   $ 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:

```bash
$ docker run -it my-alpine /bin/sh
/ # date
Fri Feb 18 20:00:00 CET 2024
```
