Search code examples
rubycentosrubygemsrvmsystemd

Can't start Ruby Sinatra App as systemd unit - gem not found


I'm trying to start Sinatra application as Systemd unit. It's not a first time, this service was working before, but now I'm stuck.

systemctl start service always throws cannot find gem sinatra

Here is the log:

Nov 27 19:52:45 cloud.onehostcloud.hosting ruby[29074]: /usr/local/rvm/rubies/ruby-2.5.7-devel/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- sinatra (LoadError)
Nov 27 19:52:45 cloud.onehostcloud.hosting ruby[29074]: from /usr/local/rvm/rubies/ruby-2.5.7-devel/lib/ruby/site_ruby/2.5.0/rubygems/core_ext/kernel_require.rb:54:in `require'
Nov 27 19:52:45 cloud.onehostcloud.hosting ruby[29074]: from /usr/lib/app/server.rb:34:in `<main>'
Nov 27 19:52:45 cloud.onehostcloud.hosting systemd[1]: app.service: main process exited, code=exited, status=1/FAILURE

The app.service file:

[Unit]
Description=API Server Service

[Service]
Type=simple
Group=appuser
User=appuser
ExecStart=/usr/bin/ruby /usr/lib/app/server.rb
StartLimitInterval=30
StartLimitBurst=3
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

I've checked and the $: is correct, so if I try with the same path all gems can be found and included via irb

Using CentOS 7 with RVM Ruby 2.5.7

Thank you!


Solution

  • Your reference to /usr/bin/ruby is bypassing RVM, and it sounds like you are using RVM to manage your gems.

    RVM doesn't seem to have documentation on how to set up systemd services, but it does have guidance on launching scripts from cron, which is a similar situation.

    Basically, RVM provides a wrapper for each combination of ruby version and gemset, which you can use in your app.service file. Your ExecService line would look something like this:

    [Service]
    ExecStart=/home/appuser/.rvm/wrappers/ruby-3.0.0@appgemset/ruby /usr/lib/app/server.rb
    

    If you haven't created a specific gemset for your app, then you can omit the @appgemset part, and only specify the ruby version you want to use.