Homebrew 是 macOS 上最实用的包管理器,一条命令即可完成 MySQL、Nginx、Redis 等服务器软件的安装、启动、开机自启和版本管理;需先安装 Command Line Tools 并配置国内镜像源以加速。
homebrew 是 macos 上最实用的包管理器,安装服务器软件(如 mysql、nginx、redis、postgresql 等)不再需要手动编译、配置服务脚本或处理依赖冲突——一条命令就能完成安装、启动、开机自启和版本管理。
安装前准备:确保基础环境就绪
Homebrew 依赖系统命令行工具,安装前需确认以下两项已就绪:
- 运行 xcode-select --install 安装 Command Line Tools(若提示已存在可跳过)
- 终端默认 shell 为 zsh(macOS Catalina 及以后默认),检查方式:echo $SHELL,输出应为 /bin/zsh
- 如在国内网络环境,建议提前配置代理或切换国内镜像源(后续步骤会说明)
安装常用服务器软件(Formula 方式)
所有服务类软件均通过 brew install 安装,无需额外下载或解压。典型示例如下:
-
MySQL:
brew install mysql—— 安装后自动创建配置文件/opt/homebrew/etc/my.cnf(Apple Silicon) -
Nginx:
brew install nginx—— 配置文件位于/opt/homebrew/etc/nginx/nginx.conf,静态文件根目录默认为/opt/homebrew/var/www -
Redis:
brew install redis—— 配置文件路径:/opt/homebrew/etc/redis.conf -
PostgreSQL:
brew install postgresql—— 初始化数据库需执行:initdb /opt/homebrew/var/postgres
注意:部分软件(如 openjdk@17)被标记为 keg-only,不会自动加入 PATH;但 MySQL、Nginx、Redis 等主流服务默认支持全局调用。
启用与管理服务(brew services)
Homebrew 提供 brew services 子命令统一管理后台服务,比手动写 launchd plist 更简洁可靠:
- 启动并设为开机自启:
brew services start mysql - 仅当前会话启动(不自启):
brew services run nginx - 停止服务:
brew services stop redis - 查看所有服务状态:
brew services list(显示 running / stopped / error 状态) - 重启服务(如修改配置后):
brew services restart postgresql
服务日志默认存于:/opt/homebrew/var/log/<service-name>.log,例如 tail -f /opt/homebrew/var/log/mysql.log 可实时跟踪错误。
配置国内镜像源(加速安装与更新)
官方源访问慢是常见问题,推荐将 Homebrew 的核心仓库和绑定的 GitHub 资源切换为清华或中科大镜像:
- 替换 brew.git:
git -C $(brew --repo) remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git - 替换 core tap:
git -C $(brew --repo homebrew/core) remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git - 替换 cask tap(如需装图形化管理工具):
git -C $(brew --repo homebrew/cask) remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git - 执行
brew update生效;恢复官方源只需把 URL 换回https://github.com/Homebrew/brew等原始地址
切换后,brew install 和 brew update 速度明显提升,尤其对大体积服务(如 PostgreSQL 或带有二进制依赖的软件)效果显著。
常见问题快速应对
实际部署中可能遇到几类高频问题,可按需排查:
-
“command not found: brew” → 检查
~/.zshrc是否已添加 Homebrew 路径:export PATH="/opt/homebrew/bin:$PATH"(Apple Silicon)或export PATH="/usr/local/bin:$PATH"(Intel),然后运行source ~/.zshrc -
brew services start 失败 → 先运行
brew doctor检查环境;常见原因是端口被占用(如 MySQL 默认 3306)、配置文件语法错误或数据目录权限不足 - 服务启动后无法访问 → 确认防火墙未拦截(macOS 系统偏好设置 → 防火墙 → 高级 → 允许远程登录/入站连接);Nginx 默认监听 localhost:8080,非 80 端口无需 sudo
-
想卸载并清理干净 → 先
brew services stop <name>,再brew uninstall <name>,最后brew cleanup清理旧版本缓存


















