Caddy简介及配置

@admin  July 16, 2020

简介

Caddy is a powerful, extensible platform to serve your sites,services, and apps, written in Go. Although most people use it as a web server or proxy, it is an excellent choice for a:

主要功能

  • web server
  • reverse proxy
  • sidecar proxy
  • load balancer
  • API gateway
  • ingress controller
  • system manager
  • process supervisor
  • task scheduler
  • (any long-running process)

最新版本

caddy_2.1.1 (本文示例版本)

下载

由于centos是我的最爱,所以我就使用centos7来做示例了。你可以访问caddy官网或者直接去caddy github主页去选择适合你操作系统的版本,我这里直接下载编辑好的二进制文件(编译就留给golang大神来玩吧)。

[root@nginx software]#  wget https://github.com/caddyserver/caddy/releases/download/v2.1.1/caddy_2.1.1_linux_amd64.tar.gz

部署

[root@nginx software]# tar -zxvf caddy_2.1.1_linux_amd64.tar.gz
[root@nginx software]# mv caddy /usr/local/bin/
[root@nginx software]# which caddy
/usr/local/bin/caddy

是的,你没看错,解压并且mv一下就部署好了。

配置

新建运行用户及组

为了使其安全的运行(使用root运行服务是运维最低级的错误),我们为其专门的新建一个用户和组。

groupadd --system caddy
useradd --system \
    --gid caddy \
    --create-home \
    --home-dir /var/lib/caddy \
    --shell /usr/sbin/nologin \
    --comment "Caddy web server" \
    caddy

进程守护

毫无疑问,centos7中我们一般使用systemctl来对服务进程进行守护、管理。你可以复制下面的代码,也可以从caddy github下载caddy.service
保存caddy.service文件到/etc/systemd/system/下面:

# caddy.service
#
# For using Caddy with a config file.
#
# Make sure the ExecStart and ExecReload commands are correct
# for your installation.
#
# See https://caddyserver.com/docs/install for instructions.
#
# WARNING: This service does not use the --resume flag, so if you
# use the API to make changes, they will be overwritten by the
# Caddyfile next time the service is restarted. If you intend to
# use Caddy's API to configure it, add the --resume flag to the
# `caddy run` command or use the caddy-api.service file instead.

[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target

[Service]
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target

请注意在ExecStart附近的一个--config配置文件路径,需要将其改成你希望的位置。

   mkdir -p /etc/caddy/ && touch /etc/caddy/Caddyfile
   chown caddy.caddy -R /etc/caddy/Caddyfile

然后我们daemon-reload一下,让systemctl知道我们新加的caddy服务。

systemctl daemon-reload
systemctl enable caddy
systemctl start caddy # 此处启动会失败,因为我们还没有Caddyfile配置文件。

配置及使用

基础配置

caddy的配置文件有两种格式,一种是json格式,另一种是Caddyfile。但最终caddy读取的都是json格式。

json

[root@nginx caddy.pclc.net]# caddy run
2020/07/16 06:37:51.453    INFO    admin    admin endpoint started    {"address": "tcp/localhost:2019", "enforce_origin": false, "origins": ["localhost:2019", "[::1]:2019", "127.0.0.1:2019"]}
2020/07/16 06:37:51.453    INFO    serving initial configuration
[root@nginx caddy]# vim caddy.json
{
    "apps": {
        "http": {
            "servers": {
                "example": {
                    "listen": [":2015"],
                    "routes": [
                        {
                            "handle": [{
                                "handler": "static_response",
                                "body": "Hello, world!"
                            }]
                        }
                    ]
                }
            }
        }
    }
}

[root@nginx caddy]# curl localhost:2019/load -X POST -H "Content-Type: application/json" -d @caddy.json
[root@nginx caddy]# curl localhost:2019/config/
{"apps":{"http":{"servers":{"example":{"listen":[":2015"],"routes":[{"handle":[{"body":"Hello, world!","handler":"static_response"}]}]}}}}}
[root@nginx caddy]# curl localhost:2015
Hello, world![root@nginx caddy]# 

caddyfile

#### 单网站

[root@nginx caddy]# vim Caddyfile
# 单网站(单域名)
localhost # 不指定端口的话,caddy会默认监听80和443端口,并为https自定申请ssl证书。

file_server browse

[root@nginx caddy]# caddy adapt --config /etc/caddy/Caddyfile  # 转换配置为json格式
{"apps":{"http":{"servers":{"srv0":{"listen":[":443"],"routes":[{"match":[{"host":["localhost"]}],"handle":[{"handler":"subroute","routes":[{"handle":[{"browse":{},"handler":"file_server","hide":["/etc/caddy/Caddyfile"]}]}]}],"terminal":true}]}}}}}

[root@nginx caddy.pclc.net]# curl -I http://localhost # CURL访问测试
HTTP/1.1 308 Permanent Redirect
Connection: close
Location: https://localhost/
Server: Caddy
Date: Thu, 16 Jul 2020 06:46:42 GMT

#### 多网站

localhost{

file_server browse
}

caddy.pclc.net {
      root * /data/wwwroot/caddy.pclc.net
      encode zstd gzip # 配置压缩
      templates
      file_server browse
}
[root@nginx caddy]# caddy adapt --config /etc/caddy/Caddyfile 
{"apps":{"http":{"servers":{"srv0":{"listen":[":443"],"routes":[{"match":[{"host":["caddy.pclc.net"]}],"handle":[{"handler":"subroute","routes":[{"handle":[{"handler":"vars","root":"/data/wwwroot/caddy.pclc.net"},{"encodings":{"gzip":{},"zstd":{}},"handler":"encode"},{"handler":"templates"},{"browse":{},"handler":"file_server","hide":["/etc/caddy/Caddyfile"]}]}]}],"terminal":true},{"match":[{"host":["localhost{"]}],"handle":[{"handler":"subroute","routes":[{"handle":[{"browse":{},"handler":"file_server","hide":["/etc/caddy/Caddyfile"]}]}]}],"terminal":true}]}}}}}

   [root@nginx caddy]# caddy start # 启动
2020/07/16 06:50:27.344    INFO    using adjacent Caddyfile
2020/07/16 06:50:27.407    INFO    admin    admin endpoint started    {"address": "tcp/localhost:2019", "enforce_origin": false, "origins": ["[::1]:2019", "127.0.0.1:2019", "localhost:2019"]}
2020/07/16 06:50:27.409    INFO    http    server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS    {"server_name": "srv0", "https_port": 443}
2020/07/16 06:50:27.409    INFO    http    enabling automatic HTTP->HTTPS redirects    {"server_name": "srv0"}
2020/07/16 06:50:27 [INFO][cache:0xc000221320] Started certificate maintenance routine
2020/07/16 06:50:27.440    INFO    tls    cleaned up storage units
2020/07/16 06:50:27.441    INFO    http    enabling automatic TLS certificate management    {"domains": ["caddy.pclc.net"]}
2020/07/16 06:50:27.519    INFO    autosaved config    {"file": "/root/.config/caddy/autosave.json"}
2020/07/16 06:50:27.519    INFO    serving initial configuration
Successfully started Caddy (pid=17314) - Caddy is running in the background

使用curl测试网站是否正常访问。

[root@server ~]# curl https://caddy.pclc.net/
<!DOCTYPE html>
<html>
    <head>
        <title>Caddy tutorial</title>
    </head>
    <body>
<img src="./caddy.png" width="400" height="100">
         <p>您的IP为: 101.32.40.209</p>
         <p>您的UA为: curl/7.29.0</p>
[100MB caddy.png favicon.ico index.html]

        <p>Page loaded at: Thu Jul 16 06:51:09 CST 2020</p>
    </body>
</html>

    </body>
</html>

配置自动从 Git 拉取页面内容

git https://仓库地址 {
    path        网站目录
    hook        /webhook    验证密码
    hook_type   github # webhook的类型,github,gitlab
}

上述配置完成后,请记得到对应的仓库setting中配置webhook。

配置反向代理

localhost{

reverse_proxy 127.0.0.1:9000
}

其他参数配置:reverse-proxy

配置日志

访问日志

output file的文件必须要先创建,并且caddy得有写入权限。 官方关于log配置的指导:caddy log

localhost{

file_server browse
}

caddy.pclc.net {
      root * /data/wwwroot/caddy.pclc.net
      encode zstd gzip
      templates
      file_server browse
log {
      output file /var/log/access.log
}
}
[root@nginx log]# tailf access.log 
{"level":"info","ts":1594883230.1685061,"logger":"http.log.access.log0","msg":"handled request","request":{"method":"GET","uri":"/","proto":"HTTP/1.1","remote_addr":"101.32.40.209:48532","host":"caddy.pclc.net","headers":{"User-Agent":["curl/7.29.0"],"Accept":["*/*"]},"tls":{"resumed":false,"version":771,"ciphersuite":49196,"proto":"","proto_mutual":true,"server_name":"caddy.pclc.net"}},"common_log":"101.32.40.209 - - [16/Jul/2020:07:07:10 +0000] \"GET / HTTP/1.1\" 200 344","duration":0.001927815,"size":344,"status":200,"resp_headers":{"Content-Length":["344"],"Server":["Caddy"],"Content-Type":["text/html; charset=utf-8"]}}
{"level":"info","ts":1594883231.5895884,"logger":"http.log.access.log0","msg":"handled request","request":{"method":"GET","uri":"/","proto":"HTTP/1.1","remote_addr":"101.32.40.209:48534","host":"caddy.pclc.net","headers":{"Accept":["*/*"],"User-Agent":["curl/7.29.0"]},"tls":{"resumed":false,"version":771,"ciphersuite":49196,"proto":"","proto_mutual":true,"server_name":"caddy.pclc.net"}},"common_log":"101.32.40.209 - - [16/Jul/2020:07:07:11 +0000] \"GET / HTTP/1.1\" 200 344","duration":0.002053207,"size":344,"status":200,"resp_headers":{"Content-Type":["text/html; charset=utf-8"],"Content-Length":["344"],"Server":["Caddy"]}}
{"level":"info","ts":1594883239.4545298,"logger":"http.log.access.log0","msg":"handled request","request":{"method":"GET","uri":"/","proto":"HTTP/1.1","remote_addr":"173.82.226.7:55226","host":"caddy.pclc.net","headers":{"User-Agent":["curl/7.29.0"],"Accept":["*/*"]},"tls":{"resumed":false,"version":771,"ciphersuite":49196,"proto":"","proto_mutual":true,"server_name":"caddy.pclc.net"}},"common_log":"173.82.226.7 - - [16/Jul/2020:07:07:19 +0000] \"GET / HTTP/1.1\" 200 343","duration":0.000931427,"size":343,"status":200,"resp_headers":{"Server":["Caddy"],"Content-Type":["text/html; charset=utf-8"],"Content-Length":["343"]}}
{"level":"info","ts":1594883241.5982244,"logger":"http.log.access.log0","msg":"handled request","request":{"method":"GET","uri":"/","proto":"HTTP/1.1","remote_addr":"173.82.226.7:55228","host":"caddy.pclc.net","headers":{"Accept":["*/*"],"User-Agent":["curl/7.29.0"]},"tls":{"resumed":false,"version":771,"ciphersuite":49196,"proto":"","proto_mutual":true,"server_name":"caddy.pclc.net"}},"common_log":"173.82.226.7 - - [16/Jul/2020:07:07:21 +0000] \"GET / HTTP/1.1\" 200 343","duration":0.000867572,"size":343,"status":200,"resp_headers":{"Content-Length":["343"],"Server":["Caddy"],"Content-Type":["text/html; charset=utf-8"]}}

参考资料:

  • 官方文档: 2.0

添加新评论

  1. 来不及解释了!快上车!!!

    Reply
  2. 听说做这个的都赚钱了

    Reply