Nginx: bind() to 0.0.0.0:8080 failed (48: Address already in use) on mac

I’m having an issue with Nginx on Mac OS (nginx version: nginx/1.17.7).

I had reinstalled Nginx through Homebrew, but when I tried to initialize Nginx I got this error:

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

I found possible solutions online, one of which was to kill processes using the port. When I tried this command ps ax -o pid,ppid,%cpu,vsz,wchan,command|egrep '(nginx|PID)', I got this output:

  PID  PPID  %CPU      VSZ WCHAN  COMMAND
21827     1   0.0  4291640 -      nginx: master process nginx
21828 21827   0.0  4301348 -      nginx: worker process
21831 93689   0.0  4267768 -      egrep (nginx|PID)

I attempted to kill the processes with kill -9 <PID>, but got an error: -bash: kill: (21827) - Operation not permitted. After running sudo kill -9 21827 instead, I killed all the processes but the third one. When I tried to sudo kill -9 21831, I got No such process because the PID was changing all the time.

I then tried restarting Nginx with sudo nginx -s stop && sudo nginx, but got nginx: [alert] kill(21827, 15) failed (3: No such process). I also tried brew services list and brew services start nginx, but again got nginx: [emerg] open() "/usr/local/var/run/nginx.pid" failed (13: Permission denied). Finally, running ps aux | grep nginx gave me this output:

apple            22922   0.0  0.0  4267768    832 s003  S+    3:09AM   0:00.00 grep nginx

I’m not sure what I’m doing wrong, or what the correct initial steps to get Nginx running are. Could someone help me out?

The error message suggests that the port 8080 is already in use. To fix this, you need to identify the process that is using this port and stop it. You can do this by running the following command:

sudo lsof -i :8080

This will give you a list of processes that are using port 8080. You can then stop the process using the port by running the following command:

sudo kill <PID>

Replace <PID> with the process ID of the process you want to stop. Once you have stopped the process, you should be able to start Nginx without any issues.