公司有些内网服务需要使用域名访问,安装bind比较麻烦,故使用coredns实现域名服务。

IP说明
192.168.0.41安装dns,作为dns服务器
192.168.0.20测试服务器

安装

有docker和预编译二进制文件等更多方式,这里采用预编译二进制文件进行安装。

下载地址:https://github.com/coredns/coredns/releases

运行

  1. 编写配置文件 Corefile
.:53 {
    # 绑定本机IP
    bind 192.168.0.41
    # 因为需要用域名的服务比较少,这里就直接使用hosts方式。
    # 如果需要配置大量域名,建议使用文件方式
    hosts {
        192.168.0.41 web.local.com
        ttl 60
        reload 1m
        fallthrough
    }
    # 最后所有的都转发到系统配置的上游dns服务器去解析
    forward . /etc/resolv.conf
    # 缓存时间ttl
    cache 120
    # 自动加载配置文件的间隔时间
    reload 6s
    # 输出日志
    log
    # 输出错误
    errors
}
  1. 运行。这里写了脚本来启动

目录结构如下:

├── bin
│   ├── coredns
│   └── start.sh
├── conf
│   └── Corefile
└── logs
    └── start.log

启动脚本示例(注意,因为默认监听53端口,所以需要使用root用户启动)

#!/bin/bash
# description: 启动CoreDNS
set -u
scriptDir=$(cd $(dirname $0) && pwd)
baseDir=$(cd ${scriptDir}/.. && pwd)
pidFile=${baseDir}/logs/app.pid
function prepare(){
    # 检查当前用户是否为root
    if [[ $(whoami) != "root" ]]; then
        echo "please use root privilege"
        exit 1
    fi
    # 检查是否存在配置文件, 无则报错退出
    if [[ ! -f ${baseDir}/conf/Corefile ]]; then
        echo "${baseDir}/conf/Corefile not found"
        exit 1
    fi
    
    # 检测是否存在日志目录, 无则创建
    if [[ ! -d ${baseDir}/logs ]]; then
        mkdir -p ${baseDir}/logs
    fi
    
    # 检查进程是否已存在, 存在则退出
    ps -ef | grep -v grep | grep ${scriptDir}/coredns > /dev/null
    if [[ $? -eq 0 ]]; then
        echo "coredns is running"
        exit 1
    fi
}
function startApp(){
    nohup ${scriptDir}/coredns --conf ${baseDir}/conf/Corefile \
        -pidfile ${pidFile} > ${baseDir}/logs/start.log 2>&1 &
}
function check(){
    # 检查是否正常启动
    for i in $(seq 2); do
        echo "checking coredns whether is running or not ..."
        sleep 1
    done
    ps -ef | grep -v grep | grep ${scriptDir}/coredns > /dev/null
    if [[ $? -eq 0 ]]; then
        echo "coredns is running"
    fi
}
function main(){
    prepare
    startApp
    check
}
main
  1. 启动
./start.sh

测试

  1. 修改测试服务器的/etc/resolv.conf,示例:
nameserver 192.168.0.41
  1. ping测试
ping -c4 web.local.com
ping -c4 www.baidu.com
  1. 如果上一步都正常响应的话,则说明成功。

更多推荐