Perfect solution to Docker Alpine mirrored time zone problem

  • 2021-10-27 09:49:19
  • OfStack

Recently, when using Docker to deploy Java application, it was found that the time zone was wrong, and using jdk to obtain the current time was 8 hours slow, using the standard time zone

Solution:

Scenario 1. Modify Dockerfile

Setting Alpine linux System Time Zone Looking up the documentation of alpine linux, we know that the time zone can be set by tzdata package. When building docker image, Dockerfile adds this sentence:


RUN apk --update add tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    apk del tzdata && \
    rm -rf /var/cache/apk/*

Complete Dockerfile


FROM openjdk:8-jre-alpine3.9

RUN apk --update add tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    apk del tzdata && \
    rm -rf /var/cache/apk/*

# copy the packaged jar file into our docker image
COPY application.jar /application.jar

Document link:

wiki. alpinelinux. org/wiki/Settin …

Scenario 2. Set the system default time zone for JVM

When starting Docker mirroring, set the time zone by setting the user. timezone JVM environment variable


java -jar -Duser.timezone=Asia/Shanghai app.jar

Scenario 3. Mount the host's time zone file into the Docker container

The cluster scheme uses K8S, and the host's time zone file is mounted into the Docker container during deployment


apiVersion: apps/v1
kind: Deployment
metadata:
  name: SERVICE_NAME
spec:
  replicas: 1
  selector:
    matchLabels:
      app: SERVICE_NAME
  template:
    metadata:
      labels:
        app: SERVICE_NAME
    spec:
      containers:
      - name: SERVICE_NAME
        image: IMAGE_TAG
        imagePullPolicy: Always
        ports:
        - containerPort: 80
      	volumeMounts:
        - name: tz-config
          mountPath: /etc/localtime
      volumes:
      - name: tz-config
        hostPath:
           path: /etc/localtime

Check to see if it is running normally


date -R

Reference documentation:

quaded. com/docker-apli …

blog. csdn. net/jeikerxiao/…


Related articles: