How to Set Up Nginx with Ruby on Rails and Puma

How to Set Up Nginx with Ruby on Rails and Puma

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.

Bash
gem install rails
gem install puma

2. Create a Rails Application:

If you haven’t already, create a new Rails application or use an existing one:

Bash
rails new myapp
cd myapp

3. Configure Puma:

Edit the Puma configuration file (config/puma.rb) and make sure it’s configured to listen on a Unix socket:

Bash
# config/puma.rb

bind "unix:///var/run/myapp.sock"

4. Start Puma:

Start the Puma server using the socket you defined:

Bash
bundle exec puma -C config/puma.rb

5. Set Up Nginx:

Install Nginx if it’s not already installed:

Bash
sudo apt update
sudo apt install nginx

6. Create Nginx Configuration:

Create a new Nginx server block configuration file for your Rails application. Replace myapp with your actual domain or server name:

Bash
sudo nano /etc/nginx/sites-available/myapp

Add the following configuration:

Bash
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:

Bash
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:

Bash
sudo nginx -t

If the test is successful, restart Nginx:

Bash
sudo systemctl restart nginx

9. 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.

Total
0
Shares

Leave a Reply

Previous Post
How to Set Up Nginx with HSTS (HTTP Strict Transport Security)

How to Set Up Nginx with HSTS (HTTP Strict Transport Security)

Next Post
How to Implement Dynamic DNS with Nginx

How to Implement Dynamic DNS with Nginx

Related Posts