记录一起Caddy由于无法绑定80、443端口导致的服务启动失败事故

常规方法安装完Caddy,写好Caddyfile和systemd服务配置文件后sudo systemctl start caddy,结果发现在获取证书时失败,导致整个服务启动失败:

failed to obtain certificate: acme: Error -> One or more domains had a problem:

Mar 05 09:55:48 instance-2 caddy[1846]: [ mydomain.example.com ] [ mydomain.example.com ] acme: error presenting token: presenting with standard provider server: could not start HTTPS server for challenge -> listen tcp :443: bind: permission denied

开始以为是 setcap 的问题,但是检查过后,发现安装时的设置没问题:

getcap /usr/local/bin/caddy
/usr/local/bin/caddy = cap_net_bind_service+ep

而且直接命令行启动也没有问题,那么看来应该是systemd服务配置中的问题,一番搜索后发现了这个:Caddy won’t start – Could not start HTTP server for challenge -> listen tcp :80: bind: permission denied ,参考问题中的解决方法,修改caddy.service配置为:

[Unit]
Description=Caddy HTTP/2 web server
Documentation=https://caddyserver.com/docs
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service

[Service]
Restart=on-abnormal

; User and group the process will run as.
User=caddy
Group=caddy

; Letsencrypt-issued certificates will be written to this directory.
Environment=CADDYPATH=/etc/ssl/caddy

; Always set "-root" to something safe in case it gets forgotten in the Caddyfile.
ExecStart=/usr/local/bin/caddy -log stdout -agree=true -conf=/etc/caddy/Caddyfile -root=/var/tmp
ExecReload=/bin/kill -USR1 $MAINPID

; Use graceful shutdown with a reasonable timeout
KillMode=mixed
KillSignal=SIGQUIT
TimeoutStopSec=5s

; Limit the number of file descriptors; see `man systemd.exec` for more limit settings.
LimitNOFILE=1048576
; Unmodified caddy is not expected to use more than that.
LimitNPROC=512

; Use private /tmp and /var/tmp, which are discarded after caddy stops.
PrivateTmp=true
; Use a minimal /dev
PrivateDevices=true
; Hide /home, /root, and /run/user. Nobody will steal your SSH-keys.
ProtectHome=true
; Make /usr, /boot, /etc and possibly some more folders read-only.
ProtectSystem=full
; … except /etc/ssl/caddy, because we want Letsencrypt-certificates there.
;   This merely retains r/w access rights, it does not add any new. Must still be writable on the host!
ReadWriteDirectories=/etc/ssl/caddy

; The following additional security directives only work with systemd v229 or later.
; They further retrict privileges that can be gained by caddy. Uncomment if you like.
; Note that you may have to add capabilities required by any plugins in use.
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

也就是打开这三行原来的注释:

CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

然后,sudo systemctl daemon-reload,再次启动服务,一切正常!

博主友情提示:

如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。