文章目录
  1. 1. 编译 coredns
  2. 2. 升级golang
  3. 3. 交叉编译与优化

在项目中使用了coredns来作为简单的DNS服务器, 已经能通过file插件在Corefile中来自定义子域名的A地址记录。最近需要实现程序新增DNS记录的功能,于是乎查找coredns plugin列表,选择redis插件 。但是, redis为非coredns自带插件, 需要重新编译coredns。

编译 coredns

先从github下载代码

1
2
git clone https://github.com/coredns/coredns
cd coredns

编辑coredns代码目录下plugin.cfg文件,添加插件

1
echo 'redis:github.com/codysnider/coredns-redis' >> plugin.cfg

注意: 插件的添加与调用顺序有关,通过测试发现redis插件一直不生效,调整至file插件之前就起作用了。

编译过程使用的命令如下,需要从github下载一列依赖的包

1
2
3
4
5
# 获取插件代码
go get github.com/codysnider/coredns-redis
# 编译
go generate
go build

在编译过程中遇到报错note: module requires Go 1.19, 原因是golang版本太低,需要升级golang版本;另外是在windows系统下编译linux使用的包, 需要指定交叉编译环境变量。于是最终使用的命令如下:

1
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go1.21.5 build

参考:

  1. coredns github:https://github.com/coredns/coredns
  2. coredns 编译时启用插件 https://coredns.io/2017/07/25/compile-time-enabling-or-disabling-plugins/
  3. redis 插件: https://coredns.io/explugins/redis/

升级golang

golang是支持多个版本同时存在, 使用时程序命令后会多出版本号。 安装golang程序,如同安装golang的库一样。

1
2
3
go install golang.org/dl/go1.21.5@latest
go1.21.5 download
go1.21.5 version

参考:

  1. https://go.dev/doc/manage-install
  2. https://go.dev/dl/
  3. https://www.cnblogs.com/pebblecome/p/14815365.html

交叉编译与优化

  1. windows下交叉编译linux下使用的程序,设置环境变量: CGO_ENABLED=0 GOOS=linux GOARCH=amd64. 另外GOOS可根据目标执行平台,指定为windows或者darwin
  2. 优化二进制输出文件大小,可以在build后添加参数-ldflags="-s -w"。通过命令CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go1.21.5 build -ldflags="-s -w" 重新编译,输出的coredns程序从开始的80M,减小为50M,效果还是很明显的。
文章目录
  1. 1. 编译 coredns
  2. 2. 升级golang
  3. 3. 交叉编译与优化