使用docker部署一个带配置文件的golang项目


配置文件放docker内只做为举例,实际并不推荐,建议用配置文件统一管理。

首先看下我这的目录结构

使用docker部署一个带配置文件的golang项目
我这的gopath为 gowork目录
使用docker部署一个带配置文件的golang项目

编写dockerfile

首先编译main.go 生成二进制文件,该二进制文件可以直接在相应的linux服务器下运行。
我这里使用如下指令,编译后会多出一个main文件

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go

可以根据自己需要编译的平台更改
使用from加入母镜像 这里使用scratch空镜像,因为编译后的main是可以直接运行的

FROM scratch

MAINTAINER指定维护者信息
WORKDIR .这里使用当前目录作为工作目录,可以修改
将main 与 test.toml 配置文件 放入当前目录
EXPOSE 这是对方开发的端口,可修改,我这使用8082
CMD 附带配置文件test.toml 运行当前目录下的main

MAINTAINER  "hcf"

WORKDIR .
ADD main .
ADD test.toml .

EXPOSE 8082
CMD ["./main","-config=./test.toml"]

容器的配置就完成了

生成镜像

在dockerfile目录运行

docker build -t dockertest .

使用docker部署一个带配置文件的golang项目
successfully built 构建成功

使用

docker images

查看刚生成的镜像
使用docker部署一个带配置文件的golang项目
运行镜像

docker run -p 8082:8082 dockertest

使用docker部署一个带配置文件的golang项目
使用docker部署一个带配置文件的golang项目
成功运行,页面输入http://localhost:8082/ 成功访问

完整文件代码

config.go

package config

import (
	"github.com/BurntSushi/toml"
)

// Config 对应配置文件结构
type Config struct {
	Listen string `toml:"listen"`
}

// UnmarshalConfig 解析toml配置
func UnmarshalConfig(tomlfile string) (*Config, error) {
	c := &Config{}
	if _, err := toml.DecodeFile(tomlfile, c); err != nil {
		return c, err
	}
	return c, nil
}

// GetListenAddr 监听地址
func (c Config) GetListenAddr() string {
	return c.Listen
}

main.go

package main

import (
	"flag"
	"net/http"

	"test/dockertest/config"

	"github.com/gin-gonic/gin"
	"github.com/go-xweb/log"
)

var (
	tomlFile = flag.String("config", "test.toml", "config file")
)

func indexHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"data": "docker test",
	})
}

func main() {
	flag.Parse()
	// 解析配置文件
	tomlConfig, err := config.UnmarshalConfig(*tomlFile)
	if err != nil {
		log.Errorf("UnmarshalConfig: err:%v\n", err)
		return
	}
	router := gin.New()
	router.GET("/", indexHandler)
	router.Run(tomlConfig.GetListenAddr())
}

test.toml

listen = ":8082"

dockerfile

FROM scratch

MAINTAINER  "hcf"

WORKDIR .
ADD main .
ADD test.toml .

EXPOSE 8082
CMD ["./main","-config=./test.toml"]

谢谢支持 附上git地址

https://github.com/516134941/docker-golang-demo 如果觉得有帮助可以star一下