CentOS 7 – Why Can’t Nginx Access Puma Socket?

centos-7nginxpermissionsrailsruby

So I have a Ruby on Rails app in /var/www/ owned by nginx with 755 permissions. Said app is intended to be deployed via puma.

Like so:

rvmsudo -u nginx bundle exec puma -e production -d -b unix:///var/www/my_app/tmp/sockets/my_app.socket

The permissions for the socket are:

srwxrwxrwx. 1 nginx nginx 0 Nov  6 09:43 tmp/sockets/my_app.sock

The process is, of course, owned by nginx:

nginx     7335  0.0  8.8 536744 90388 ?        Sl   09:43   0:00 puma 2.9.2 (unix:///var/www/my_app/tmp/sockets/my_app.sock)

My nginx configuration configuration is as follows:

upstream my_app {
  server unix:///var/www/my_app/tmp/sockets/my_app.sock;
}

server {
  listen 80;
  server_name www.example.com example.com;
  root /var/www/my_app/public;

  location / {
    proxy_pass http://my_app;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

All of this and my application is still denied permissions.

connect() to unix:///var/www/my_app/tmp/sockets/my_app.sock failed (13: Permission denied) while connecting to upstream,

I have tried all of this as the root user, also. But it still does not work.

Does anyone know what I am doing wrong?

Best Answer

Hallelujah! This all turned out to be an SELinux policy issue specifically pertaining to nginx. After hours of digging, I discovered such denials by running:

sudo grep nginx /var/log/audit/audit.log

The messages looked like so:

type=AVC msg=audit(1415283617.227:1386): avc:  denied  { write } for  pid=1683 comm="nginx" name="my_app.sock" dev="tmpfs" ino=20657 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_run_t:s0 tclass=sock_file

In order to fix this, I found a wonderful article by Axilleas.

To create the policy containing the necessary permissions, I had to install audit2allow and run:

grep nginx /var/log/audit/audit.log | audit2allow -M nginx

Once done, I finalized the policy with:

semodule -i nginx.pp

Unfortunately, I had to run this process twice before being able to access my application because further policies were needed. Nonetheless, here was the solution.

Also, there is another nice article by Sergiy Krylkov.

Moral of the story: learn SELinux.

Related Question