Setting up Nginx with Ruby on Rails and Puma involves configuring Nginx as a reverse proxy to forward requests to the Puma application server. Here’s a step-by-step guide:
1. Install Ruby on Rails and Puma:
Make sure Ruby on Rails and Puma are installed on your server. You can use a tool like rbenv or rvm to manage your Ruby environment.
gem install rails
gem install puma2. Create a Rails Application:
If you haven’t already, create a new Rails application or use an existing one:
rails new myapp
cd myapp3. Configure Puma:
Edit the Puma configuration file (config/puma.rb) and make sure it’s configured to listen on a Unix socket:
# config/puma.rb
bind "unix:///var/run/myapp.sock"4. Start Puma:
Start the Puma server using the socket you defined:
bundle exec puma -C config/puma.rb5. Set Up Nginx:
Install Nginx if it’s not already installed:
sudo apt update
sudo apt install nginx6. Create Nginx Configuration:
Create a new Nginx server block configuration file for your Rails application. Replace myapp with your actual domain or server name:
sudo nano /etc/nginx/sites-available/myappAdd the following configuration:
upstream myapp {
server unix:///var/run/myapp.sock;
}
server {
listen 80;
server_name your_domain.com; # Replace with your domain or server name
root /path/to/your/rails/app/public; # Replace with the path to your Rails app's public directory
try_files $uri/index.html $uri @myapp;
location @myapp {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://myapp;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}7. Enable the Nginx Configuration:
Create a symbolic link to enable the Nginx server block:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/8. Test and Restart Nginx:
Before applying the changes, test your Nginx configuration:
sudo nginx -tIf the test is successful, restart Nginx:
sudo systemctl restart nginx9. Set Up DNS (Optional):
Point your domain (e.g., your_domain.com) to your server’s IP address if you haven’t already.
10. Verify Deployment:
Visit your domain in a web browser, and you should see your Rails application served by Puma via Nginx.
By following these steps, you have set up Nginx with Ruby on Rails and Puma, allowing Nginx to act as a reverse proxy forwarding requests to the Puma application server. This configuration enables you to deploy your Rails application for production use.