Making use of timezone in an alpine container image
To set your alpine-based container to output the date in your favorite local timezone, pass it the TZ=Europe/Amsterdam
environment variable and also install the tzdata
package using apk
. A date
command will then give you your local time instead of (the default) UTC time.
I really like alpine as a basis for creating my custom container images. Alpine is a very small and efficient container-optimized “OS disk” which is built around musl libc instead of glibc. Another big plus for this image is that it’s by default less prone to containing potentially vulnerable binaries (like with debian, ubuntu and centos base images), simply because it contains only the bare minimum.
To use the proper local time inside a container within an alpine based image, you should do two things:
- Pass the
TZ
environment variable key to the container with its value set to a known timezone. Please note that timezone strings seem to be case-sensitive. - Install the
tzdata
package usingapk
.
A oneliner to show the timezone at work (CET
in the time below indicates the timezone):
$ docker container run -it -e "TZ=Europe/Amsterdam" --rm alpine /bin/sh -c 'apk --no-cache add tzdata && date'
fetch https://dl-cdn.alpinelinux.org/alpine/v3.15/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.15/community/x86_64/APKINDEX.tar.gz
(1/1) Installing tzdata (2021e-r0)
Executing busybox-1.34.1-r3.trigger
OK: 9 MiB in 15 packages
Fri Dec 17 11:50:04 CET 2021
Or if you prefer a docker compose
example, here’s a docker-compose.yml
:
version: '3'
services:
alpine:
image: alpine
environment:
- "TZ=Europe/Amsterdam"
command: /bin/sh -c 'apk --no-cache add tzdata && date'
And i’ll finish with an example Dockerfile
for building your own image:
FROM alpine
ENV TZ Europe/Amsterdam
RUN apk --no-cache add tzdata
That’s it!