How to change listening Nginx Port
How to change listening Nginx Port
NGINX is a high-performance, open-source web server and reverse proxy server. It is well-known for its speed, scalability, and efficiency, particularly when handling a large number of concurrent connections.
Error Indication
You get the following error when you start Nginx server.
ubuntu nginx[4686]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
The problem root cause is that the listening port is already in use. To change the port that NGINX listens on, you need to modify the NGINX configuration file.
Steps
Steps to change the port are as follows:
Open the NGINX Configuration File: You can use any text editor like nano or vim. The main configuration file is usually located at
/etc/nginx/nginx.conf, but some systems might use
/etc/nginx/sites-available/default
or
/etc/nginx/conf.d/default.conf
For example, open the NGINX configuration file with nano:
$ sudo nano /etc/nginx/nginx.conf
Find the listen Directive: Look for the listen directive in the configuration file. This tells NGINX which port it should be listening on. By default, it might look like this:
server {
listen 80;
server_name example.com;
...
}
Change the Port: Modify the listen directive to the new port you want NGINX to listen on. For example, to change it to port 8080, you would modify it like this:
server {
listen 8080;
server_name example.com;
...
}
Save and Exit: After making the change, save the file and exit the editor. If you’re using nano, press CTRL + O to save, then CTRL + X to exit.
Check NGINX Configuration
It’s always a good idea to check if the configuration is valid before restarting NGINX. Run:
$ sudo nginx -t
If the output says the configuration is OK, you can proceed. If there are errors, fix them before proceeding.
Restart NGINX
After making the changes, restart NGINX for the changes to take effect:
$ sudo systemctl restart nginx
Allow the New Port through the Firewall (if applicable): If you’re using a firewall (e.g., ufw), make sure the new port is allowed.
For example, if you changed to port 8080:
$ sudo ufw allow 8080
Now, NGINX should be listening on the new port! To verify, you can check with:
$ sudo netstat -tuln | grep 8080