Set a time zone for a container

更新时间:
复制 MD 格式

This topic describes how to configure a time zone for a container. This ensures that the time in the container is consistent with the local time and helps prevent data consistency and accuracy issues.

Configuration example

  1. Create a ConfigMap and import the time zone that you want to use.

    The following command is an example. For other time zones, you can use the corresponding file from the /usr/share/zoneinfo/ folder.

    kubectl create configmap tz --from-file=/usr/share/zoneinfo/Asia/Shanghai
  2. Create an application to set the time zone.

    kubectl apply -f set-timezone.yaml

    The following is an example of the set-timezone.yaml file:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: timezone
      labels:
        app: test
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          name: timezone
          labels:
            app: nginx
            alibabacloud.com/eci: "true" 
        spec:
          containers:
          - name: timezone
            image: registry.cn-shanghai.aliyuncs.com/eci_open/nginx:1.14.2
            volumeMounts:
              - name: tz
                mountPath: /etc/localtime   # Mount path
                subPath: Shanghai       # Replace with the time zone file name from your ConfigMap
          volumes:
            - name: tz
              configMap:   # Mount the ConfigMap
                name: tz  

Verify the result

Log in to the container and verify that the time zone is set.

  1. Retrieve the pod information.

    kubectl get pod

    The following output is an example:

    NAME                        READY   STATUS    RESTARTS   AGE
    timezone-77cc64c57d-h59n8   1/1     Running   0          6
  2. Access the container.

    Run the following command. Replace <pod-name> with the name of your pod.

    kubectl exec -it <pod-name> -- sh
  3. Check the time zone of the container.

    date -R

    If the returned time matches the configured time zone, the time zone is set successfully. The following output is an example:

    Mon, 19 Feb 2024 17:24:00 +0800