はじめに
ローカルの開発環境でテストしたアプリをコンテナ化した際に、時刻の処理でズレが出てしまっていた。 開発環境がAsia/Tokyoで、コンテナがUTCだったことが原因。 その時の調査内容をメモしておく。
Linuxにおけるタイムゾーンについて
こちらが分かりやすい。
普通、コンテナ内はどうなっているか
今回検証で利用したコンテナイメージは以下の通り。
- debian:12.6
- debian:12.6-slim
- ubuntu:24.04
- redhat/ubi9:9.4
- alpine:3.20.1
- python:3.12.4-bookworm
- python:3.12.4-slim-bookworm
そして、以下のスクリプトを実行して、各コンテナでタイムゾーンの設定がどうなっているかを確認する。
#!/bin/bash IMAGES=( "debian:12.6" "debian:12.6-slim" "ubuntu:24.04" "redhat/ubi9:9.4" "alpine:3.20.1" "python:3.12.4-bookworm" "python:3.12.4-slim-bookworm" ) SCRIPT=$(cat << 'EOS' echo " $(LANG=C date)" for FILEPATH in /etc/localtime /etc/timezone /usr/share/zoneinfo; do RESULT="not exist" test -e ${FILEPATH} && RESULT="exists" echo " ${FILEPATH} ${RESULT}" done EOS ) echo "host machine ($(source /etc/os-release; echo ${PRETTY_NAME}))" /bin/sh -c "${SCRIPT}" for IMAGE in "${IMAGES[@]}" ; do echo "${IMAGE}" docker run --tty --rm ${IMAGE} /bin/sh -c "${SCRIPT}" done
実行結果は以下の通り。
host machine (Ubuntu 24.04 LTS) Mon Jul 8 23:39:01 JST 2024 /etc/localtime exists /etc/timezone exists /usr/share/zoneinfo exists debian:12.6 Mon Jul 8 14:39:01 UTC 2024 /etc/localtime exists /etc/timezone exists /usr/share/zoneinfo exists debian:12.6-slim Mon Jul 8 14:39:01 UTC 2024 /etc/localtime exists /etc/timezone exists /usr/share/zoneinfo exists ubuntu:24.04 Mon Jul 8 14:39:02 UTC 2024 /etc/localtime not exist /etc/timezone not exist /usr/share/zoneinfo not exist redhat/ubi9:9.4 Mon Jul 8 14:39:02 UTC 2024 /etc/localtime exists /etc/timezone not exist /usr/share/zoneinfo exists alpine:3.20.1 Mon Jul 8 14:39:02 UTC 2024 /etc/localtime not exist /etc/timezone not exist /usr/share/zoneinfo not exist python:3.12.4-bookworm Mon Jul 8 14:39:02 UTC 2024 /etc/localtime exists /etc/timezone exists /usr/share/zoneinfo exists python:3.12.4-slim-bookworm Mon Jul 8 14:39:03 UTC 2024 /etc/localtime exists /etc/timezone exists /usr/share/zoneinfo exists
ここで調べた範囲のコンテナイメージでは、明確にUTCと設定されているか、設定がないためにUTCに倒れている(はず)。 公開されているコンテナイメージのタイムゾーンは、おおよそUTCであると思われる。
タイムゾーンについての考察
仮想マシンやクラウドが普及する前は、リモートであっても比較的近い場所(国内)の物理マシンの利用が普通だったので、マシンそのものにタイムゾーンを設定するのが妥当だった。
しかし、今では利用するマシンは地理的にどこに配置されているかは重要ではないので、特にコンテナのようなサーバではタイムゾーンはUTCのままにしておいて、アプリケーションで任意のタイムゾーンを設定できるようにしておけばよいと思う。
SaaSのようなどこの国からでもアクセスされるようなものは、タイムゾーンはユーザごとの設定として持つように設計すべきだろう。