DevOpsil
NginxHigh

Fix: Nginx Cannot Connect to Unix Socket

Nginx error log: 'connect() to unix:/path/to/socket failed (13: Permission denied)'

!Symptoms

  • Nginx error log: 'connect() to unix:/path/to/socket failed (13: Permission denied)'
  • 502 Bad Gateway when using unix socket for upstream
  • Works with root but fails when Nginx runs as www-data

?Root Causes

  • Unix socket file has wrong ownership or permissions
  • SELinux blocking Nginx from accessing the socket
  • Nginx worker running as different user than socket owner
  • Socket directory permissions too restrictive
  • AppArmor profile blocking socket access

#Diagnosis Steps

  1. 1Check socket permissions: `ls -la /path/to/socket`
  2. 2Check Nginx worker user: `grep 'user' /etc/nginx/nginx.conf`
  3. 3Check SELinux: `getenforce` and `ausearch -m avc -ts recent`
  4. 4Verify the upstream creates the socket with correct permissions
  5. 5Check AppArmor: `aa-status` and review the Nginx profile

>Fix

  1. 1Fix socket permissions: ensure Nginx user can read/write the socket
  2. 2Add Nginx user to the upstream application's group
  3. 3Configure the upstream to create the socket with group-writable permissions (e.g., PHP-FPM: listen.mode = 0660)
  4. 4Fix SELinux: `setsebool -P httpd_can_network_connect 1` or create a custom policy
  5. 5Set socket directory permissions: `chmod 755 /path/to/socket/dir`

*Prevention

  • Use a shared group between Nginx and the upstream application
  • Document socket permission requirements in deployment docs
  • Test socket connectivity after any permission changes
  • Automate socket permission setup in deployment scripts (Ansible, etc.)
  • Consider TCP sockets for simpler permission management at slight performance cost

Related Error Messages

connect() to unix:/run/php/php-fpm.sock failed (13: Permission denied)connect() to unix:/tmp/gunicorn.sock failed (2: No such file or directory)502 Bad Gatewayupstream connect error