不知道你是怎么在你的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端口啟動了。