在 Homebrew 中,homebrew/services 是一个扩展插件(Tap),它允许用户通过 Homebrew 方便地管理 macOS 上的后台服务(如 MySQL、Nginx、PostgreSQL 等)。它基于 macOS 的 launchd 系统(类似于 Linux 的 systemd),提供简单的命令来启动、停止、重启或查看服务的状态。
主要功能
1、统一管理服务
通过 brew services 命令管理所有通过 Homebrew 安装的支持 launchd 的服务。
2、常用命令
# 启动服务(并设置开机自启)
brew services start <formula>
# 停止服务
brew services stop <formula>
# 重启服务
brew services restart <formula>
# 查看所有服务状态
brew services list
# 关闭开机自启
brew services unlink <formula>
3、开机自启
支持将服务注册为开机自动启动(通过 launchd 的 plist 文件)。
安装方法
homebrew/services 是 Homebrew 的官方 Tap,通常已默认关联。如果没有,可以通过以下命令安装:
brew tap homebrew/services
使用示例
以管理 nginx 为例:
# 安装 nginx
brew install nginx
# 启动 nginx 并设置开机自启
brew services start nginx
# 查看运行状态
brew services list
# 输出示例:
# nginx started user ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
# 停止服务
brew services stop nginx
注意事项
1、仅适用于支持的服务
并非所有 Homebrew 软件包都支持 brew services,只有那些配置了 plist 文件的公式(Formulae)才能被管理。
2、与 launchd 的关系
它本质是对 launchctl(macOS 的服务管理工具)的封装,配置文件通常存放在:
用户级服务:~/Library/LaunchAgents/
系统级服务:/Library/LaunchDaemons/
3、调试问题
如果服务启动失败,可以通过 brew services info <formula> 或直接查看日志文件定位问题。
总结
homebrew/services 简化了 macOS 上通过 Homebrew 安装的服务的生命周期管理,避免了手动操作 launchd 的复杂性。如果你经常用 Homebrew 安装数据库、服务器等软件,这个工具会非常实用。