一、安装caddy
官方安装示例:https://caddyserver.com/docs/install
中文网:https://caddy2.dengxiaolong.com/docs/ 或 https://caddyserver.com.cn/
1. 更新系统
在安装 Caddy 之前,确保系统是最新的:
sudo apt update sudo apt upgrade -y
2. 安装必要的依赖
安装一些必要的工具和依赖项:
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
3. 添加 Caddy 的 GPG 密钥和官方仓库
运行以下命令添加 Caddy 的 GPG 密钥和仓库:
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
4. 安装 Caddy
更新包列表并安装 Caddy:
sudo apt update sudo apt install caddy -y
5. 验证安装
安装完成后,检查 Caddy 是否安装成功:
caddy version
6. 启动和启用 Caddy 服务
启动 Caddy 并设置为开机自启动:
sudo systemctl start caddy sudo systemctl enable caddy
7. 配置 Caddy
Caddy 的配置文件通常位于 /etc/caddy/Caddyfile。您可以编辑该文件来设置您的站点。例如:
abc.yuming.net {
# Set this path to your site's directory.
root * /root/wwwroot/abc.yuming.net #应用路径
# Enable the static file server.
file_server
# Another common task is to set up a reverse proxy:
reverse_proxy http://localhost:50051 {
header_up X-Forwarded-For {remote_host} #服务端获取真实ip
header_up X-Forwarded-Proto {scheme} #服务端获取真实协议
}
encode zstd gzip #启用zstd和gzip压缩
}
保存后重新加载 Caddy 配置:
sudo systemctl reload caddy
其他常用命令
sudo systemctl stop caddy # 关闭caddy服务 sudo systemctl restart caddy # 重启caddy服务 sudo systemctl start caddy # 启动caddy服务 sudo systemctl status caddy # 查看caddy服务状态 sudo caddy run --config /etc/caddy/Caddyfile # 以指定配置文件进行启动
二、asp.net core应用设置开机自启动
参考:https://www.cnblogs.com/fireicesion/p/18778690
三、asp.net core搭配caddy使用的其他事项
1. 给应用目录设置写入权限(不设置上传图片和写入日志会失败)
开机启动服务中设置了默认用户为www-data,需要给www-data赋予写入应用目录的权限
检查目录权限:
#查看目录权限 ls -l /path/to/app_directory #确保目录对运行 Caddy 或应用程序的用户具有写入权限。 #例如,Caddy 默认运行用户是 www-data,更新权限如下: sudo chown -R www-data:www-data /path/to/app_directory sudo chmod -R 775 /path/to/app_directory
2. 写入caddy代理日志
abc.yuming.net {
# Set this path to your site's directory.
root * /root/wwwroot/abc.yuming.net #应用路径
# Enable the static file server.
file_server
# Another common task is to set up a reverse proxy:
reverse_proxy http://localhost:50051 {
header_up X-Forwarded-For {remote_host} #服务端获取真实ip
header_up X-Forwarded-Proto {scheme} #服务端获取真实协议
}
encode zstd gzip #启用zstd和gzip压缩
log {
output file /root/wwwroot/abc.yuming.net/caddy/access.log # 指定日志文件路径
format json # 日志格式为 JSON,可改为 console
}
}
确保日志文件路径对 Caddy 的运行用户(通常是 www-data)具有写入权限:
sudo chown www-data:www-data /root/wwwroot/abc.yuming.net/caddy/access.log sudo chmod 664 /root/wwwroot/abc.yuming.net/caddy/access.log
3. 查看应用控制台输出
假设您的服务文件名称为 myapp.service,运行以下命令:
sudo journalctl -u myapp.service -f
-
-u myapp.service:指定服务名称。
-
-f:实时查看日志(类似于 tail -f)。
浙公网安备 33010602011771号