[FIXED] Error 502 Bad Gateway in Nginx with PHP-FPM
The 502 Bad Gateway error on Nginx web servers using PHP-FPM occurs when Nginx acts as a reverse proxy but fails to establish a socket connection with the PHP backend process. The error log at /var/log/nginx/error.log usually states: connect() to unix:/run/php/php8.2-fpm.sock failed (2: No such file or directory) or Connection refused.
Quick Diagnostics
sudo systemctl start php-fpm (or php8.2-fpm)www-data:www-data in /etc/php/fpm/pool.d/www.confThe 502 Bad Gateway error on Nginx web servers using PHP-FPM occurs when Nginx acts as a reverse proxy but fails to establish a socket connection with the PHP backend process. The error log at /var/log/nginx/error.log usually states:
connect() to unix:/run/php/php8.2-fpm.sock failed (2: No such file or directory) or Connection refused.
Quick Solution (1 Minute):
- Restart your active PHP-FPM service:
sudo systemctl restart php8.2-fpm- Ensure your Nginx
fastcgi_passdirective matches your exact installed PHP socket version.
🚀 Step-by-Step Fixes
Step 1: Check PHP-FPM Daemon Status
Verify that PHP-FPM is active and running:
sudo systemctl status php8.2-fpm
If status reports inactive or failed, enable and start it:
sudo systemctl enable --now php8.2-fpm
Step 2: Verify Exact Socket (.sock) Path
Check the active socket location created by PHP:
ls -la /run/php/
Expected output: php8.2-fpm.sock or php8.3-fpm.sock.
Open your Nginx site configuration file at /etc/nginx/sites-available/yourdomain.conf:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# MUST match your active .sock file path:
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
Step 3: Fix PHP-FPM Socket Permissions
If the .sock file exists but Nginx returns Permission denied in its logs:
Edit your PHP-FPM pool configuration:
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
Ensure the socket owner matches Nginx (www-data):
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Restart services:
sudo systemctl restart php8.2-fpm
sudo systemctl restart nginx
Prevention Advice
Recommended security practices: