清水

最小的善行胜过最大善念

Mac OSX 开机自动启动 Nginx 服务

  系统:OS X EI Capitan 10.11.3

  本来很简单的一件事,却因强迫症不肯放过任何 error 而折腾了半天。方法是在 /Library/LaunchDaemons/ 目录下创建一个 .plist 配置文件,然后运行 sudo launchctl load /Library/LaunchDaemons/nginx.plist 就 OK 了,完成之后各种访问都 OK,但 error.log 文件却出现大量以下错误:

nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] still could not bind()

  而且这错误是不断累积的,很明显告诉你 80 端口已被占用,经查并没有其它程序占用此端口,而是 nginx 自己占用了,但为何会出现这错误,至今也搞不明白。后来搜索到 nginx 官网有个配置文件,就按官网重新放置了 .plist 文件,这次居然不报错了。以下是配置文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key><string>nginx</string>
    <key>Program</key><string>/usr/local/bin/nginx</string>
    <key>KeepAlive</key><true/>
    <key>NetworkState</key><true/>
    <key>WorkingDirectory</key><string>/usr/local/etc/nginx</string>
    <key>StandardErrorPath</key><string>/usr/local/etc/nginx/logs/error.log</string>
    <key>StandardOutPath</key><string>/usr/local/etc/nginx/logs/access.log</string>
    <key>LaunchOnlyOnce</key><true/>
  </dict>
</plist>

  还有 nginx.conf 文件里的这句配置 listen 80 default_server;,出错时我是没加 default_server 的,后来和修改配置文件时一起加上的,不知会不会是这个原因,已无心验证。

参考

nginx error_log reports “bind() to 0.0.0.0:80 failed (48: Address already in use)”
nginx官网:OSX Launchd
Mac OSX的开机启动配置
Launchd in MacOS

Comments