Idea Mac OS 80端口被占用

一、概述

       用Mac电脑做开发时,经常会碰到远程调试或者调用时需要用80端口来启动WEB服务,Intellij IDEA上把tomcat的默认端口改成80,启动web应用时一直提示80端口被占用。使用lsof -i:80命令查找发现是Chrome浏览器占用80端口,然后杀掉浏览器进程再次启动web应用,仍然提示80端口被占用。经过Google发现是由于 Mac 系统限制非root用户不能启动1024以下端口,而我们平时使用Mac一般都是非root用户,所以如果想启动80端口必须用root用户。比如启动nginx,必须使用sudo nginx ,但是如果用root权限启动nginx或tomcat又会造成, 启动创建的各类文件是root的,普通用户无法删除。尤其是使用公司的电脑安装了权限控制。。。这真是让人头疼的问题?

二、解决方案

      解决方法:可以通过pfctl做网络层的端口转发, 让连接到本机80端口的请求, 都转发到8080端口。

  • 用管理员权限打开编辑pf.conf文件,命令如下:
sudo vim /etc/pf.conf
  • 在 rdr-anchor "com.apple/*" 这一行的后面添加一行,如下所示:
rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 8080

   注意:conf是对顺序强要求的, 所以注意添加的内容放的顺序。效果如下:

# Default PF configuration file.
# This file contains the main ruleset, which gets automatically loaded
# at startup.  PF will not be automatically enabled, however.  Instead,
# each component which utilizes PF is responsible for enabling and disabling
# PF via -E and -X as documented in pfctl(8).  That will ensure that PF
# is disabled only when the last enable reference is released.
#
# Care must be taken to ensure that the main ruleset does not get flushed,
# as the nested anchors rely on the anchor point defined here. In addition,
# to the anchors loaded by this file, some system services would dynamically
# insert anchors into the main ruleset. These anchors will be added only when
# the system service is used and would removed on termination of the service.
#
# See pf.conf(5) for syntax.
# com.apple anchor point
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 8080
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"
  • 其中lo0是绑定了127.0.0.1的网络设备名称,具体可以使用ifconfig查看。在tomcat的配置中,设定启动端口为8080,依次执行如下命令让端口转发马上生效:
sudo pfctl -d   #第一步

sudo pfctl -f /etc/pf.conf    #第二步

sudo pfctl -e    #第三步

       在执行上述命令的过程中如果发现如下提示,忽略之即可:

No ALTQ support in kernel
ALTQ related functions disabled
pfctl: pf already enabled

       最后启用之前请先停掉其他占用80端口的进程如nginx等应用。项目启动成功n(*≧▽≦*)n

你可能感兴趣的:(Mac,Linux基础命令,IDEA)