🎯 Objective
Configure Nginx to execute PHP applications using PHP-FPM via a Unix socket, which is faster than using TCP ports because communication happens locally through a file.
# 📜 What is PHP-FPM?
PHP-FPM (FastCGI Process Manager) manages PHP worker processes and allows web servers like Nginx to execute PHP scripts efficiently.
Flow:
Browser → Nginx → PHP-FPM → PHP Application# 1️⃣ Install Nginx and PHP-FPM
Ubuntu / Debian
sudo apt update
sudo apt install nginx php-fpm php-mysql-yRHEL / CentOS / Amazon Linux
sudo yum install nginx php php-fpm php-mysqlnd-y# 2️⃣ Start and Enable Services
Start services:
sudo systemctlstart nginx
sudo systemctlstart php-fpmEnable at boot:
sudo systemctl enable nginx
sudo systemctl enable php-fpmCheck status:
sudo systemctl status nginx
sudo systemctl status php-fpm# 3️⃣ Configure PHP-FPM Unix Socket
Edit configuration:
sudo nano /etc/php-fpm.d/www.confFind:
listen = 127.0.0.1:9000Change to:
listen = /run/php-fpm/www.sockSet permissions:
listen.owner = nginx
listen.group = nginx
listen.mode = 0660Restart PHP-FPM:
sudo systemctl restart php-fpm# 4️⃣ Configure Nginx to Use Socket
Edit Nginx configuration:
sudo nano /etc/nginx/conf.d/default.confExample configuration:
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}# 5️⃣ Test Configuration
sudo nginx -tExpected output:
syntax is ok
test is successful# 6️⃣ Restart Nginx
sudo systemctl restart nginx# 7️⃣ Create Test PHP File
sudo nano /usr/share/nginx/html/info.phpAdd:
<?php
phpinfo();
?>Open browser:
http://server-ip/info.phpYou should see the PHP configuration page.
# 🧠 Architecture
Client Browser
│
▼
Nginx Web Server
│
▼
Unix Socket (/run/php-fpm/www.sock)
│
▼
PHP-FPM
│
▼
PHP Application# ⚡ Why Use Unix Socket Instead of TCP?
Example comparison:
TCP: 127.0.0.1:9000
Socket: /run/php-fpm/www.sock# 🧪 Troubleshooting
Check PHP-FPM socket
ls-l /run/php-fpm/Check Nginx logs
sudo tail-f /var/log/nginx/error.logRestart services
sudo systemctlrestart nginx
sudo systemctlrestart php-fpm# ✅ Summary