1. Causes

kubectl exec -it podName -n namespace /bin/sh.

When I entered the container and ran the date command, I found that the time zone is not UTC time zone, so the company logging system cannot collect logs and needs to change to UTC+8.

2. Solution

You need to change the Dockerfile to change the timezone when you build the image.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
FROM alpine:3.11.6

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

ENV TZ=Asia/Shanghai
RUN apk update \
    && apk add tzdata \
    && echo "${TZ}" > /etc/timezone \
    && ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
    && rm /var/cache/apk/*

...

My base image is alpine and I can use the above settings.

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories means use Ali’s mirror service, which can speed up the installation of tzdata, otherwise it will be very slow because of the network limitation in China.

3. Other systems

Debian-based

Just set the environment variables directly, tzdata is installed by default.

1
ENV TZ=Asia/Shanghai

Ubuntu-based

1
2
3
4
5
6
7
8
9
FROM ubuntu:bionic
 
ENV TZ=Asia/Shanghai
 
RUN echo "${TZ}" > /etc/timezone \
    && ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
    && apt update \
    && apt install -y tzdata \
    && rm -rf /var/lib/apt/lists/*