Search code examples
ruby-on-railsrubynginxchef-infrachef-solo

Configuring Nginx for rails using Chef Solo


I'm trying to configure a CentOS server to host my rails application. I am using chef solo to configure nginx but when I try to restart the server I get an error saying unknown directive upstream

error

 Error executing action `restart` on resource 'service[nginx]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '6'
    ---- Begin output of /sbin/service nginx restart ----
    STDOUT: 
    STDERR: nginx: [emerg] unknown directive "upstream" in /etc/nginx/nginx.conf:5
    nginx: configuration file /etc/nginx/nginx.conf test failed
    ---- End output of /sbin/service nginx restart ----
    Ran /sbin/service nginx restart returned 6

nginx.rb

package 'nginx'

# execute 'sudo mkdir /etc/nginx/sites-enabled'
directory '/etc/nginx/sites-enabled' do
  owner 'deploy'
  group 'wheel'
  mode '0755'
  action :create
end

# remove default nginx config
default_path = '/etc/nginx/sites-enabled/default'
execute "rm -f #{default_path}" do
  only_if { File.exist?(default_path) }
end

# start nginx
service 'nginx' do
  supports [:status, :restart]
  action :start
end

# # set custom nginx config
# template "/etc/nginx/sites-enabled/#{node['app']}" do
#   source 'nginx.conf.erb'
#   mode 0644
#   owner node['user']['name']
#   group node['group']
#   notifies :restart, 'service[nginx]', :delayed
# end

template '/etc/nginx/nginx.conf' do
  source 'nginx.conf.erb'
  mode 0644
  owner node['user']['name']
  group node['group']
  notifies :restart, 'service[nginx]', :delayed
end

nginx.conf.erb

upstream puma {
  server unix:///home/deploy/apps/<%= node['app'] %>/shared/tmp/sockets/<%= node['app'] %>-puma.sock;
}

server {
  listen 80 default_server deferred;
  # server_name example.com;

  root /home/deploy/apps/<%= node['app'] %>/current/public;
  access_log /home/deploy/apps/<%= node['app'] %>/current/log/nginx.access.log;
  error_log /home/deploy/apps/<%= node['app'] %>/current/log/nginx.error.log info;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 10M;
  keepalive_timeout 10;
}

Solution

  • Most likely the version of Nginx you are installing is too old or doesn't have the upstream module compiled in. In either case, Chef isn't involved, nginx itself is rejecting your config.