Docker镜像时区设置

alpine系统时区设置

咱们先使用docker run -it --name alpine_test --rm alpine:3.9 sh命令启动一个alpine系统。python

查看系统时间:linux

# echo $TZ

# date
Mon Mar 11 10:47:20 UTC 2019
复制代码

看到默认时间为UTC时间,比北京时间晚8个小时。nginx

先安装**tzdata*包:git

apk add --no-cache tzdata
复制代码

而后有下面2种方式设置时区:github

  1. 设置TZ环境变量
export TZ="Asia/Shanghai"
# echo $TZ
Asia/Shanghai
# date
Mon Mar 11 18:48:30 CST 2019
复制代码

注意,这种方式只对当前终端有效。能够使用docker exec进行检查。docker

  1. 修改本地时间
# date
Mon Mar 11 11:48:56 UTC 2019
# ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# date
Mon Mar 11 18:49:02 CST 2019
复制代码

从nginx-alpine镜像的dockerfile也能够看到这种处理方式:bash

# Bring in tzdata so users could set the timezones through the environment
# variables
&& apk add --no-cache tzdata
复制代码

alpine镜像扩展

既然知道如何设置alpine系统时间,咱们能够这样编写镜像文件dockerfile:ui

FROM alpine:3.9
RUN apk add --no-cache tzdata
复制代码

而后编译镜像docker build . -f Dockerfile -t alpine-ext:0.0.1云计算

使用docker run -it --rm -e TZ=Asia/Shanghai alpine-ext:0.0.1 sh命令,而后执行date结果为Mon Mar 11 20:11:16 CST 2019;使用docker run -it --rm -e TZ=Asia/Bangkok alpine-ext:0.0.1 sh命令,而后执行date结果为Mon Mar 11 19:12:16 +07 2019。曼谷时间比北京时间晚1个小时,这样能够看到2个时间都正确。spa

这种方式还展现了能够在运行时指定时区。

另外若是确认代码不存在国际化需求,也能够直接将时区定义固定为CST:

FROM alpine
RUN apk add --no-cache tzdata \
    && ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo "Asia/Shanghai" > /etc/timezone
ENV TZ Asia/Shanghai
复制代码

应用程序时间示例

咱们选择go语言实现:gotime.go,代码以下:

package main

import (
	"fmt"
	"time"
)

func main() {
	currentTime:=time.Now()
	fmt.Printf("%12s: %s\n", "currentTime",currentTime)
	curNow:=currentTime.Local()
	fmt.Printf("%12s: %s\n", "localTime",curNow)
	name, offset := currentTime.Zone()
	fmt.Printf("%12s: %s\n","timeZone",name)
	fmt.Printf("%12s: %d\n","offset",offset)
	fmt.Printf("%12s: %s\n","UTCTime",currentTime.UTC())
	timeUnix:=currentTime.Unix()
	fmt.Printf("%12s: %d\n","unixTime",timeUnix)
}
复制代码

使用go build gotime.go命令获得gotime

若是是在mac上编译,编译命令须要调整成: GOOS=linux GOARCH=amd64 go build gotime.go,即编译为linux 64位程序。

先使用docker run -it --rm -e TZ=Asia/Shanghai --name=alpine_test alpine-ext:0.0.1 sh命令启动容器。而后经过docker cp go/src/gotime alpine_test:/复制gotime到容器中,校验:

# date 
Mon Mar 11 18:12:05 CST 2019
# ./gotime 
 currentTime: 2019-03-11 18:12:19.131226991 +0800 CST m=+0.000535254
   localTime: 2019-03-11 18:12:19.131226991 +0800 CST
    timeZone: CST
      offset: 28800
     UTCTime: 2019-03-11 10:12:19.131226991 +0000 UTC
    unixTime: 1552299139
复制代码

从结果看,应用程序获取到正确时间。

插句题外话,go适合云计算的特性在这里完美展示出来。其它语言好比python,只可以换成python:3.7-alpine这样的镜像,而go能够独立运行,编译后copy到alpine镜像便可运行,因此镜像会很是小。

最后咱们能够获得下面结论:

安装了tzdata包的docker镜像,均可以使用环境变量TZ=Asia/Shanghai方式调整时区。

相关文章
相关标签/搜索