1.直接挂载宿主机 /etc/localtime 和 /etc/timezone
1 2 3 4 5 6
| services: app: image: myapp:latest volumes: - /etc/localtime:/etc/localtime:ro - /etc/timezone:/etc/timezone:ro
|
:ro 表示只读挂载,防止容器修改宿主机时间。
- 这样容器会使用宿主机的时区和时间。
2.使用环境变量指定时区
1 2 3 4 5
| services: app: image: myapp:latest environment: - TZ=Asia/Shanghai
|
- 设置时区环境变量,让应用按本地时区显示时间。
- 注意:容器内系统时间仍然可能与宿主机略有差异,但应用层时间是对的。
3.使用 host 网络时间(NTP 同步)
如果容器时间和宿主机差距较大,可以在容器内安装 chrony 或 ntp,同步时间:
1 2
| apt-get update && apt-get install -y chrony chronyd -q "server time.google.com iburst"
|
- 推荐 生产环境不依赖容器自同步,直接挂载宿主机时间最稳。