iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0
Modern Web

BeeGo系列 第 20

Docker

今天我們來試著打包為 docker image 吧。

之前我們所安裝的 bee 工具,就可以幫我們產生 Dockerfile 。

bee dockerize

產生出來的 Dockerfile 內容。

FROM library/golang

# Godep for vendoring
RUN go get github.com/tools/godep

# Recompile the standard library without CGO
RUN CGO_ENABLED=0 go install -a std

ENV APP_DIR $GOPATH/src/github.com/elleryq/ithome-iron-beego
RUN mkdir -p $APP_DIR

# Set the entrypoint
ENTRYPOINT (cd $APP_DIR && ./ithome-iron-beego)
ADD . $APP_DIR

# Compile the binary and statically link
RUN cd $APP_DIR && CGO_ENABLED=0 godep go build -ldflags '-d -w -s'

EXPOSE 8080

試著用 docker build 來建置 docker image,會出現幾個問題:

  1. 說找不到 git 這個指令
  2. 建置時,有 import 路徑問題

找不到 git 指令,可以在 Dockerfile 前面加上 apk add 來解決。

RUN apk add --no-cache git

import 路徑問題,就比較麻煩一些了。之前便宜行事,並沒有依照 GO 的慣例來擺放專案原始碼。那現在我們做調整,因為專案是放在 github,所以把原來 $GOPATH/src/my/hello 改放到 $GOPATH/src/github.com/elleryq/ithome-iron-beego ,接著將程式裡用到 import "my/hello" 的部份,都修改為 import "github.com/elleryq/ithome-iron-beego"

調整完之後,要處理模組的部份,我們期望在建置 docker image 時,會自動去安裝專案所需要的模組,然後再建置。GO 1.11 已經釋出 go modules,我們就用 go mod init 來產生 go.mod,用 go build 生成 go.sum。產生以後,要把 go.mod / go.sum 加到 git repository 裡。

# 產生 go.mod
go mod init github.com/elleryq/ithome-iron-beego

# 在建置過程會更新 go.mod 並產生 go.sum
# 在完成後,把 go.mod / go.sum 加入 git repository
go build

處理完這兩個問題以後,我們重新調整一下 Dockerfile

# 改用 alpine 當基底,縮減 docker image 的大小
FROM golang:1.13-alpine

# 加入 git
RUN apk add --no-cache git

# Recompile the standard library without CGO
RUN CGO_ENABLED=0 go install -a std

ENV APP_DIR /app
RUN mkdir -p $APP_DIR

# Set the entrypoint
ENTRYPOINT (cd $APP_DIR && ./ithome-iron-beego)
ADD . $APP_DIR

# Compile the binary and statically link
RUN cd $APP_DIR && CGO_ENABLED=0 go build -ldflags '-d -w -s'

EXPOSE 8080

調整完,進行建置,現在我們已經有 docker image,並且可以用 docker 執行啦。

docker build -t elleryq/ithome-iron-beego:0.1.0
docker run --name beego-mysql -e MYSQL_DATABASE=hellodb -e MYSQL_ROOT_PASSWORD=my-secret-pw -p 3306:3306 -d mysql:5.7
docker run -p 8080:8080 -e ORM_DRIVER=mysql -e "ORM_SOURCE=root:my-secret-pw@tcp(beego-mysql:3306)/hellodb?charset=utf8" --link beego-mysql elleryq/ithome-iron-beego:0.1.0

參考資料


上一篇
Logging
下一篇
Health check
系列文
BeeGo30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言