How to Keep Docker Containers in Sync with Host Timezone
This guide explains why Docker containers default to UTC, then walks through three practical ways—mounting host timezone files, setting the TZ environment variable, and using timedatectl or scripts—to ensure container time matches the host for reliable logging and scheduling.
Why Timezone Synchronization Matters
In containerized deployments, matching the container's timezone with the host's is essential for accurate log timestamps, scheduled tasks, and overall application stability. By default Docker runs containers in UTC, which can cause mismatches with host services.
Method 1: Mount Host Timezone Files
Map the host's /etc/localtime and /etc/timezone into the container so it inherits the same settings.
docker run -v /etc/localtime:/etc/localtime:ro -v /etc/timezone:/etc/timezone:ro -d centos:7Docker Compose example:
version: '3.3'
services:
your_service:
image: centos:7
volumes:
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:roMethod 2: Use the TZ Environment Variable
Set TZ in a Dockerfile or docker‑compose.yml for more flexibility, especially in multi‑timezone deployments.
FROM ubuntu
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezoneCompose version:
version: '3.3'
services:
your_service:
image: ubuntu
environment:
- TZ=Asia/ShanghaiUsing timedatectl on the Host
The timedatectl command lets you view and change the system timezone on Linux (e.g., CentOS). timedatectl | grep "Time zone" Set a new timezone:
sudo timedatectl set-timezone Asia/ShanghaiDynamic Timezone Setting in Scripts
For automation scripts, you can read a configuration file and export TZ at runtime.
#!/bin/bash
# Assume timezone_config.txt contains a timezone string
TIMEZONE=$(cat timezone_config.txt)
export TZ=$TIMEZONE
echo "Current time: $(date)"This approach makes scripts configurable and adaptable to different user or regional preferences.
Conclusion
Properly configuring timezone settings for containers and the host ensures consistent behavior, simplifies log management, and helps applications run reliably across global environments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
