OS X - 在80端口启动Nginx

不知道你是怎么在你的mac上安装nginx的,但是如果你跟我一样:

brew install nginx

然后你会发现你的nginx.conf中的端口是8080。
于是你可能像我一样试着把端口改为80,然后reload一下。

你发现没有任何错误提示,当你访问localhost时却没有nginx的首页,甚至连403也没有。

于是你尝试...

sudo lsof -n -i:80 | grep -i LISTEN

却发现没有输出和nginx有关的任何东西。
于是才想起OSX不允许system级以外的服务使用1024以下的端口。


起初我并没有太关心这个问题,我并不介意多输入几个数字。
直到我加入了一个新的团队,我和我那些使用其他操作系统的同事们统一了hosts,并使用同一个数据库进行开发时才意识到 —— 我可能因为这个问题给别人造成麻烦。

 

launchd

关于launchd的描述,这里引用一下manpage,如下:

launchd manages processes, both for the system as a whole and for individual users.
The primary and preferred interface to launchd is via the launchctl(1) tool which (among other options) allows the user or administrator to load and unload jobs.
Where possible, it is preferable for jobs to launch on demand based on criteria specified in their respective configuration files.
launchd also manages XPC services that are bundled within applications and frameworks on the system.
During boot launchd is invoked by the kernel to run as the first process on the system and to further bootstrap the rest of the system.
You cannot invoke launchd directly.

launchd用于为系统和用户管理进程,主要通过launchctl对其进行操作,用户无法直接调用launchd。
启动时由内核调用launchd,运行第一个进程。

 

plist

另外我们需要了解的就是plist文件。
plist就是property list format的意思,是苹果用来保存应用数据的格式,其实就是个xml。
可以在 /usr/local/opt/nginx 下找到nginx对应的plist文件,比如在我的电脑上是 homebrew.mxcl.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>homebrew.mxcl.nginx</string>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <false/>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/local/opt/nginx/bin/nginx</string>
            <string>-g</string>
            <string>daemon off;</string>
        </array>
        <key>WorkingDirectory</key>
        <string>/usr/local</string>
    </dict>
</plist>


我们需要把这个文件复制到 /Library/LaunchDaemons 下,如果是 ~/Library/LaunchAgents 也可以,但两者有区别。
前者是系统启动时启动,后者则是在用户登录时启动。 接着执行launchctl load -w,如下:

sudo cp /usr/local/opt/nginx/*.plist /Library/LaunchDaemons
sudo launchctl load -w /Library/LaunchDaemons/homebrew.mxcl.nginx.plist


最后,重启你的机器,你会发现nginx在80端口启动了。

 

posted @ 2016-03-30 23:57  Jinkora  阅读(5319)  评论(4编辑  收藏  举报
visit:click tracking