问题背景
使用vite将项目启动配置到80端口的时候发现80端口被占用。
通过浏览器访问该页面时显示 it works
.响应头的Server中显示由apache提供服务
问题排查
通过端口命令,查找占用端口的进程
sudo lsof -i:80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
httpd 145 root 4u IPv6 0x86fb7c76ad702387 0t0 TCP *:http (LISTEN)
httpd 1214 _www 4u IPv6 0x86fb7c76ad702387 0t0 TCP *:http (LISTEN)
httpd 3143 _www 4u IPv6 0x86fb7c76ad702387 0t0 TCP *:http (LISTEN)
httpd 3144 _www 4u IPv6 0x86fb7c76ad702387 0t0 TCP *:http (LISTEN)
httpd 3145 _www 4u IPv6 0x86fb7c76ad702387 0t0 TCP *:http (LISTEN)
尝试通过命令停用服务释放端口占用,显示该服务未启用
/opt/homebrew/opt/httpd/bin/httpd -k stop
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using admindeMacBook-Pro-7.local. Set the 'ServerName' directive globally to suppress this message
httpd (pid 5691?) not running
查看apache的index.html路径,并将文本内容改为 it
,访问本机环回地址仍显示it works
,初步推断本地存在不止一个apache。
通过监视器查询与端口关联进程145获得信息,父进程为launched,用户为root。
由于该服务被kill掉以后会被立即重启,因此需要从守护服务当中关闭掉该服务。
在守护进程相关目录下进行httpd服务查询。
与守护进程相关目录为:
Type | Location | Run on behalf of |
---|---|---|
User Agents | ~/Library/LaunchAgents | Currently logged in user |
Global Agents | /Library/LaunchAgents | Currently logged in user |
Global Daemons | /Library/LaunchDaemons | root or the user specified with the key UserName |
System Agents | /System/Library/LaunchAgents | Currently logged in user |
System Daemons | /System/Library/LaunchDaemons | root or the user specified with the key UserName |
查找系统守护进程目录下的httpd服务,并移除该服务。
/System/Library/LaunchDaemons sudo launchctl list | grep httpd
11344 0 org.apache.httpd
查看该服务相关配置:
cat org.apache.httpd.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>Disabled</key>
<true/>
<key>Label</key>
<string>org.apache.httpd</string>
<key>EnvironmentVariables</key>
<dict>
<key>XPC_SERVICES_UNAVAILABLE</key>
<string>1</string>
<key>OBJC_DISABLE_INITIALIZE_FORK_SAFETY</key>
<string>YES</string>
</dict>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/httpd-wrapper</string>
<string>-D</string>
<string>FOREGROUND</string>
</array>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
删除掉该守护服务后,80端口被释放。
/System/Library/LaunchDaemons sudo launchctl remove org.apache.httpd
至此,问题解决。
问题结论
由于系统守护进程中包含了一个httpd服务,导致该服务会自启动并占用80端口。
参考资料
- launch:https://www.launchd.info/