sodcalculator

10 Tech How-To

Deploy a Rails App to a VPS: Step-by-Step Guide

Guide 10-48394 · Updated · Step by step

This guide walks you through deploying a Ruby on Rails application to a Virtual Private Server (VPS) from scratch. You’ll end up with a production-ready app served by Puma and Nginx, with PostgreSQL as the database, running on Ubuntu. Before starting, you should have a Rails app that works locally, a VPS with Ubuntu 22.04 or 24.04, and SSH access to that server.

What You’ll Need

  • A VPS with Ubuntu 22.04 or 24.04 (any provider works)
  • SSH access to the server (root or a user with sudo privileges)
  • A Rails application that runs locally (Ruby 3.x, Rails 7.x recommended)
  • A domain name pointing to your server’s IP (optional but recommended for production)
  • Git installed on your local machine
  • Basic comfort with the command line

Step-by-Step

  1. Update the server and create a deploy user. SSH into your VPS as root, then run apt update && apt upgrade -y. Create a new user with adduser deploy, add them to the sudo group with usermod -aG sudo deploy, and switch to them with su - deploy. Using a non-root user is safer for production.
  2. Install Ruby. Use a version manager like rbenv to install the Ruby version your app needs. As the deploy user, run sudo apt install -y git curl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libncurses5-dev libffi-dev libgdbm-dev, then curl -fsSL https://github.com/rbenv/rbenv-installer/raw/HEAD/bin/rbenv-installer | bash. Add rbenv to your shell by running echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc and echo 'eval "$(rbenv init -)"' >> ~/.bashrc, then reload with source ~/.bashrc. Install Ruby with rbenv install 3.2.2 (or your app’s version) and set it globally with rbenv global 3.2.2.
  3. Install Node.js and Yarn. Rails needs a JavaScript runtime for the asset pipeline. Install Node.js 18.x with curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - then sudo apt install -y nodejs. Enable Yarn with sudo corepack enable.
  4. Install PostgreSQL. Run sudo apt install -y postgresql postgresql-contrib libpq-dev. Start the service with sudo systemctl start postgresql. Create a database user for your app: sudo -u postgres createuser --createdb deploy and set a password with sudo -u postgres psql -c "ALTER USER deploy WITH PASSWORD 'your_strong_password';". Write down this password.
  5. Install Nginx. Run sudo apt install -y nginx. This will serve static files and proxy requests to Puma.
  6. Clone your app to the server. From your local machine, push your Rails app to a Git repository (GitHub, GitLab, etc.). On the server, as the deploy user, run git clone https://github.com/yourusername/yourapp.git in your home directory. Then cd yourapp.
  7. Install dependencies. Run bundle install --without development test to install gems. Then run yarn install to install JavaScript packages.
  8. Configure the database. Edit config/database.yml to use PostgreSQL in production. Set the username to deploy and the password to the one you created. You can use environment variables for security: username: <%= ENV['DB_USERNAME'] %>. Create a .env file in the app directory with DB_USERNAME=deploy and DB_PASSWORD=yourpassword. Then run RAILS_ENV=production bundle exec rails db:create db:migrate.
  9. Precompile assets and set the secret key. Run RAILS_ENV=production bundle exec rails assets:precompile. Generate a secret key with RAILS_ENV=production bundle exec rails secret and add it to your .env file as SECRET_KEY_BASE=your_generated_key.
  10. Test Puma. Start Puma manually to verify it works: RAILS_ENV=production bundle exec puma -C config/puma.rb. You should see it listening on port 3000. Press Ctrl+C to stop it.
  11. Create a systemd service for Puma. Create a file /etc/systemd/system/puma.service with sudo. Include the following (adjust paths to match your app):
     [Unit]
    Description=Puma HTTP Server
    After=network.target
    
    [Service]
    User=deploy
    WorkingDirectory=/home/deploy/yourapp
    Environment=RAILS_ENV=production
    EnvironmentFile=/home/deploy/yourapp/.env
    ExecStart=/home/deploy/.rbenv/shims/bundle exec puma -C config/puma.rb
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    

    Then run sudo systemctl daemon-reload and sudo systemctl enable --now puma.

  12. Configure Nginx. Create a new Nginx site with sudo nano /etc/nginx/sites-available/yourapp. Add a server block that listens on port 80, sets the server name to your domain or IP, and proxies requests to Puma. A minimal config looks like:
     server {
        listen 80;
        server_name yourdomain.com;
    
        root /home/deploy/yourapp/public;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    
        location ~ ^/assets/ {
            expires 1y;
            add_header Cache-Control public;
        }
    }
    

    Enable the site with sudo ln -s /etc/nginx/sites-available/yourapp /etc/nginx/sites-enabled/, remove the default site with sudo rm /etc/nginx/sites-enabled/default, and test with sudo nginx -t. Then restart Nginx with sudo systemctl restart nginx.

  13. Open the firewall. If you have UFW enabled, allow SSH and HTTP: sudo ufw allow OpenSSH and sudo ufw allow 'Nginx Full'. Then enable with sudo ufw enable.
  14. Verify the deployment. Visit your server’s IP or domain in a browser. You should see your Rails app. If not, check the logs with sudo journalctl -u puma and sudo tail -f /var/log/nginx/error.log.

Common Mistakes

  • Forgetting to set the secret key base. Rails will refuse to start in production without it. Always generate and set it.
  • Using the wrong Ruby version. If your app uses 3.2.0 but you installed 3.2.2, bundle may fail. Match exactly.
  • Not precompiling assets. If you skip this, Nginx will serve raw Ruby files and your CSS/JS will be broken.
  • Hardcoding database credentials. Putting passwords in database.yml is a security risk. Use environment variables.
  • Forgetting to run migrations. Your database tables won’t exist, causing errors at runtime.

Tips

  • Use Capistrano or Kamal for future deployments. They automate the process and handle rollbacks gracefully.
  • Set up SSL with Let’s Encrypt. Use sudo apt install certbot python3-certbot-nginx then sudo certbot --nginx to get a free certificate.
  • Use a swap file if your VPS has little RAM. Rails can be memory-hungry. Create one with sudo fallocate -l 2G /swapfile and enable it.
  • Backup your database regularly. Use pg_dump and store backups off-server.

Troubleshooting

  • 502 Bad Gateway from Nginx. This usually means Puma isn’t running. Check sudo systemctl status puma and the logs. Ensure the EnvironmentFile path is correct and the user has permission to read it.
  • Assets not loading. Run RAILS_ENV=production bundle exec rails assets:precompile again and restart Puma. Also check that public/assets exists.
  • Database connection refused. Check that PostgreSQL is running (sudo systemctl status postgresql) and that the credentials in .env match what you set in PostgreSQL.
  • Puma starts then exits. Look at sudo journalctl -u puma -n 50. Common causes: missing secret key, wrong database config, or missing gems.
  • Permission denied when writing to log or tmp. Ensure the deploy user owns the app directory: sudo chown -R deploy:deploy /home/deploy/yourapp.

Frequently Asked Questions

Do I need to use PostgreSQL?

No, you can use MySQL or SQLite, but PostgreSQL is the most common choice for Rails production because of its reliability and features. Adjust the install steps accordingly.

Can I deploy without a domain name?

Yes, you can use your server’s IP address in the Nginx config. Just set server_name to the IP.

How do I update my app after making changes?

Pull the new code with git pull, run bundle install if dependencies changed, run migrations if needed, precompile assets, and restart Puma with sudo systemctl restart puma.

Is it safe to run Rails as root?

No, always use a non-root user like deploy. Running as root can lead to security vulnerabilities and permission issues.

What if my app uses background jobs like Sidekiq?

You’ll need to install Redis and create a separate systemd service for Sidekiq, similar to the Puma service but with ExecStart=/home/deploy/.rbenv/shims/bundle exec sidekiq.

How do I set up SSL?

Install Certbot with sudo apt install certbot python3-certbot-nginx, then run sudo certbot --nginx -d yourdomain.com. Certbot will automatically configure Nginx and renew the certificate.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →