티스토리 뷰

golang

Golang: timezone 설정하기

주먹불끈 2023. 6. 11. 23:59

개요

Golang Docker container 내에서 timezone을 한국으로 하고 싶다.

이를 위해서는

  1. 원하는 timezone을 로드한 다음, 설정을 하면 되는데
  2. 경량 이미지라면 timezone data를 이미지에 추가해줘야 한다.

구현

Local time 설정하기

실행 코드: https://goplay.tools/snippet/jsxRaDEqQeY

  1. time.LoadLocation 으로 timezone을 로드해서
  2. time.Local 에 설정하면 KST 로 나오는 것을 알 수 있다.
package main

import (
	"fmt"
	"time"
)

func main() {
	// Load the Seoul timezone
	currentTime := time.Now()
	fmt.Println("Current time", currentTime)

	location, err := time.LoadLocation("Asia/Seoul")
	if err != nil {
		panic(err)
	}

	// Set the timezone for the current process
	time.Local = location

	// Get the current time in the set timezone
	currentTime = time.Now()
	fmt.Println("Current time", currentTime)
}

// Current time 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
// Current time 2009-11-11 08:00:00 +0900 KST m=+0.000000001

timezone data

time.LoadLocation 은 OS의 tzdata에서 정보를 가져오는데 경량 이미지를 사용하면 이 정보마저 없기에 에러가 발생한다.

Dockerfile 에서 이미지를 만들 때에 tzdata를 설치하면 이 문제가 해결된다.

# Stage 1: Build the Go application 
FROM golang:1.20.2-alpine AS build

WORKDIR /app
COPY  . .
RUN go build -o myapp

# Stage 2 - Create a minimal image to run the application
FROM alpine:latest

**## Install tzdata
RUN apk --no-cache add tzdata**
 
COPY --from=build /app/myapp /myapp
CMD ["/myapp"]
반응형
반응형
잡학툰 뱃지
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함