# 502 bad gateway Nginx

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:

```bash
systemctl status nginx
```

You will see the following output if the Nginx is running:

```bash
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:

```bash
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:

```bash
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:

```bash
systemctl enable nginx
```

## Check the config syntax

To check the config syntax, run the following command:

```bash
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:

```bash
systemctl restart nginx
```

## Check the error logs

If Nginx is running and config syntax is OK, run the following command to
display error logs:

```bash
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:

```bash
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:

```bash
chown -R www-data:www-data /var/www/yourdomain.com
```

## Other options

Check if Nginx is binding to the default ports:

```bash
netstat -plant | grep '80\|443'
```
