Recently, WHEN DEPLOYING Java applications with Docker, I found that the time zone was not correct. The current time obtained by JDK was 8 hours late and the standard time zone was used
Solutions:
Solution 1. Modify the Dockerfile
The tzdata package is available in Alpine Linux to set the time zone. The Dockerfile is used to set the time zone in Alpine Linux.
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 code
The 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
Copy the code
Document links:
Wiki.alpinelinux.org/wiki/Settin…
Option 2. Set the default system time zone for the JVM
When starting the Docker image, set the timezone by setting the user.timezone JVM environment variable
java -jar -Duser.timezone=Asia/Shanghai app.jar
Copy the code
Solution 3. Mount the host’s time zone file into the Docker container
The cluster solution uses K8S, which mounts the host’s time zone file 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
Copy the code
Check whether the system runs normally
date -R
Copy the code
Reference Documents:
Quaded.com/docker-apli…
Blog.csdn.net/jeikerxiao/…