502 bad gateway Nginx

Better Stack Team
Updated on November 16, 2022

If you are getting the 502 bad gateway error when accessing a Nginx server, here are a few solutions:

Check if Nginx is running

To check if Nginx is running run the following command:

systemctl status nginx

You will see the following output if the Nginx is running:

nginx.service - The nginx HTTP Server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2019-11-19 09:37:46 UTC; 2 days ago
     Docs: https://httpd.nginx.org/docs/2.4/

Or this output if the server is not running:

nginx.service - The nginx HTTP Server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Fri 2019-11-22 08:41:01 UTC; 39s ago
     Docs: https://httpd.nginx.org/docs/2.4/

To start the Nginx in case it is not running, run the following command:

systemctl start nginx

Then check the status again and make sure that Nginx remains running.

• If Nginx did not start after a reboot, you could enable it so that it starts after the next reboot:

systemctl enable nginx

Check the config syntax

To check the config syntax, run the following command:

nginx -t

If there is a problem with the config syntax, it will be listed in the output of this command. You will need to fix each problem and then restart Nginx using the following command:

systemctl restart nginx

Check the error logs

If Nginx is running and config syntax is OK, run the following command to display error logs:

tail -f /var/log/nginx/error.log

Check for the permissions

Check the permissions of the files and folders in your document root. Find the user that your Nginx service is running as:

ps auxf | grep nginx

If you are using Ubuntu, the user should be www-data, so you would need to make sure that your files and folders are owned by that user, so Nginx could read and write to those files:

chown -R www-data:www-data /var/www/yourdomain.com

Other options

Check if Nginx is binding to the default ports:

netstat -plant | grep '80\|443'
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack