Deploy Ruby On Rails on
Ubuntu 14.04 Trusty Tahr

A guide to setting up a Ruby on Rails production environment



This will take about 45 minutes.

Skip all this work and let Hatchbox configure your servers and deploy Rails apps to it.

Check out Hatchbox!

We will be setting up a Ruby on Rails production environment on Ubuntu 14.04 LTS Trusty Tahr.

Since we setup Ubuntu for our development environment, we also want to use it in production. This keeps your application running consistently between development and production. We're using an LTS version of Ubuntu in production because it is supported for several years where a normal version of Ubuntu isn't.

Using Ubuntu LTS in production allows you to continue receiving security updates which is important for your production server(s).

We're going to be setting up a Droplet on Digital Ocean for our server. It costs $5/mo and is a great place to host your applications.

If you sign up with my Digital Ocean referral link, you'll get 2 months ($10) free credit to try it out.

You can use any cloud server hosting company you choose for your Rails application. I've had excellent experience with Digital Ocean and Linode with the servers I have used. If you're looking for alternatives outside the US or otherwise, just google "VPS hosting". A VPS is a virtual private server. It's just like a server you setup at home, only virtualize and running with a suite of other servers in a datacenter.

Since we're using Digital Ocean for our cloud server, the first thing we're going to do is configure a new one. I'm going with the Droplet with 1GB of RAM. You can setup whichever size server you prefer, keep in mind that if you choose a 512MB server you may run into some slowness with a low amount of RAM.

Droplet Size

The next step is to choose your location. Choose one close to you so that you can have better connection speeds.

Droplet Region

Last, but not least we need to choose which OS to use. We're going to be using Ubuntu 14.04 LTS x64. Your application may require a different OS or version, but if you're not sure this is generally what you should use.

Droplet Image

Optionally you can add your SSH key into the Droplet so you can SSH in and skip the ssh-copy-id step.

Once Digital Ocean has configured your server, check your email to get your password for the new cloud server.

You should follow the instructions in the email to login via SSH for the very first time and verify it is working.

The first thing we will do on our new server is create the user account we'll be using to run our applications and work from there.

sudo adduser deploy
sudo adduser deploy sudo
su deploy

Before we move forward is that we're going to setup SSH to authenticate via keys instead of having to use a password to login. It's more secure and will save you time in the long run.

We're going to use ssh-copy-id to do this. If you're on OSX you may need to run brew install ssh-copy-id but if you're following this tutorial on Linux desktop, you should already have it.

Once you've got ssh-copy-id installed, run the following and replace IPADDRESS with the one for your server:

Make sure you run ssh-copy-id on your computer, and NOT the server.

ssh-copy-id [email protected]

Now when you run ssh [email protected] you will be logged in automatically. Go ahead and SSH again and verify that it doesn't ask for your password before moving onto the next step.

For the next steps, make sure you are logged in as the deploy user on the server!

Choose the version of Ruby you want to install:

The first step is to install some dependencies for Ruby and Rails.

To make sure we have everything necessary for Webpacker support in Rails, we're first going to start by adding the Node.js and Yarn repositories to our system before installing them.

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev software-properties-common libffi-dev nodejs yarn

Next we're going to be installing Ruby using one of three methods. Each have their own benefits, most people prefer using rbenv these days, but if you're familiar with rvm you can follow those steps as well. I've included instructions for installing from source as well, but in general, you'll want to choose either rbenv or rvm.

Choose one method. Some of these conflict with each other, so choose the one that sounds the most interesting to you, or go with my suggestion, rbenv.

Installing with rbenv is a simple two step process. First you install rbenv, and then ruby-build:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.5.1
rbenv global 2.5.1
ruby -v

The installation for rvm is pretty simple:

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
curl -sSL https://get.rvm.io | bash -s stable
source ~/.rvm/scripts/rvm
rvm install 2.5.1
rvm use 2.5.1 --default
ruby -v

Arguably the least useful Ruby setup for development is installing from source, but I thought I'd give you the steps anyways:

cd
wget http://ftp.ruby-lang.org/pub/ruby/2.5/ruby-2.5.1.tar.gz
tar -xzvf ruby-2.5.1.tar.gz
cd ruby-2.5.1/
./configure
make
sudo make install
ruby -v

The last step is to install Bundler

gem install bundler

rbenv users need to run rbenv rehash after installing bundler.

Phusion is the company that develops Passenger and they recently put out an official Ubuntu package that ships with Nginx and Passenger pre-installed.

We'll be using that to setup our production server because it's very easy to setup.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7
sudo apt-get install -y apt-transport-https ca-certificates

# Add Passenger APT repository
sudo sh -c 'echo deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main > /etc/apt/sources.list.d/passenger.list'
sudo apt-get update

# Install Passenger & Nginx
sudo apt-get install -y nginx-extras passenger

So now we have Nginx and passenger installed. We can manage the Nginx webserver by using the service command:

sudo service nginx start

Open up the server's IP address in your browser to make sure that nginx is up and running.

The service command also provides some other methods such as restart and stop that allow you to easily restart and stop your webserver.

Next, we need to update the Nginx configuration to point Passenger to the version of Ruby that we're using. You'll want to open up /etc/nginx/nginx.conf in your favorite editor. I like to use vim, so I'd run this command:

sudo vim /etc/nginx/nginx.conf
# You could also use nano if you don't like vim
# sudo nano /etc/nginx/nginx.conf

Find the following lines, and uncomment them:

##
# Phusion Passenger
##
# Uncomment it if you installed ruby-passenger or ruby-passenger-enterprise
##

include /etc/nginx/passenger.conf;

Save and close nginx.conf. Then open /etc/nginx/passenger.conf in your editor to modify the ruby line:

sudo vim /etc/nginx/passenger.conf

# You could also use nano if you don't like vim
# sudo nano /etc/nginx/passenger.conf

And change the passenger_ruby line to point to your ruby executable:

passenger_ruby /home/deploy/.rbenv/shims/ruby; # If you use rbenv
# passenger_ruby /home/deploy/.rvm/wrappers/ruby-2.1.2/ruby; # If use use rvm, be sure to change the version number
# passenger_ruby /usr/bin/ruby; # If you use ruby from source

The passenger_ruby is the important line here. Make sure you only set this once and use the line from the example that pertains to the version of Ruby you installed..

Once you've changed passenger_ruby to use the right version Ruby, you can run sudo service nginx restart to restart Nginx with the new Passenger configuration.

Now that we've restarted Nginx, the Rails application will be served up using the deploy user just how we want. In the Capistrano section we will talk about configuring Nginx to serve up your Rails application.

Setting up your production database is pretty easy. Make sure to keep in mind that you should use a different password for your production databases.

Depending on what database you want to use, follow the steps related to the database:

Installing MySQL

All you need to do in order to install MySQL is to run the following command:

sudo apt-get install mysql-server mysql-client libmysqlclient-dev

You can use the root user and password set during installation for your database or you can add a new user to MySQL.

Installing PostgreSQL

Postgres 9.3 is available in the Ubuntu repositories and we can install it like so:

sudo apt-get install postgresql postgresql-contrib libpq-dev

Next we need to setup our postgres user:

sudo su - postgres
createuser --pwprompt
exit

The password you type in here will be the one to put in your my_app/current/config/database.yml later when you deploy your app for the first time.

For Capistrano, make sure you do these steps on your development machine inside your Rails app.

The fancy new verison of Capistrano 3.0 just shipped and we're going to be using it to deploy this application.

The first step is to add Capistrano to your Gemfile:

gem 'capistrano', '~> 3.1.0'
gem 'capistrano-bundler', '~> 1.1.2'
gem 'capistrano-rails', '~> 1.1.1'

# Add this if you're using rbenv
# gem 'capistrano-rbenv', github: "capistrano/rbenv"

# Add this if you're using rvm
# gem 'capistrano-rvm', github: "capistrano/rvm"

Once these are added, run bundle --binstubs and then cap install STAGES=production to generate your capistrano configuration.

Next we need to make some additions to our Capfile to include bundler, rails, and rbenv/rvm (if you're using them). Edit your Capfile and add these lines:


require 'capistrano/bundler'
require 'capistrano/rails'

require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

# If you are using rbenv add these lines:
# require 'capistrano/rbenv'
# set :rbenv_type, :user # or :system, depends on your rbenv setup
# set :rbenv_ruby, '2.0.0-p451'

# If you are using rvm add these lines:
# require 'capistrano/rvm'
# set :rvm_type, :user
# set :rvm_ruby_version, '2.0.0-p451'

After we've got Capistrano installed, we can configure the config/deploy.rb to setup our general configuration for our app. Edit that file and make it like the following replacing "myapp" with the name of your application and git repository:

set :application, 'myapp'
set :repo_url, '[email protected]:excid3/myapp.git'

set :deploy_to, '/home/deploy/myapp'

set :linked_files, %w{config/database.yml}
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  after :publishing, 'deploy:restart'
  after :finishing, 'deploy:cleanup'
end

Now we need to open up our config/deploy/production.rb file to set the server IP address that we want to deploy to:

set :stage, :production

# Replace 127.0.0.1 with your server's IP address!
server '127.0.0.1', user: 'deploy', roles: %w{web app}

If you have any trouble with Capistrano or the extensions for it, check out Capistrano's Github page.

Thankfully there aren't a whole lot of things to do left!

Adding The Nginx Host

In order to get Nginx to respond with the Rails app, we need to modify it's sites-enabled.

Open up /etc/nginx/sites-enabled/default in your text editor and we will replace the file's contents with the following:

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        server_name mydomain.com;
        passenger_enabled on;
        rails_env    production;
        root         /home/deploy/myapp/current/public;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

This is our Nginx configuration for a server listening on port 80. You need to change the server_name values to match the domain you want to use and in root replace "myapp" with the name of your application.

Connecting The Database

You can run cap production deploy to deploy your application.

The file config/database.yml needs to be updated for the production database server username, password, and host. You can set host to "localhost" and you will have to create a database on the server with the same name. Capistrano won't create it for you because it's something that should really only happen once. After deploying you can set create it by SSHing in and running RAILS_ENV=production bundle exec rake db:create in your app's /home/deploy/myapp/current directory (just change "myapp" to match the name of your app).

Something you should consider is only storing the database credentials on the server and having Capistrano symlink the database.yml file so that it doesn't have to be stored in git. This is especially important when you have a public git repository and don't want to publish your database credentials.

Restarting The Site

One last thing you should know is that restarting just the Rails application with Passenger is very easy. If you ssh into the server, you can run touch myapp/current/tmp/restart.txt and Passenger will restart the application for you. It monitors the file's timestamp to determine if it should restart the app. This is helpful when you want to restart the app manually without deploying it.

Conclusion

And there you have it, a very long-winded explanation of all the different things you need to do while setting up an application to be deployed. There is a lot of system administration pieces that can expand upon this, but that's for another time. Please let me know if you have any questions, comments, or suggestions!



Discussion


Gravatar
Grigory Reznichenko on

The following commands should be slightly modified:
cap install STAGES=production
cap production deploy

I believe it should be the following:
bundle exec cap install STAGES=production
bundle exec cap production deploy

If you run 'cap' directly from the shell, it searches standard linux PATH and says that cap is not installed.
In other words, the binary is in gems folder ( ~/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/capistrano-3.1.0/bin/cap ) and should be called with bundle exec.

At least that's what I found out trying to replicate the installation.

Gravatar

I believe, if you run rbenv rehash after installing the capistrano gem, the executable should become available without having to run bundle exec. I could be wrong, but that's also the same way that gets the rails command available.


Gravatar

Thanks for this guide, it's my first time trying to deploy an app in rails. With a little help from google and stackoverflow I managed to set it all up and finally created a db, but when I visit my site in the browser I get an error page. It says to check my log file in var/log/nginx but when I try to go there it says:
-bash: cd: nginx: Permission denied

Any idea how I can see the error log? and also do I maybe need to do anything else not mentioned in this guide to get the site live?

Gravatar

You need to add a beginning slash to that command: cd /var/log/nginx/ or just view it by doing sudo less /var/log/nginx/error.log

That file will have your Nginx and passenger logs, but your Rails app will contain your Rails errors. Use less /home/deploy/MYAPP/current/log/production.log to view that.

If you send me your error, I can give you some more guidance on fixing it.

Gravatar

Thanks for the fast reply! when I try: less /var/log/nginx/error.log I still get the permission denied error. The production.log is empty so I guess there are no rails errors.

Gravatar

Oh sorry, run it as root with sudo less /var/log/nginx/error.log because the /var/log folder is owned by root.

Gravatar

Thanks! I found this error:

[ 2014-05-19 11:41:44.9304 807/7fb260d9f700 agents/HelperAgent/RequestHandler.h:2222 ]: [Client 20] Cannot checkout session.

Error page:

An error occurred while starting up the preloader. It exited before signalling successful startup back to Phusion Passenger. Please read this article for more information about this problem.

<h2>Raw process output:</h2>


*** ERROR ***: Cannot execute /home/deploy/.rvm/bin/passenger_ruby: No such file or directory (2)

EDIT:
googled on it, read the link in the error log, but were no help.

Gravatar

It looks to me like it cannot find your version of Ruby. Did you modify your nginx config to point to the correct location? Basically, it is saying that /home/deploy/.rvm/bin/passenger_ruby is not a valid ruby executable.

If you are using rvm, you'll want to set passenger_ruby to something like this

passenger_ruby /home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby

Change you ruby version accordingly. You can always cd into these folders to verify what is available.

It appears I never gave an example for rvm, so sorry on the confusion.

Gravatar

No worries. where can I find the config file?

My ruby version is indeed 2.1.2, should I place the line:

passenger_ruby /home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby

in the config or run it on the command line. Running it gives:
passenger_ruby: command not found

Gravatar

You want to edit /etc/nginx/nginx.conf and place it in there. See the instructions at the bottom of the Installing Nginx section for more on that.

Gravatar

ah, I think I just skipped that because I didn't see it for RVM.

when I set what you suggest I get the following error:

[ 2014-05-19 12:52:47.4277 1338/7fbd3086e700 agents/HelperAgent/RequestHandler.h:2222 ]: [Client 20] Cannot checkout session.

Error page:

You've set the `PassengerRuby` (Apache) or `passenger_ruby` (Nginx) option to '/home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby'. However, because you are using RVM, this is not allowed: the option must point to an RVM wrapper script, n

ot a raw Ruby binary. This is because RVM is implemented through various environment variables, which are set through the wrapper script.

To find out the correct value for `PassengerRuby`/`passenger_ruby`, please read:

http://www.modrails.com/doc...

http://www.modrails.com/doc...

Scroll to section 'RVM helper tool'

----

I tried to add:

passenger_ruby /usr/local/rvm/wrappers/ruby-2.1.2-p95/ruby

as described here: http://www.modrails.com/doc... (rvm helper tool)

but I discovered there is no rvm folder in /usr/local, and I can't locate it anywhere else..

EDIT:
Fixed it! I had to put:
passenger_ruby /home/deploy/.rvm/wrappers/ruby-2.1.2/ruby

now I only need to find out how to move my local database to the server.

Thanks for the help on having my app deployed :)

Gravatar

Oh awesome, thanks for posting the fix. I'll be sure to update the tutorial so no one else has to go through this trouble. ;)

If you're on a mac, Sequel Pro can export and import databases very nicely. Otherwise there is mysqldump or the taps gem that could help.

Gravatar

I'm on Ubuntu. It's a new app so later I realized I only needed a rake db:migrate.

Anyways, thanks a lot for the help, and the guide!

Gravatar

Absolutely, glad you got it working and thanks for pointing out the rvm thing!

Gravatar

Im following the tutorial very close but i get lost when you say "You'll want to open up /etc/nginx/nginx.conf in your favorite editor, find the following lines, and uncomment them:"

Since i am logged in as deploy. How do i get to that file. My assumption is that this file is on the server. Would i need to login as root to get to it?

sudo nano /opt/nginx/conf/nginx.conf brings an empty file.

Gravatar

You want to run sudo nano /etc/nginx/nginx.conf instead (not the /opt one).

You can see the file as your deploy user but you can't actually save changes. That's why you need sudo so that you can save your changes.


Gravatar
Chris Zempel on

Hey, small typo thing: if you select to install with 2.0.0-p481

the Capfile section still says:

# set :rbenv_ruby, '2.0.0-p451'
# set :rvm_ruby_version, '2.0.0-p451'


Gravatar

I'm having capistrano failing on this command of deployment [ -f home/deploy/codeblog/repo/HEAD ]

Gravatar

actually, it looks like that failure is fine.. however when it's trying to mirror my git repo it's giving me this error: fatal: destination path 'home/deploy/codeblog/repo' already exists and is not an empty directory. When i ssh into the server and look at the file structure that folder isn't there.

Gravatar

What did you set for your repo_url?

Gravatar

I have it set to the public repo on github

Gravatar
Bhuwan Arora on

is the issue resolved? I am facing the same error. Though I have the repo folder created with git branches, hooks etc

Gravatar
Gravatar

Awesome! glad you got that figured out and thanks for sharing. I'll be sure to note this for the future.


Gravatar

Gravatar

When I run the command (gem 'capistrano', '~> 3.1.0' It returns this error "unknown command capistrano" any ideas why this might be happening?

Gravatar

I think because that's not a command you run in your terminal but you need to add that to the file named Gemfile instead.


Gravatar
Jakub Kuchar on

This is tutorial is awesome, but i got server hacked withing 3 days on digital ocean. Be sure you close ssh with login/password http://lani78.com/2008/08/0...

Gravatar

Ouch! Did you have a short password?

Gravatar
Jakub Kuchar on

Yep i had it short, my bad. But even on my second droplet (with strong password) i have seen some Chinese ip logged in via SSH.

Gravatar

Dang. Well, one good practice is to always disable password authentication with SSH. http://askubuntu.com/questi...

I'll probably add this step into the tutorial tomorrow because that's no fun at all.


Gravatar

Awesome tut, thank you very much.

I managed to deploy but I have an error "We're sorry, but something went wrong."

when i type sudo less /var/log/nginx/error.log i get the following.

[ 2014-06-17 04:55:18.8418 903/7f6b1e392700 agents/HelperAgent/RequestHandler.h:2262 ]: [Client 20] Cannot checkout session.

Error page:

Your Ruby version is 1.9.3, but your Gemfile specified 2.1.2 (Bundler::RubyVersionMismatch)
/home/deploy/.rvm/gems/ruby-2.1.2/gems/bundler-1.6.3/lib/bundler/definition.rb:390:in `validate_ruby!'
/home/deploy/.rvm/gems/ruby-2.1.2/gems/bundler-1.6.3/lib/bundler.rb:116:in `setup'
/home/deploy/.rvm/gems/ruby-2.1.2/gems/bundler-1.6.3/lib/bundler/setup.rb:17:in `<top (required)="">'

**omitted same lines***

rails -v

WARNING:root:could not open file '/etc/apt/sources.list.d/passenger.list'
The program 'rails' can be found in the following packages:
* ruby-railties-3.2
* ruby-railties-4.0

ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]

Been trying the whole day. May you please help.

Gravatar

Double check that you set your nginx passenger_ruby to point to RVM or Rbenv properly and that you set the global ruby version to 2.1.2.

Gravatar

This is how it looks like.

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby;

and

:~$ which ruby
/home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby

Gravatar

Try changing it to passenger_ruby /home/deploy/.rbenv/shims/ruby; and restarting nginx to see what happens. I think pointing directly to that version of Ruby should work, but I've also always just pointed it to the shim.

Gravatar

Error still persists

which ruby
/home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
#passenger_ruby /home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby;
passenger_ruby /home/deploy/.rbenv/shims/ruby;

Gravatar

My bad. I misread. You're using rvm so that wouldn't help anyways. Try:

passenger_ruby /usr/local/bin/passenger_ruby;
Gravatar

Ooops, just did that and still no luck. How come when i type which ruby i always get the same answer regardless of what passenger_ruby looks like?

which ruby
/home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby

I can also run migrations.

Gravatar
Daniel Baldwin on

Having had a similar issue, it seems that the answer is not to use the output for 'which ruby' when using RVM.

The output left in /var/log/nginx/error.log told me:

You've set the `PassengerRuby` (Apache) or `passenger_ruby` (Nginx) option to '/home/deploy/.rvm/rubies/ruby-2.1.2/bin/ruby'. However, because you are using RVM, this is not allowed: the option must point to an RVM wrapper script, not a raw Ruby binary. This is because RVM is implemented through various environment variables, which are set through the wrapper script.

To find out the correct value for `PassengerRuby`/`passenger_ruby`, please read:

https://www.phusionpassenge...

Gravatar

My solution was to start over and all well.

Gravatar
Daniel Baldwin on

That's good to hear.

Did you use the same [.rvm] path second time around?

Gravatar

yes. I followed the one on the tutorial.

Gravatar
Gonzalo Sanchez on

in RVM passenger_ruby should point to /home/deploy/.rvm/wrappers/ruby-2.1.2;

Gravatar

Looks like i have a different error from restart the server.

https://gist.github.com/vez...

I really don't want to use Heroku and i will not give up.

Gravatar

Hmm, looks like it's similar issue. One last suggestion from my server that I have running apache instead of Nginx (but still uses Passenger) is to use this for passenger_ruby:

passenger_ruby /usr/local/rvm/wrappers/ruby-2.1.2/ruby

It's possible the wrapper helps it load the proper version. This is one of the problems with rvm in the sense that it integrates almost too much with your environment causing it to be a headache to set up at times.

Gravatar

Hi Chris, Thank you for your help yesterday. Sorry i could not find a way to contact you privately. I ended rebuilding the droplet and all works perfect now. Again thank you.

Gravatar

Good to hear but sorry you had to rebuild! There's a link to the about page in the footer that has my email address on it if you need to get ahold of me in the future.

Gravatar
Luiz Augusto on

Hi. Which passenger_ruby is working for you? I`m having the same problem :/

Gravatar

Try

passenger_ruby /usr/local/rvm/wrappers/ruby-2.1.2/ruby

but replace that version of Ruby with the one you installed in case it is different.

Gravatar
Luiz Augusto on

It worked. Now i'm having this error:
http://pastebin.com/z0DEw2Uj

I've tried adding gem 'dotenv-rails' and added a .env file in my /home/deploy/myapp, but it doesn't work.

Gravatar

Well, it's saying that you should update your config/secrets.yml to include a section for production. You can either set it up in the file and commit it, or you can remove it from git and set it up to link the file on deploy just like your database.yml

Gravatar
Luiz Augusto on

Oh, my bad. I didn't realised that I could solve it the same way I did with database.yml. Thanks! :D I'm new to all this stuff

Where should I look for application errors (500) log? There is a way to enter in console mode (rails console)?

Gravatar

Yep! For error logs, check out this file for your production logs: /home/deploy/MYAPP/current/log/production.log


Gravatar
Daniel Baldwin on

Hi, thanks for the tut, it seems like a very concise and informative resource.

I seem to have hit an issue though, when running:

cap production deploy

I get an error:

ERROR linked file /home/deploy/my_actual_app_name/shared/config/database.yml does not exist on my.server.ip.address
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host my.server.ip.address: exit

The backtrace is pretty unhelpful but the tasks: TOP suggests the issue is originating (as expected) from config/deploy.rb

Tasks: TOP => deploy:check:linked_files

I am using Figaro for keeping my password out of git but that should have nothing to do with the file being sent to the server right?

would you happen to know what may be going wrong here?

Thanks in advance

Gravatar

Hey Daniel,

You'll need to manually create a database.yml file on your server. It's trying to link it but it hasn't been created yet. So you can ssh in and edit that file

nano /home/deploy/my_actual_app_name/shared/config/database.yml

and put in your database config for the server database that you just setup.

Gravatar
Daniel Baldwin on

Thanks Chris.

That makes sense now. I assume that there are ways to automate this part of the process but I guess it's also an idea to do it manually for the extra layer of control it grants.

I also hit a few other issues after this (and so have yet to actually deploy) but seem to be making steady progress now.

Thanks again.

Gravatar

Sometimes people keep database.yml in their repository but then your production password is saved in your code repo so a lot of people choose not to do it that way.

Let me know if I can help out with any of the other issues!

Gravatar
Daniel Baldwin on

Thanks again, I managed to get through it soon enough after this issue.

My business partner actually decided to use Figaro for exactly that purpose. It means that we can keep the database.yml file in version control whilst keeping the particulars locally secured.

The snippet here:

https://gist.github.com/pat...

helped somewhat with getting the application.yml file onto the server but I found that because we were using Devise I had to change the line:

after "deploy:symlink:release", "figaro:symlink"
to
before "deploy:compile_assets", "figaro:symlink"

A nice list of all the built-in Capistrano hooks (the flow) can be found here:
http://capistranorb.com/doc...

Gravatar

Awesome stuff. Thanks for sharing Daniel.

Gravatar
andre bautista on

Hi Chris,

I followed these steps in creating a database.yml file in the listed directory and I'm getting the error

"rm stdout: Nothing written
rm stderr: rm: cannot remove ‘/home/deploy/gymsight/releases/20140630064741/config/database.yml’: No such file or directory"

Any ideas on how to get past this?

Gravatar

Hmm, that's odd. It shouldn't be trying to remove the file. Can you send over some more of your logs in a github gist?

Gravatar
andre bautista on

https://gist.github.com/and...

So the error has changed magically, but it appears as though it's trying to access all the branches of my repo even though I'm specifying "set :branch, 'master'" in the deploy file.

Gravatar

That's okay because it is just cloning the repository. It looks like the symlink is crashing possibly because /home/deploy/gymsight/shared/config/database.yml doesn't exist. Have you double checked that file exists?

Gravatar
andre bautista on

Just checked, file is there. I also edited the gist to show my latest error message.

Gravatar

Looks like you've already got a database.yml in your repo. Either remove the symlink on deploy and add your credentials to that file, or remove the file from git so that it can symlink on deploy.

Gravatar
andre bautista on

I don't have a database.yml in the remote repo. (https://github.com/andrebau... )
Here's my deploy.rb file, I think the error might be in the deploy itself, I'm still trying to decipher what all these things mean.
https://gist.github.com/and...

Gravatar

Interesting, that all looks correct to me.

Gravatar
andre bautista on

Do you have a public repository with this kind of set up? It could also be my production.rb file causing issues. https://gist.github.com/and...

Gravatar
Gravatar
andre bautista on

The repo helped me work through most of the problems. Just need to clarify one thing now. In the database.yml file the username should be "postgres" and the password is the password we entered when we created "postgres"? I'm able to sign into the user fine if I "su postgres" but when I use those credentials in the database.yml file to create a DB, after signing back into deploy, I get the error FATAL: password authentication failed for user "postgres".

Gravatar

I guess, just double check that you've got it in the right format then. Can't think of anything else that would be wrong. You're pretty close now!

Gravatar
andre bautista on

sigh...Heroku won this battle

Gravatar

Dang! :\ To be fair, Heroku's simplicity is pretty darn impressive and I don't blame you.

If you ever do need to get your site running on a VPS, shoot me an email and we can do a short one-on-one gig and I can probably get you squared away.


Gravatar

Where is the Gem File ? Please give me the exact location of the Gemfile.
"like /home/rails or /etc/nginx etc."
To add the lines :

gem 'capistrano', '~> 3.1.0'
gem 'capistrano-bundler', '~> 1.1.2'
gem 'capistrano-rails', '~> 1.1.1'

# Add this if you're using rbenv
# gem 'capistrano-rbenv', github: "capistrano/rbenv"

Gravatar

The Gemfile is in the top folder in your Rails application.


Gravatar

Hello Chris,

Here is the error I see when I try to run the command bundle --binstubs

[email protected]:~/AsachTimepass$ bundle --binstubs

/home/deploy/.rbenv/versions/2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- bundler (LoadError)

from /home/deploy/.rbenv/versions/2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'

from /usr/bin/bundle:7:in `<main>'

I am using passenger_ruby /home/deploy/.rbenv/shims/ruby;

in the nginx.conf file, but it still doesnt work.

Can you help me ?


Gravatar
Bhuwan Arora on

I have managed to go through and run the complete tutorial, but after running touch APP-NAME/current/tmp/restart.txt I only see an nginx welcome page on the server IP. How can I debug the problem.

These are my config files
config/deploy.rb http://pastebin.com/1SXMDYvS
config/deploy/production.rb http://pastebin.com/ZYGejqJF
/etc/nginx/sites-enabled/default http://pastebin.com/0JNG54KH

I also tried with SERVER-IP instead of WEB-ADDRESS in server-name in /etc/nginx/sites-enabled/default

Where am I go wrong

Gravatar
Bhuwan Arora on

Ahh I found out I had created a backup for nginx.conf with the name nginx.conf.backup and that was creating all the problem..


Gravatar
Nick DelRossi on

Thanks for the tutorial.

I want to add a helpful tip incase anyone else's Rails app has SSL enabled and is not working.

If you have enabled SSL/https on your Rails app, you will need to add another step to this process. I went through this tutorial and was getting ERR_CONNECTION_REFUSED in chrome when I tried to get to my site. I am new to this and it took me hours before I realized what the problem was.

If you follow the steps in this article it should fix the issue.
https://www.digitalocean.co...

Gravatar

Thanks for sharing Nick!


Gravatar
Jakub Kuchar on

Soon i would like to write a deployment guide for opensource project https://github.com/sharetri... from non-server guy perspective. And this guide playing a big role, i hope you wouldn't mind that i will reference it via link?

Gravatar

I don't mind at all Jakub. Let me know if there's anything I can help with.


Gravatar
Chris Sciolla on

Hi Chris, I've followed this tutorial exactly and I'm getting the following error and can't figure out why. I also have no idea why example.com is there...

cap production deploy:check

[68f3b617] Running /usr/bin/env [ ! -d ~/.rbenv/versions/2.0.0-p481 ] on ***.***.***.***
[68f3b617] Command: [ ! -d ~/.rbenv/versions/2.0.0-p481 ]
[d8d5b994] Running /usr/bin/env [ ! -d ~/.rbenv/versions/2.0.0-p481 ] on example.com
[d8d5b994] Command: [ ! -d ~/.rbenv/versions/2.0.0-p481 ]
[68f3b617] Finished in 1.144 seconds with exit status 1 (failed).

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing on host example.com: No route to host - connect(2)

Errno::EHOSTUNREACH: No route to host - connect(2)

Tasks: TOP => rbenv:validate

Any ideas? Thanks for taking the time to write this up.

Gravatar

Check your config/deploy/production.rb file to make sure it doesn't have example.com in it. I would guess that's where it is coming from. Swap that with your domain or IP and you should be good.

Gravatar
Chris Sciolla on

That's the weird thing. I only have the correct IP address in there. do I need to run any commands if I change production.rb? re-commit to github on restart the production server?

Gravatar

Make sure the file is saved, but that's all you should need to do. You can try doing a project wide search in your text editor to find "example.com". That should point you to it.

Gravatar
Chris Sciolla on

ughhhhh. can't believe I missed that in production.rb in the roles. sorry for the stupid question...

Gravatar

I've had times where I went through everything and I couldn't find it so I ended up deleting all the files and starting from scratch so I know the feeling well. ;-)

Gravatar
Chris Sciolla on

I got the dreaded, We're sorry , but something went wrong and have no idea where to start looking. I got a bunch of fails during the cap build, many similar to:

Command: [ -L /home/deploy/*****/releases/20140627215511/tmp/
Finished in 0.051 seconds with exit status 1 (failed).

Gravatar

Sometimes having failed commands is good. It occasionally checks to see if it needs to create a directory like this one so it fails because it already exists which is totally okay.


Gravatar

Hey, thanks a lot for this tutorial. This is one of the most comprehensive one that I've come across thus far!

I am running into some trouble however. For some reason, the app that is actually up and running on my server is an older version (from like two months ago) of my application, but the "current" version of the app is my desired up-to-date one. (I see this when I review the code in that directory.)

I've specified that the master branch should be deployed, restarted the web and app servers, precompiled assets. But, I still have this older version running.
(I am having the same problem this person had http://stackoverflow.com/qu...

Does anyone have any ideas as to why this may be the case?

Gravatar

One thing is to check and make sure your config points to the right directory. It definitely has happened to me before, but it is almost always a case of either reading the wrong config or the config pointing to the wrong folder.

Gravatar

Thank you! I double checked the config.

It turned out that the problem was not cap but my own code.

For anyone reading this if your site looks like an older version of your site, it might just be that your assets are not loading properly.

It turns out that my custom stylesheet was not actually loading, and there was an error in the precompilation of assets because of this.

One way to check for that is by (if you're using chrome) go to a page on your app, open the inspect tool (ctrl + i), go to the network tab, refresh your page. Look for any red links (stylesheets or assets that are not loading). This is a problem with your code not capistrano. The code for loading specific stylesheets was working on my local machine, but it didn't work in production. So double check that. :]

Gravatar

Oh! That's an interesting one. It has happened to me before but that definitely is an obscure one. I'm glad you got it figured out!


Gravatar
Felipe Campos Clarke on

this was very useful for me. Thank you very much for the article!


Gravatar

Hi, thanks for this tutorial, I tried to follow every step, I deployed the app with some fails
http://pastebin.com/zgkQXcqE

the vps still showing the nginx welcome message, I can't figure out why!

Gravatar

Your deploy was successful. The failures are supposed to happen.

Make sure you point nginx to /home/deploy/sample_app/current/ and restart it.

Gravatar

Just checked, default file in /etc/nginx/sites-enabled/ is filled with correct values, it's weird

root /home/deploy/sample_app/current/public;

Gravatar

You can check the nginx log then for errors and you should find something there. Could be syntax errors for example.

Gravatar

There was no error in syntaxe, but it woked after commenting those lignes:

# listen 80 default_server;
# listen [::]:80 default_server ipv6only=on;

Gravatar

Glad you found it!


Gravatar
Rafal Szymanski on

Thanks for this, quite helpful. I'm having an issue with capistrano.

cap production deploy

results in

cap aborted!
Don't know how to build task 'deploy:updated'

with a bunch of other errors after it. I think I set everything up as shown here though – any ideas how to solve this?

Gravatar

I think this comes from your Capfile not being configured appropriately. Double check that step and make sure you've got all the correct require statements.

Gravatar
Rafal Szymanski on

Thanks yep, managed to get it working, it was indeed about the Capfile. `cap install` wasn't working for the same reason. If anyone has the same issue, making sure that

require 'capistrano/setup'
require 'capistrano/deploy'

appears at the top of the Capfile fixed this for me. cheers

Gravatar

Glad you got it! :)


Gravatar

Hey Chris, thanks for providing this walkthrough, it's been mostly a breeze. One thing I'm stuck on however is generating the database. When I run RAILS_ENV=production bundle exec rake db:create in the /home/deploy/myapp/current directory, substituting "myapp" for the actual name of my app or course, the vps tells me ruby 2.1.1 is not installed, so I install it, then it wants me to bundle install, and so I do, and finally I'm stuck with "Gem::Ext::BuildError: ERROR: Failed to build gem native extension." type errors as the gems fail to compile. Where did I go wrong? I'd be happy to supply much more insight into this issue, up to and including access to the vps! thanks in advance.


Gravatar

Hi,
Thanks for the tutorial. I'm having trouble uncommenting the /etc/nginx/nginx.conf file. It says I have read only permission and cannot edit it, even though I followed the previous steps of setting the permissions. How do I fix this? Thanks again.

Gravatar

Make sure you open up the file using sudo before. So either "sudo vim /etc/nginx/nginx.conf" or "sudo nano /etc/nginx/nginx.conf"

Gravatar

Thanks a lot, that works. :)


Gravatar

Hi Chris

When I ran the commend `cap install STAGES=production`, I came across the following issue.

```

cap aborted!

ArgumentError: invalid byte sequence in US-ASCII

(See full trace by running task with --trace)

cap aborted!

NoMethodError: undefined method `deploying?' for #<capistrano::application:0x007fe88153d1c8>

```

I ran this commend on my local machine, not server end.

Gravatar

Sounds like you might have a foreign character somewhere in there that isn't US-ASCII. Are you using UTF8 characters anywhere?


Gravatar

When I use 'cap install STAGES=production' i get error kernel_require.rb:55:in `require': cannot load such file -- capistrano/cli (LoadError)
Any ideas to fix it?


Gravatar

Good article, I would like to see how a simple setup like this could be provisioned with Chef. Future article maybe?

Gravatar

Thanks Ben, definitely plan on doing that. Chef scripts are super duper awesome and it's incredibly useful. Hopefully I'll be able to do that soon!

Gravatar

That would be great! I did also find your Chef/Vagrant article to be particularly helpful.


Gravatar

Great Tutorial,

but I am getting:

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing on ip_address: Authentication failed for user [email protected]_address

/home/user/.rvm/gems/[email protected]/gems/net-ssh-2.9.1/lib/net/ssh.rb:219:in `start'

Any ideas how to get authentication working?

Gravatar

[email protected]_address

It looks like you didn't change user or ip_address to the actual user account or IP number. Change that and it should work.

Gravatar

Hi Chris,

Thanks for the reply... but ip_address is just a place holder for this post... I have the actual ip_address in place when i get that error.

Gravatar

Ah okay, then check that your config matches your ssh credentials. You've got something different in your config than what you use when connecting over ssh manually.

Gravatar

this is my production.rb

role :app, %w{[email protected]_ip_address}
role :web, %w{[email protected]_ip_address}
#role :db, %w{[email protected]_ip_address}

server 'actual_ip_address', user: 'actual_user', roles: %w{web app}, my_property: :my_value

# Global options
# --------------
set :ssh_options, {
keys: %w('/home/actual_user/.ssh/id_rsa'),
forward_agent: true,
auth_methods: %w(publickey)
}
#

not sure what I am doing wrong.

Gravatar

Get rid of the keys line in ssh_options. You have to login to the server with your local ssh key, not your remote user's key. It will do this by default and same with auth_methods. You can leave forward_agent but can get rid of the rest.

Gravatar

Still no luck :(

Do you have an email I can contact you personally?


Gravatar

Hi chris, what's the difference with PUMA ? best performance ?

Gravatar

Depends on what you want to do, but generally Passenger is quite good on all fronts. You can read some more about some performance testing but no matter what, it isn't going to be definitive that one is always better than another. https://blog.engineyard.com...


Gravatar
hadifarnoud on

Thanks for awesome guide! just a heads up, in Capfile part you didn't change Ruby version. I chose 2.1.2 but in Capfile it's still 2.0.0-p451.

I changed it to 2.1.2 and all works now,

Gravatar

Oh hey, good find. I'll be sure to update that soon.


Gravatar

I have setup nginx + passenger on EC2 instance ubuntu 14.04. I successfully get first page "Welcome aboard" but when I try to get some controller's action I get "page not found 404" error.

Configuration in sites_enabled/default is as given below

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

server_name localhost;
passenger_enabled on;
rails_env production;

location / {

root /home/ubuntu/myapp/public;

}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}


Gravatar

how can I run rake on server? I tried to do it via ssh by root and deploy. they both give me following error:

ActiveRecord::NoDatabaseError: FATAL: role "deploy" does not exist

should I run rake via Capistrano? if so, how?


Gravatar
Mark Murphy on

It would be awesome if you could also include how to set up a background job processor like Sidekiq or Resque as a service in ubuntu.

Gravatar

Absolutely! I'll probably plan on covering this in a screencast or a separate tutorial.


Gravatar

I'm having this problem
$ cap production deploy
DEBUG[e90accc1] Running /usr/bin/env [ -d ~/.rvm ] on xxx.xx.xxx.xxx
DEBUG[e90accc1] Command: [ -d ~/.rvm ]
DEBUG[f6a43b18] Running /usr/bin/env [ -d ~/.rvm ] on domain.com
DEBUG[f6a43b18] Command: [ -d ~/.rvm ]
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host domain.com: Connection refused - connect(2)

my config/deploy/production.rb is:

role :app, %w{domain.com}
role :web, %w{domain.com}

set :stage, :production

server 'xxx.xx.xxx.xxx', user: 'user_name', roles: %w{web app}

my /etc/nginx/sites-enabled/default is:

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

server_name domain.com;
passenger_enabled on;
rails_env production;
root /home/user_name/apps/app_name/current/public;

# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {OA
root html;
}
}

Any advise?

Gravatar
Gravatar

I 'm not being able to correct this problem... =(

In my production.rb I have:

set :ssh_options, {
keys: %w(/home/deploy/.ssh/id_rsa),
forward_agent: true
}

So, in my authenticated keys I have the public key with which I SSH the remote server from my local machine and also SSH the git repository. But it continues to give me this problem

cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host domain.com: Authentication failed for user [email protected]

Any suggestion?

Gravatar

Don't specify the keys option there. Your local key in ~/.ssh/id_rsa will be tried against the server's /home/deploy/authorized_keys file. Capistrano won't allow password authentication, so you must make sure you ran the ssh-copy-id to add your pub key to the server deploy user's authorized_keys file.

Gravatar

I've done both things and unfortunately it doesn't work.

I've run ssh-copy-id from my local machine to the remote machine, so I have the public key in the authorized_keys.

I think that I understand what forward agent is doing... so if I SSH my remote machine from my remote machine, do i need the password from the user 'deploy'?

Gravatar

forward_agent is mainly just used when it checks out your code from Github or the like. It will use the key you deploy with to talk to github instead of a key on the server.

Gravatar

ok. So when I have

cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host domain.com: Authentication failed for user [email protected]

what is exactly the issue? Capistrano isn't able to talk with my domain.com with 'deploy' as a user via SSH? or with github via forward agent?

Gravatar

The first one. It's saying it can't ssh into domain.com as the deploy user. When you ssh in manually with ssh [email protected] that should connect without asking you for a password. That works correctly?

Gravatar

yes, it works fine. That is why I'm so confused

Gravatar

Send a copy of your config to me at [email protected] and I'll see if I can help!

Gravatar

ok, thx

Gravatar

same error on this

Gravatar

Ok, it was due to my port, which wasn't 22. Anyway, right now I'm having this problem :

cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host domain.com: Authentication failed for user @domain.com

Any suggestion? I guess it is related with ssh keys?

Gravatar

Yeah, when it says authentication failed, it means it couldn't connect over SSH. You'll need to tweak your deploy config to make sure it matches your SSH configuration.

Gravatar

I'll try this http://capistranorb.com/doc... and see what happens


Gravatar
Miloš Mihajlović on

Hi guys, great tutorial. :)
I did it exactly the same way like described here prior to reading it and wrote a blog on how to install rbenv globally for all users. Check it out here: http://toschas.com/rbenv-se... .


Gravatar

{You'll want to open up /etc/nginx/nginx.conf in your favorite editor} where can find nginx.conf

Gravatar

It's on the server in the /etc/nginx folder. You can type nano /etc/nginx/nginx.conf or use vim instead to edit it through your SSH connection.

Gravatar

[ Error writing /etc/nginx/nginx.conf: Permission denied ] got error

Gravatar

Oh, yes. Add "sudo" to beginning of the command.

sudo nano /etc/nginx/nginx.conf
Gravatar

how open? where is? /etc/nginx/sites-enabled/default


Gravatar

Nice tutorial, very well explained! @excid3:disqus , could I translate to pt-BR (Brazilian portuguese), to help my Brazilian friends? Thanks a lot.

Gravatar

Thanks for translating! :)


Gravatar

Thanks for the tutorial! I get most of the way through, but when i try running

cap production deploy

I get the 'authentication failed for user [email protected]' message.

I'm able to SSH into my remote server without entering the deploy user's password, so I'm not really sure where else to tweak. My stackoverflow searching hasn't really turned up any easy solutions. I'd appreciate any thoughts that worked for others.


Gravatar

I'm trying to add my ssh key but when I try to log in into the dropplet my password is asked

sh-3.2# ssh-copy-id [email protected]

/usr/local/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/local/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.

sh-3.2# ssh [email protected]
[email protected]'s password:

What should I do?


Gravatar

Hi Chris, Time to add ruby 2.1.3

Gravatar

Done!


Gravatar

good job Chris, any plans to add sidekiq integration to this post?

Gravatar

I'll probably do a screencast on Sidekiq (and other background workers) in the future. For now, you might want to check out this post http://chrisdyer.info/2013/...


Gravatar

I get lost at the nginx.conf part. After editing the file and do a restart I get a [fail] message which I suspect ain't a good thing. When I do which ruby I get /home/deploy/.rvm/rubies/ruby-1.9.3-p547/bin/ruby. (yes i am doing 1.9.3)

Should I have both

passenger_ruby /usr/bin/ruby;
and
passenger_ruby /home/deploy/.rvm/rubies/ruby-1.9.3-p547/bin/ruby
in the conf ?

Gravatar

ah i figured it out

Only one line for passenger_ruby


Gravatar

People still use Capistrano? Dokku FTW


Gravatar
a_disbeliever on

Hi, I am proceeding along with the tutorial, after reading it thoroughly. I find it confusing that the user name is 'deploy' when that term overlaps with Capistrano-installed file and folder names. I used 'deployer' (user) to discriminate from 'deploy' (action). I know this is just a nit, but it cost me some time.

I am deploying to a headless server on my LAN, so I skimmed through the Droplet stuff.


Gravatar

When i start cap production deploy, i have errors:

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing on host 104.131.87.26: ln exit status: 1

ln stdout: Nothing written

ln stderr: Nothing written


Gravatar

After I installed the postgres, I ran the script below
```
sudo su - postgres
createuser --pwprompt

```
However, it showed, "createuser: creation of new role failed: ERROR: role "postgres" already exists"

What's the problem?

Gravatar
Joel Grannas on

same issue here.

Gravatar

How about trying

sudo su - postgres
createuser --interactive

Gravatar
Paul Ericson on

The problem is that installing the postresql apt package creates a role called 'postgres'.

Return to being deploy with:
$ exit

Then run psql as the postgres role with:
$ sudo -u postgres psql

Then set the password:
postgres=# \password postgres

Then to quit:
postgres=# \q

Gravatar
Karl Metum on

try "createuser --pwprompt a_random_user_name" instead


Gravatar
Arjan Frans on

Hey,

Very nice tutorial, it worked for me the first time (with hardcoding the secret and database password). One thing I missed was environment variables, as they are also an important part of deployment. I tried to deploy another project using environment variables, but I couldn't get it to work.

I spend hours looking around on how to get environment variables to work. I used rbenv on my server which needs the 'rbenv-env' plugin. I didn't realize after a few hours that I needed this plugin to get my environment variables to work.

It would be nice to see it added to this tutorial. I am sure others have had problems trying to figure out what the right/easiest way is to achieve this.

Gravatar

Definitely a pain in the butt! I think my personal suggestion for most people is to use Rails' secrets.yml and symlink that on deploy just like database.yml. It works just like environment variables more or less and is builtin to Rails.

Gravatar

Chris - can you elaborate on this or point me to a tutorial on setting this up? I had done this with ENV variables but after my last VPS reboot they all seemed to be lost and I can't recall how I set them before.


Gravatar

I ran `ssh-copy-id [email protected]` and I'm able to SSH into the VPS without having to put in a password, however, when I run `$ cap production deploy` I get this error:

[ecc89106] Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.
DEBUG[ecc89106] Permission denied (publickey).
DEBUG[ecc89106] fatal: Could not read from remote repository.
DEBUG[ecc89106]
DEBUG[ecc89106] Please make sure you have the correct access rights
DEBUG[ecc89106] and the repository exists.
DEBUG[ecc89106] Finished in 0.742 seconds with exit status 128 (failed).
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host xxx.xxx.xxx.xx: exit

I only have `authorized_keys` and `known_hosts` within /home/deploy/.ssh/. Do I need to manually copy over my public/private keys as well?

Gravatar

I changed `set :repo_url, '[email protected]:username/testapp.git'` to `set :repo_url, 'https://github.com/username...` and that fixed the error.


Gravatar
Richard Box on

Thanks for the really clear tutorial. I have however had difficulty getting all of the way through to a working deployment. A couple of points that threw me or might need further clarity are as follows (working with rbenv):

1. The createuser --pwprompt should I believe be createuser [user name] --pwprompt

2. When running the cap commands I need to prefix with bundle exec.

3. The Capistrano section is all run locally, not on the server.

This gets me through to the stage where I deploy, however on running the

bundle exec cap production deploy

I get an error as follows:

rbenv: bundle: command not found

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing on host 109.74.205.192: bundle exit status: 127

bundle stdout: Nothing written

bundle stderr: rbenv: bundle: command not found

/Users/richardbox/Dropbox/Rails/deploy_app/vendor/bundle/gems/sshkit-1.5.1/lib/sshkit/command.rb:97:in `exit_status='

/Users/richardbox/Dropbox/Rails/deploy_app/vendor/bundle/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:148:in `block (5 levels) in _execute'

/Users/richardbox/Dropbox/Rails/deploy_app/vendor/bundle/gems/net-ssh-2.9.1/lib/net/ssh/connection/channel.rb:551:in `call'

/Users/richardbox/Dropbox/Rails/deploy_app/vendor/bundle/gems/net-ssh-2.9.1/lib/net/ssh/connection/channel.rb:551:in `do_request'

I do seem to get past this stage by manually performing sudo apt-get install bundler. However that doesn't seem the right approach to me and when successfully deployed after that I get a passenger error as follows:

cannot load such file -- bundler/setup (LoadError)
/home/deploy/.rbenv/versions/2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/home/deploy/.rbenv/versions/2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:263:in `block in run_load_path_setup_code'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:366:in `running_bundler'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:261:in `run_load_path_setup_code'
/usr/share/passenger/helper-scripts/rack-preloader.rb100in `preload_app'
/usr/share/passenger/helper-scripts/rack-preloader.rb:158:in `<module:app>'
/usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<module:phusionpassenger>'
/usr/share/passenger/helper-scripts/rack-preloader.rb:28:in `<main>'

I'd appreciate any help in overcoming this issue.

Gravatar

You want to run gem install bundler to get the appropriate version on your server. apt-get for any ruby related things is bad with this set up because you'll get conflicting things going on (or at least confusing things).

Gravatar
Richard Box on

Thank-you Chris, that did the job.


Gravatar
Gabriel Czirak on

Hi Chris!

I followed your tutorial but after deploy and putting the IP of the server to the browser I get a message "We're sorry, but something went wrong." I did asset precompile and db:migrate either. I also tried to run the app with webrick on port 3000 and it went all fine. My nginx log file is empty. What do you suggest?

Thank you.

Gravatar

That message comes from the Rails 500 error, so you'll want to check your Rails logs to see what's going wrong there.

Gravatar
Gabriel Czirak on

I was just checking it and there are no errors in production.log whatsoever. The only logs there are successful migrations. I'm using sqlite if that matters.

Thank you

Gravatar
Gabriel Czirak on

Finally got it up and running, a typo in nginx.conf in rvm's path :) Thanks for your time!

Gravatar

Glad you got it working!


Gravatar

Hi, I'm getting this error when I run cap production deploy

DEBUG[9cef5778] Could not locate Gemfile
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host my.server.ip.here: bundle exit status: 10
bundle stdout: Nothing written
bundle stderr: Nothing written

any advice? Thanks!


Gravatar
Vibhoo Mishra on

Very Nice tutorial

but I could not get how to start rails app as no where rails is installed can please get back to me ASAP

Gravatar

You don't have to run it manually like you do in development. When you run Capistrano, it runs bundler which installs the Rails gem. Then, Nginx is always running and it fires up Passenger which starts your Rails app for you. So basically Nginx is the thing that runs your Rails app in production and all you need to do is make sure Nginx is running.

Gravatar
Vibhoo Mishra on

Thank you so much !! & can you provide guidance how to setup using Unicorn?


Gravatar
Magzhan Shokparbayev on

Thanks for your tutorial! but I have one problem with ssh key. When I trying to deploy I had error with ssh key. The problem is that if I authenticate to server via [email protected] it goes via ssh keys but when I try with deploy user it prompts me the password. Should I write deploy's password somewhere like production.rb or do you have any solution? I am very new at deploying projects so any help may help me. Thanks

Gravatar

The goal is not to use passwords for ssh so it is more secure. You'll just need to copy your ssh public key to the deploy user with ssh-copy-id. Double check that you can ssh into deploy without a password so Capistrano can too.

Gravatar
Magzhan Shokparbayev on

Ooh, thanks a lot ! Finally I uploaded my project. And run touch myapp/current/tmp/restart.txt , it created file but it seems didn't restarted. What should I do?
Or should I run bundle exec rails s in current folder and add to IPADDRESS:3000?


Gravatar
Harish Garg on

Step - Installing Ruby using rvm, there is one more step which needs to be added before rvm could be installed...

gpg --keyserver hkp://keys.gnupg.net --recv-keys D39DC0E3


Gravatar
Vibhoo Mishra on

My migration is not running automatically I have added

require 'capistrano/rails/migrations' -> in Capfile

&

before :starting , 'deploy:migrate' -> config/deploy.rb file still my migration is not running

please Help anyone ASAP


Gravatar

Awesome setup


Gravatar
Tony Brown on

Is there a tutorial that I'm missing for this? I guess I will try with one of my rails apps but if someone could provide me a link to the tutorial on how to build this app or explain this part about the Gemfile to me that would be great( I know what a Gemfile is, just not in context to the tutorial)

Gravatar
Tony Brown on

I was able to get one of my Rails up and running on Digital Ocean using this and a tut I found on DO community site. Thanks Chris for all your hard work that went into this site


Gravatar

is it the same method on EC2

Gravatar

Yep, pretty much the same thing aside from they connect you differently with .pem keys instead of a password to login initially. May also have to open up the ports to the outside world so you can server HTTP requests.

Gravatar

What about rubber ??

Gravatar

If you're shooting for a complex setup, Rubber is probably good. This is just a simple Rails App and MySQL or Postgres instance on the same server.

Gravatar

thanks for the quick replies


Gravatar

is it possible to deploy by using git to push the rails up to the server and then use the same nginx with passenger configurations

Gravatar

Yep. You can set it up to do a git push like Heroku does, but I've never set a server up that way before so you'll probably need to do some digging to figure out how to do it. Check out this: https://www.digitalocean.co...


Gravatar
Magzhan Shokparbayev on

Hi Chris! Can you help me ?. I get "We're sorry, but something went wrong." then I run "sudo nginx -t" it says syntax is ok and nginx.conf test is successful. What should I do?

Gravatar

Check your /home/deploy/APP/current/logs/production.log file for the errors. That's the error page from Rails so Nginx is set up properly but Rails isn't just yet.

Gravatar

Hey Chris and Magzhan,

I've got the same problem at the moment with my nibli site (chris you'll remember doing the code cast for me:) )

I've check the production.log but nothing there, i've also checked the /var/log/nginx/error.log and it's got something to do with the table lead

App 2163 stdout: Processing by PagesController#index as HTML
App 2163 stdout: PG::UndefinedTable: ERROR: relation "leads" does not exist
App 2163 stdout: LINE 5: WHERE a.attrelid = '"leads"'::regclass
App 2163 stdout: ^
App 2163 stdout: : SELECT a.attname, format_type(a.atttypid, a.atttypmod),
App 2163 stdout: pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
App 2163 stdout: FROM pg_attribute a LEFT JOIN pg_attrdef d
App 2163 stdout: ON a.attrelid = d.adrelid AND a.attnum = d.adnum
App 2163 stdout: WHERE a.attrelid = '"leads"'::regclass
App 2163 stdout: AND a.attnum > 0 AND NOT a.attisdropped
App 2163 stdout: ORDER BY a.attnum
App 2163 stdout:
App 2163 stdout: PG::UndefinedTable: ERROR: relation "leads" does not exist
App 2163 stdout: LINE 5: WHERE a.attrelid = '"leads"'::regclass
App 2163 stdout: ^
App 2163 stdout: : SELECT a.attname, format_type(a.atttypid, a.atttypmod),
App 2163 stdout: pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
App 2163 stdout: FROM pg_attribute a LEFT JOIN pg_attrdef d
App 2163 stdout: ON a.attrelid = d.adrelid AND a.attnum = d.adnum
App 2163 stdout: WHERE a.attrelid = '"leads"'::regales
App 2163 stdout: AND a.attnum > 0 AND NOT a.attisdropped
App 2163 stdout: ORDER BY a.attnum
App 2163 stdout:
App 2163 stdout: Completed 500 Internal Server Error in 2ms

I thought that when we do the created the database it would do all the tables, how do i register them? do i have to do rake db:migrate?


Gravatar
Paul Ericson on

The Capistrano section makes a huge assumption that will trip up a newbie (like me).

Up to that point, bundler has not been installed, so there is no Gemfile (beyond the template) and the subsequent 'bundle --binsubs' command will fail.

Don't follow the advice in the shell and install bundler using apt-get, it will reset your Ruby version back to 1.9. Instead, use gem like this:

$ gem install bundler
$ export GEM_HOME=$(ruby -e 'print Gem.user_dir')
$ bundle init

Outputs; "Writing new Gemfile to /home/deploy/Gemfile"

Now you can edit Gemfile and run bundle commands.

WARNING: If you are using rbenv, you have to uncomment this line in your Gemfile:
# gem 'capistrano-rbenv', github: "capistrano/rbenv"


Gravatar
Paul Ericson on

Stuck on, "cap install STAGES=production".
Getting, "WARNING:root:could not open file '/etc/apt/sources.list.d/passenger.list'

The program 'cap' is currently not installed. You can install it by typing:
sudo apt-get install capistrano"

This seems to work:

$ bundle exec cap install STAGES=production

Guess rbenv users all have the rbenv-binstubs plugin installed?

Gravatar

You can do "rbenv rehash" to make the cap executable available like a regular command.

Gravatar
Paul Ericson on

"rbenv rehash" doesn't change the behavior.

Gravatar

How about:

```
sudo chmod go=r /etc/apt/sources.list.d/passenger.list

```


Gravatar

Many thx,It is very very helpful :)


Gravatar

I'm trying to install Ruby 2.2 on my staging server through rbenv and it's just hanging:



[email protected]:~$ rbenv install 2.2.0
Downloading ruby-2.2.0.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/7671e394abfb5d262fbcd3b27a71bf78737c7e9347fa21c39e58b0bb9c4840fc
Installing ruby-2.2.0...

Any ideas??

* UPDATE*
It finally failed and I got the following error messages:


BUILD FAILED (Ubuntu 14.04 using ruby-build 20150116-6-g7f1d8df)

Inspect or clean up the working tree at /tmp/ruby-build.20150122190357.31648
Results logged to /tmp/ruby-build.20150122190357.31648.log

Last 10 log lines:
make[3]: Leaving directory /tmp/ruby-build.20150122190357.31648/ruby-2.2.0/ext/fiddle/libffi-3.2.1'<br>linking shared-object fiddle.so<br>/usr/bin/ld: ./libffi-3.2.1/.libs/libffi.a(raw_api.o): relocation R_X86_64_32S against.rodata' can not be used when making a shared object; recompile with -fPIC
./libffi-3.2.1/.libs/libffi.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
make[2]: *** [../../.ext/x86_64-linux/fiddle.so] Error 1
make[2]: Leaving directory /tmp/ruby-build.20150122190357.31648/ruby-2.2.0/ext/fiddle'<br>make[1]: *** [ext/fiddle/all] Error 2<br>make[1]: Leaving directory/tmp/ruby-build.20150122190357.31648/ruby-2.2.0'
make: *** [build-ext] Error 2
Gravatar

I ran into this issue trying to install ruby 2.2 from source. More info here: https://github.com/sstephen...
You can set CFLAG=-fPIC

or install sudo apt-get install libffi-dev


Gravatar

I'm having trouble at the step of installing Ruby with rbenv. rbenv installed fine but when I run rbenv install 2.2.0 it hangs (not really hangs, I can see stuff happening if I use the --verbose flag), and then I get the following:



[email protected]:~$ rbenv install 2.2.0

Downloading ruby-2.2.0.tar.gz...

-> http://dqw8nmjcqpjn7.cloudfront.net/7671e394abfb5d262fbcd3b27a71bf78737c7e9347fa21c39e58b0bb9c4840fc

Installing ruby-2.2.0...

BUILD FAILED (Ubuntu 14.04 using ruby-build 20150116-6-g7f1d8df)

Inspect or clean up the working tree at /tmp/ruby-build.20150122204243.31132

Results logged to /tmp/ruby-build.20150122204243.31132.log

Last 10 log lines:

make[3]: Leaving directory `/tmp/ruby-build.20150122204243.31132/ruby-2.2.0/ext/fiddle/libffi-3.2.1'

linking shared-object fiddle.so

/usr/bin/ld: ./libffi-3.2.1/.libs/libffi.a(raw_api.o): relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC

./libffi-3.2.1/.libs/libffi.a: error adding symbols: Bad value

collect2: error: ld returned 1 exit status

make[2]: *** [../../.ext/x86_64-linux/fiddle.so] Error 1

make[2]: Leaving directory `/tmp/ruby-build.20150122204243.31132/ruby-2.2.0/ext/fiddle'

make[1]: *** [ext/fiddle/all] Error 2

make[1]: Leaving directory `/tmp/ruby-build.20150122204243.31132/ruby-2.2.0'

make: *** [build-ext] Error 2

Any suggestions??


Gravatar

Used only a portion of this tutorial; using rbenv to install ruby version 2.1.3; i was having problems installing mechanize gem. The part where you showed how to setup ruby using rbenv benefited me. Excellent tutorial


Gravatar

So how do you got about debugging errors where Capistrano cannot find gems. Even when gems are in the Gemfile and work just find if you run the rails app with 'rails s'


Gravatar

I went through the tutorial. I had a few issues but managed to get through it.
However now that I have finished it. It looks like the rails application is not actually running.
There are no log files in 'myapp'/log (I am not sure where they logs would be).
When I go to the IP address for my server all I see is the welcome to nginx. I am not sure if there is supposed to be another url I go to instead.

Gravatar

Make sure to restart nginx after changing the configs. You can double check /var/log/nginx/error.log for Nginx errors if you get any issues.

Gravatar

I actually apparently had 2 issues. I small typo and because I am using rvm.

The section "RVM Helper Tool" helped on this page https://www.phusionpassenge...

Now I am digging into "(Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`)"

Gravatar

You'll want to create a secrets.yml just like you do with database.yml in the shared/config folder

Gravatar

Got that working. Thank you.

Something I am confused about.

I am guessing that I need to do "cap production deploy" every time I make a change. But doing so wipes away the secret key I set in shared/config (like database.yml I just did a symlink to current/config)

Gravatar

You run capistrano every time you want to make your changes live on production. The shared directory ( and a symlink pointing to there ) is required so that you don't wipe out that file every deploy.


Gravatar
Sean Perryman on

Hey Chris, great tutorial! I am stuck at the end here, I've been beating my head against the wall all afternoon trying to get it to work. I am getting this error in my production.log:

ActiveRecord::NoDatabaseError (FATAL: role "deploy" does not exist);

Here is my database.yml:

production:
adapter: postgresql
encoding: unicode
pool: 5
host: ""
database: itt_production
username: postgres
password: ""

My pg_hba.conf has everything in trust mode, so this should work. When I switch the pg_hba.conf over to password or md5, and put a password in the database.yml file, I get an error that no password was provided; even though I've provided one. I noticed someone else had an error like this down in the comments, but there was not a resolution posted. Is this something you are familiar with?

Gravatar
Sean Perryman on

HAHA! After switching everything to blank password string and trust, and rebooting the server, the site just loaded up for me. I'd restarted the rails instance, as well as postgres service, but I guess that wasn't enough. This leads to the next question of getting this to work with a password or some other more secure method; luckily this deployment is only for an intranet site.


Gravatar

sudo nginx -t

nginx: [emerg] invalid number of arguments in "passenger_ruby" directive in /etc/nginx/nginx.conf:72

nginx: configuration file /etc/nginx/nginx.conf test failed

Result of "which ruby"
passenger_ruby /home/deploy/.rvm/rubies/ruby-2.2.0/bin/ruby

Gravatar

There's a typo in the tutorial there. You actually want the .wrapper version commented out in the example config there. I'll get that fixed shortly!


Gravatar

hello, i did everything like in this tutorial, but when i try to access my vserver i just get a "Incomplete response received from application" response in my browser.

Gravatar

This is caused by the lack of a secret_key_base export. http://stackoverflow.com/qu...

Gravatar

Been having the same issue, I have had export my secret_key_base as it follows in the SO link you shared but it didn't change a thing.


Gravatar

Users using the RVM method need to execute this command after 'source ~/.rvm/scripts/rvm' -- 'echo "source ~/.rvm/scripts/rvm" >> ~/.bashrc'; otherwise if you exit the terminal session and log back in it will not be loaded. If you are getting a message that 'rails' isn't an installed gem this is likely the cause I would think.

Gravatar
Ben Polinsky on

Thanks, should be more visible

Gravatar

I don't get this and it's getting infuriating. I go to my site folder, cd to current, run "rails c" and I get:

WARNING:root:could not open file '/etc/apt/sources.list.d/passenger.list'

The program 'rails' can be found in the following packages:

* ruby-railties-3.2
* ruby-railties-4.0

Try: sudo apt-get install <selected package="">

So I put source ~/.rvm/scripts/rvm and run rails c again. Same result. I cannot get the effing console to start and I'm about to lose my cool. I'm going on 2 hours wasted on this and it's absolutely infuriating.

Gravatar

Had the same problem. Just use "bundle exec rails c -e production" from current folder.


Gravatar

Can the guide be updated with how to correctly handle the production database.yml and adding the secret_key as an environment variable for for nginx?
It is also a bit unclear about at what point are we cloning the repo to the machine vs what is committed to the repo.

Gravatar

Definitely. That's one of my major goals to add to this tutorial. It's an important piece and I kind of glossed over it. I also need to do a screencast to explain how it works as well.


Gravatar

`cap production deploy` returns `ERROR rbenv: 2.0.0-p451 is not installed or not found in ~/.rbenv/versions/2.0.0-p451`. Any ideas?

Gravatar

found it. The Capfile has to declare version 2.2.0 instead. I also ended up renaming the folder in `versions`


Gravatar
Steven Magelowitz on

Excellent tutorial! Any chance you can explain how to set up multiple rails apps on a single droplet?

Gravatar

The only difference is to deploy your other apps to separate folders, create their dbs, and add another server config to nginx so it knows to serve it up on a different domain/subdomain.


Gravatar
Ivor Horton on

"The first step is to add Capistrano to your Gemfile"

Here we create a new Rails project and edit it's Gemfile or just create a file called Gemfile anywhere in the system?

Gravatar

Always the file named Gemfile in the root of your Rails application. It's the defining list of dependencies for each Rails app. You save it in each app so that all of them can use different versions without fighting each other.


Gravatar
Ivor Horton on

What should changed if my project is private and I don't want to put on github?

Gravatar

Most of my projects are private and I put them on Github (paying for private repos) and you could easily store them privately on Bitbucket. In either case, your Capistrano URL will securely authenticate with Github or Bitbucket using your SSH key to check out the code. It logs in using that so you don't need to use a password to clone the code on a deploy.


Gravatar

Hi! I followed all the tutorial and everything is working fine. The only thing I cannot do and I would like to be able to do is to run rails console on the server. When I run 'RAILS_ENV=production bundle exec rails console' in the /current folder it looks like there isn'n a rails project. I'm missing something in the command? How can i get the console working? Thank you

Gravatar

That's exactly the command and the location you need to in order to do it.

Are you sure you're in the right directory? When you run ls it shows all the files in your rails app?

Gravatar

Yes I'm in the right directory all the files and folders of the project are there, but I still can't get my console working.

Gravatar

What's the output it's giving you?

Gravatar

This is the output, as I run 'rails -h'
----------------------------------
Usage: rails new APP_PATH [options]

Options:

-r, [--ruby=PATH] # Path to the Ruby binary of your choice

# Default: /home/paparot-deploy/.rbenv/versions/2.1.5/bin/ruby

-m, [--template=TEMPLATE] # Path to some application template (can be a filesystem path or URL)

[--skip-gemfile], [--no-skip-gemfile] # Don't create a Gemfile

-B, [--skip-bundle], [--no-skip-bundle] # Don't run bundle install

-G, [--skip-git], [--no-skip-git] # Skip .gitignore file

.....

Gravatar

Hmm, maybe these help? http://stackoverflow.com/qu...

Gravatar

I found out what was the problem thanks to this answer and your help.

http://stackoverflow.com/qu...

Since the ./bin directory is version controlled in Rails 4, we need to prevent Capistrano from linking it on deployments by removing bin from set :linked_dirs. Now in order to prevent bundler from overwriting the version controlled binstubs, we can add the line set :bundle_binstubs, nil which will prevent capistrano-bundler from setting the --binstubsoption when running bundle install.

Should also be changed in the guide maybe?!
Hope this helps and thank you Chris for your help!!

Gravatar

Ah ha! That's happened to me before and I totally forgot about it. I'm going to be recording a video on this setup so I'll make sure to address that when I get that recorded.

Thanks for sharing your solution! :)

Gravatar

Please update the guide with Michel suggestion!, few days ago I followed the guide, nice guide, everything is fine. But today, I needed the console and it is not working. I lost a lot of time searching the web, but the answer was here, at Micahel's answer.

Gravatar

What isn't working for you?


Gravatar
Alejandro Ventura on

is there a video about it?
Thanks!


Gravatar

Thank you for step by step process. I ended up with 403 forbidden error at the end. Could you shed some light on what might have went wrong. I posted it on stackoverflow as well but nothing is working.
http://stackoverflow.com/qu...


Gravatar
Innokenty Longway on

Thanks!


Gravatar
Roosevelt P on

After trying out various articles/tutorials, this tutorial worked great! The setup was flawless!


Gravatar

will I be able to scale the VPS servers horizontally like in heroku?

Gravatar

Not really. You'll need to setup load balancers, etc to do that.


Gravatar
Stephen Dolan on

Great guide. I had a few errors, namely that I needed nodejs installed on the server and that you should get your passenger_ruby path using the passenger-config --ruby-command (at least for RVM).

Gravatar
Rahul Roy on

Hey! How did you solve passenger_ruby path problem? How did you configured passenger_ruby path? I'm stuck with the same problem.

Gravatar
Stephen Dolan on

Run `passenger-config --ruby` to get the correct path.


Gravatar

Hi Chris,

I've tried to follow your steps with true care, but for some reason my Nginx is jinxing me :(
I just can't figure out what to do.. just a starting developer alone in the scary world of deployment. Could you maybe help me for a few minutes, for I am sure you are a true pro.
Capistrano seems to be connected, but presents us with an ssh error; permission denied.
There's also a problem with nginx: sudo service nginx restart presents me with FAIL, I've tried
nginx -t, which presents me with a few errors, though sudo nginx -t says everything is fine.

I'm a little lost..

Thanks and it's no problem if you don't want to,

Abel


Gravatar
Comment_Again on

Great tutorial, Thanks! I had the same issue as @disqus_sRbyuMSsk1:disqus . I also always forget that I need to create the secrets.yml values in production. It would be great to see a section about adding environment variables in the future.

Gravatar

I believe there is a gem that does that for you; however, I find it much simpler just to export the environment variables I need into my shell's rc (.bashrc or .bash_profile if you're using bash) then just refer to them in my database.yml and secrets.yml. Hope this helps.


Gravatar
Piyush Maurya on

I have gone through all the process and cap production deploy become successfull, but at visiting my IP address, i am getting message "We're sorry, but something went wrong(500)"
Please suggest me what to do, i have already spend my 3 days to solve it.
Thanks.

Gravatar

Read the Rails and Nginx logs to check for errors. I didn't cover the part of setting up the database.yml and secrets.yml files.

Gravatar
Piyush Maurya on

I have set up database,yml n secrets.yml files. Now it is giving error "404 not found".

production.log file is empty.

in nginx log:
"/home/deploy/ApplyWin/current/public/index.html" is not found (2: No such file or directory),

please help.

Thanks.


Gravatar
Soheil Eizadi on

The command:

gpg --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7

I had to change to get around firewall problems
gpg --keyserver keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7


Gravatar
Soheil Eizadi on

Had error when I tried to run my app and got error that it could not compile the app, I was missing:
apt-get install libcurl4-openssl-dev

I found this using the passenger tool passenger-install-nginx-module which should be highlighted as a resource.


Gravatar
Soheil Eizadi on

I had to change following
gpg --keyserver hkp://keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7
to
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7

It was getting blocked by firewall.


Gravatar
Amit Patel on

Getting following error on `cap production deploy`
```
INFO [75233a5d] Running /usr/bin/env git ls-remote --heads [email protected]:BoTreeConsultingTeam/magnificent.git as [email protected]

DEBUG [75233a5d] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/magnificent/git-ssh.sh /usr/bin/env git ls-remote --heads [email protected]:BoTreeConsultingTeam/magnificent.git )
DEBUG [75233a5d] ERROR: Repository not found.
DEBUG [75233a5d] fatal: Could not read from remote repository.
DEBUG [75233a5d]
DEBUG [75233a5d] Please make sure you have the correct access rights
DEBUG [75233a5d] and the repository exists.

```

Gravatar

Its one of two things:
1- You have not specified your git repository correctly in capistrano's deploy.rb
2- You didn't add your VPS ssh public key to your github key chain for passwordless deployment https://help.github.com/art...

Gravatar
Amit Patel on

Thanks @moebdol. I verified again am I am sure both suggestions are already taken care.

From the capistrano authentication guide I figured out following steps to fix this.

1. `$ eval "$(ssh-agent -s)"`
2. `$ ssh-add ~/.ssh/id_rsa`

After this if `cap production deploy` works without this error.


Gravatar

Gravatar
Shehbaz Bashir on

I have just automated the process of setting up a production server for Ruby on Rails production application. It includes Nginx, Redis, Memcached, Ruby with RVM, Unicorn or passenger, Mysql or Postgresql.
It uses Chef, knife solo and librarian. No need to be afraid, they are simple commands for you. Hopefully it can some of you to cut on time they spend for server setup.

http://devbox.co/setup-ruby...

Gravatar

Thanks for sharing Shebaz! Part of the reason I don't link to an automated process is because I want people to learn and understand how to setup their machine. It's good to be familiar with all the tools and their configurations. These automated scripts are perfect after you're familiar with the basics! :)

Gravatar
Shehbaz Bashir on

I totally agree with you Chris. I have written it after reading many articles like yours. It not for learning but for people who are already familiar and perform this task regularly. Its just to avoid repetition. THanks


Gravatar
Eluwa Emeka Michael on

Thank you very much gorails.com I succesfully installed rvm on my ubuntu 14.04. This has been a night mare for me, installing rvm correctly.
I couldn't find a good how to guide on this not until i stumbled upon gorails.com. I now bookmark this site and joined the mailing list so i can also share with others not in this group.

Gravatar

Thanks Eluwa! I really appreciate it! :)


Gravatar

I got these errors when running `cap production deploy`:

DEBUG [7923ef33] Finished in 0.010 seconds with exit status 1 (failed).
/home/deploy/deploy_test/shared/config/database.yml does not exist

I put the rails app here:
/home/deploy/code/deploy_test

Gravatar

Try creating /home/deploy/deploy_test/shared/config/database.yml file on your VPS and fill it with you database configurations.

Gravatar

I have the same problem but there is a database.yml file on the server... not sure how to resolve it


Gravatar
fatttttttttt on

very thanks for post!!!!!!


Gravatar

Adding Capistrano I get error:

Retrying dependency api due to error (2/4): Bundler::HTTPError Network error while fetching https://bundler.rubygems.or...

using rvm. It helps changing Gemfile to:

group :development, :test do
gem 'capistrano', '~> 3.4', require: false
gem 'capistrano-rvm', '~> 0.1', require: false
gem 'capistrano-rails', '~> 1.1', require: false
gem 'capistrano-bundler', '~> 1.1', require: false
end

and execution:

bundle install --full-index


Gravatar

This tutorial worked, but need some addition, especially for installing nodejs on first step and add environment variables on /etc/nginx/nginx.conf.

BTW, thank you very much for pointing in the right direction.


Gravatar
Alejandro Ventura on

Please can you help me out, I got this error executing "capistrano production deploy":

Alejandros-MacBook-Pro:SAIIP2 Lexynux$ cap production deploy
DEBUG [83f26320] Running /usr/bin/env [ -d ~/.rvm ] as [email protected]16.79.129
DEBUG [83f26320] Command: [ -d ~/.rvm ]
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:pato2015
DEBUG [83f26320] Finished in 21.796 seconds with exit status 0 (successful).
DEBUG [5d0ab93d] Running ~/.rvm/bin/rvm version as [email protected]
DEBUG [5d0ab93d] Command: ~/.rvm/bin/rvm version
DEBUG [5d0ab93d] rvm 1.26.11 (latest) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
DEBUG [5d0ab93d] Finished in 0.155 seconds with exit status 0 (successful).
rvm 1.26.11 (latest) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
DEBUG [db09357f] Running ~/.rvm/bin/rvm current as [email protected]
DEBUG [db09357f] Command: ~/.rvm/bin/rvm current
DEBUG [db09357f] ruby-2.1.3
DEBUG [db09357f] Finished in 0.160 seconds with exit status 0 (successful).
ruby-2.1.3
DEBUG [8ecded29] Running ~/.rvm/bin/rvm default do ruby --version as [email protected]
DEBUG [8ecded29] Command: ~/.rvm/bin/rvm default do ruby --version
DEBUG [8ecded29] ruby 2.1.3p242 (2014-09-19 revision 47630) [i686-linux]
DEBUG [8ecded29] Finished in 0.246 seconds with exit status 0 (successful).
ruby 2.1.3p242 (2014-09-19 revision 47630) [i686-linux]
INFO [a5a6ecd3] Running /usr/bin/env mkdir -p /tmp/SAIIP2/ as [email protected]
DEBUG [a5a6ecd3] Command: /usr/bin/env mkdir -p /tmp/SAIIP2/
INFO [a5a6ecd3] Finished in 0.004 seconds with exit status 0 (successful).
DEBUG Uploading /tmp/SAIIP2/git-ssh.sh 0.0%
INFO Uploading /tmp/SAIIP2/git-ssh.sh 100.0%
INFO [8b24e7fb] Running /usr/bin/env chmod +x /tmp/SAIIP2/git-ssh.sh as [email protected]
DEBUG [8b24e7fb] Command: /usr/bin/env chmod +x /tmp/SAIIP2/git-ssh.sh
INFO [8b24e7fb] Finished in 0.004 seconds with exit status 0 (successful).
INFO [58bcdad8] Running /usr/bin/env git ls-remote --heads [email protected]:AlexVentura/SAIIP2.git as [email protected]
DEBUG [58bcdad8] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/SAIIP2/git-ssh.sh /usr/bin/env git ls-remote --heads [email protected]:AlexVentura/SAIIP2.git )
DEBUG [58bcdad8] Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts.
DEBUG [58bcdad8] Permission denied (publickey).
DEBUG [58bcdad8] fatal: Could not read from remote repository.
DEBUG [58bcdad8]
DEBUG [58bcdad8] Please make sure you have the correct access rights
DEBUG [58bcdad8] and the repository exists.
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as [email protected]: git exit status: 128
git stdout: Nothing written
git stderr: Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

SSHKit::Command::Failed: git exit status: 128
git stdout: Nothing written
git stderr: Warning: Permanently added 'github.com,192.30.252.130' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Gravatar

Hey Alejandro,

2 things:

1. You accidentally pasted your password into this (I edited it out), but you'll want to go change that now.

2. It sounds like your SSH key is not added to Github. It's connected to the server and now needs to ask Github for your code so that it can put it on there. That step has failed and so you'll want to make sure that your ssh key is added to your user account on Github.

Gravatar
Alejandro Ventura on

Ok I got it. I didn't paste my password, I typed it directly on the terminal when it was asked. But yes, my ssh is not set in Github, so how ca I add my ssh key to my user account in Github?

Gravatar
Bharath Shetty on

I added my sshkey to my user account on Github but still the error prevails


Gravatar

Please help, I got this error executing "capistrano production deploy":

INFO [77acabf2] Running /usr/bin/env bundle install --path /home/wanglihua/myapp/shared/bundle --without development test --deployment --quiet as [email protected]
DEBUG [77acabf2] Command: cd /home/wanglihua/myapp/releases/20150917064532 && /usr/bin/env bundle install --path /home/wanglihua/myapp/shared/bundle --without development test --deployment --quiet
DEBUG [77acabf2] /usr/bin/env: bundle: No such file or directory
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as [email protected]: bundle exit status: 127
bundle stdout: Nothing written
bundle stderr: /usr/bin/env: bundle: No such file or directory

SSHKit::Command::Failed: bundle exit status: 127
bundle stdout: Nothing written
bundle stderr: /usr/bin/env: bundle: No such file or directory

Tasks: TOP => deploy:updated => bundler:install
(See full trace by running task with --trace)
The deploy has failed with an error: #<sshkit:runner:executeerror: exception="" while="" executing="" as="" [email protected]:="" bundle="" exit="" status:="" 127="" bundle="" stdout:="" nothing="" written="" bundle="" stderr:="" usr="" bin="" env:="" bundle:="" no="" such="" file="" or="" directory="">


Gravatar

Thanks!


Gravatar

So I don't need to have the secrets.yml and database.yml files on my rails project? Just the examples?

Thanks awesome tutorial.

Gravatar

Yep! The real reason is so that you don't store your production secrets in git for security.


Gravatar

The Java runtime needs to be noted also. I am stuck here in the deploy stage:

Psych::BadAlias: Cannot load `Rails.application.database_configuration`:
Unknown alias: default

Google results in lots of comments about your default section of your database file. I took those right out and hard coded them vs the alias and I still get this error.

Gravatar

I realized that I had not updated my remote database.yml file

Gravatar

Ah yep! That would do it! I was going to say, sounds like you've got a reference to "default" in your yaml file.

Gravatar

Now its:

rake stdout: Nothing written
rake stderr: rake aborted!
NoMethodError: undefined method `tr' for nil:NilClass
/home/deploy/test_deploy/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/connection_specification.rb:37:in `initialize'

Gravatar

Issue also on Stackexchange:

http://stackoverflow.com/qu...


Gravatar

Awesome tutorial Chris Oliver very detailed and well explained. I managed to get the server up and running. However, I have one hiccup, after I run cap production deploy some of my assets do not show up. Some images appear, others don't and when viewing the webpage on mobile it seems the css doesn't work as well ( showing the desktop site when view from mobile ). Any idea why this may be so?

The following are two logs that appear in red when cap production deploy is run:

[4ccfb05d] I, [2015-10-03T15:44:57.443886 #8238] INFO -- : Writing /home/deploy/test_deploy/releases/20151003194438/public/assets/lead-f711de8905ea0fb3d7e8f652cf53a1a9f36e231231a122bd165693d992487d65.png

[4ccfb05d] cp -p /home/deploy/test_deploy/releases/20151003194438/public/assets/ckeditor/plugins/icons_hidpi-cdeb694f528f1dce0ef080b7473dfe9283d8b625f7311db7baea4eb9e7368207.png /home/deploy/test_deploy/releases/20151003194438/public/assets/ckeditor/plugins/icons_hidpi.png

Gravatar

The one thing I might think of is that you want to make sure you're using ERb asset_url helper appropriately to reference your images. If you're using those through CSS, you can use the "asset-url" helper in your CSS. The urls that are used in production have different URLs than in development so you have to use these helpers.

Gravatar

Forgot to leave my resolution. Thanks for the adice @Chris, got me started in the right direction. I had added some files to the vendors folder so I had to make sure that they were being linked properly. Thanks again.


Gravatar

Hello,

Please help urgent, I'm currently using mysql2 as the adapter. When i try run "rails generate scaffold User email", I get the error -

/home/deploy/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/application/configuration.rb:110:in `database_configuration': Cannot load `Rails.application.database_configuration`: (RuntimeError)
Could not load database configuration. No such file - ["config/database.yml"]

I have already configured my database.yml as

production:
adapter: mysql2
database: deploy_test
username: deploy
password: password

Gravatar

Hi there,
Soiunds like you are trying to continue development using your production server. You will want to continue development on your local machine, checking the files into version control and deploying when needed. Hope this helps!


Gravatar

You mention that Capfile should include `require 'capistrano/rails'`. However the base cap installation has commented out ` # require 'capistrano/rails/assets' # require 'capistrano/rails/migrations' ` What is the delta between these two options?

Gravatar

It actually includes bundler, assets, and migrations in one. https://github.com/capistra...

Gravatar

That may explain why I hit a small bump with the above. Editing the Capfile would then *not* need `require 'capistrano/bundler'`. Next time I deploy, I'll report back...


Gravatar

Thanks for the guide, very useful! I have "thin" gem installed in my gem file. So, the nginx is connect thin or Passenger? Do I need any config for better performance?

Gravatar

In production I typically use Passenger because it has really great performance. You can also use thin but you'll have to set it up differently than I've laid out here. Check out some things like this: http://www.rackspace.com/kn...


Gravatar

HI , i try to deploy by following your tutorial but every time i run i saw this in in server
nginx error file

[ 2015-10-18 20:48:51.3464 3671/7f4021bf3700 age/Cor/Req/CheckoutSession.cpp:252 ]: [Client 1-1] Cannot checkout session because a spawning error occurred. The identifier of the error is 91421a8b. Please see earlier logs for details about the error.

[ 2015-10-18 20:48:51.3469 3671/7f4021bf3700 age/Cor/Req/CheckoutSession.cpp:252 ]: [Client 1-2] Cannot checkout session because a spawning error occurred. The identifier of the error is 91421a8b. Please see earlier logs for details about the error.

[email protected]:~$


Gravatar
Howard Cornett on

This has been a great help, but I am totally stuck now. Every time I manually create the database on the server as you suggest, it is created successfully. However, when I try to connect to it with my deploy user, it tells me the database does not exist. But if I login as the postgres user, it is there. What am I doing wrong, and how can I fix it?

Gravatar
Howard Cornett on

I think I figured out my own solution. The process you listed for created the database didn't work for me. So from the deploy user account on my remote server I entered the command:

psql -d postgres -W

That logged me into psql as the postgres user. I then created the database as you instructed from there. Then I was able to log into the database successfully from my deploy account.


Gravatar
Fritz Rodriguez Jr. on

Hey Chris,

Anyway I could get a link to download this video, would be helpful for easy reference. Thanks so much!

Best!

Gravatar

There's a cool little trick that if you change the youtube URL from "youtube.com" to "ssyoutube.com" it will redirect and give you a link to download the video like this:

http://en.savefrom.net/#url...


Gravatar
Fritz Rodriguez Jr. on

Sweet...thanks Chris!:) FYI creating my second droplet on Digital Ocean. Going to see how difficulty it will be to manage my own servers...two reasons 1. Cost (cheaper and faster with SSD) 2. With you instructions, it seems easier to get something up and running and I get more granular control over the environment...been having issues with other hosting services. Security is the one major area of concern going forward. Also, is there a good service or app for monitoring (like when the app goes down)?

Gravatar

For security, there's a few things you can do like setup a firewall and only open port 80 or 443 for web, setup fail2ban, and disable password authentication over SSH. You'll want to be careful not to lock yourself out of the server, but the recovery console can still let you in if you do. :) More stuff to checkout https://wiki.ubuntu.com/Bas...

Pingdom is probably the most used one, but there are a bunch if you search for monitoring. I use Pingdom's free service I think.


Gravatar

this is an incredibly huge pain point for us ... thanks for video (pray you keep updating it)


Gravatar

Gravatar

This is a fantastic article that I have used to deploy over 5 applications! Thanks so much for iwriting it!!
I find that the postgres createuser command is a bit old and since postgres no longer prompts for options by default.. I find it works better with

createuser --interactive --pwprompt

,


Gravatar
Nick Weavers on

Be great to see a tab for installing ruby using ruby-install and chruby, and an update to the nginx section showing how to set passenger_ruby when using chruby.

ruby-install and chruby makes installing ruby and switching between versions so easy even I could do it!


Gravatar

Hello I am trying to install Fedena School ERP using Nginx and Capistrano. I have managed to get Nginx running but now I am completely confused, I really don't know where to go from here; the entire Capistrano process makes me confused. Also, I already have my app folder locally and not on git.
Please I need help on this please.


Gravatar
Rahul Roy on

Hey! Thanks for detailed guide. However, I'm stuck with a problem while setting up a server using rvm method.


App 25994 stdout:

App 25994 stderr: *** ERROR ***: Cannot execute /home/deploy/.rvm/wrappers/ruby/[email protected]_name/ruby: No such file or directory (2)

: Could not spawn process for application /home/deploy/india_boulevard/current: An error occurred while starting up the preloader. It exited before signalling successful startup back to Phusion Passenger.

I tried changing following line, but no luck so far :(


passenger_ruby /home/deploy/.rvm/wrappers/ruby-2.1.2/ruby;

EDIT: Thanks to Stephen Dolan's comment I solved the problem like this http://stackoverflow.com/a/...


Gravatar
Oscar Ishen on

Hello! Any reason you didn't place capistrano related gems into the development group?


Gravatar
Arif Zaman on

In "Installing Nginx" section, why do you have the same apt-key and apt-get commands repeated twice?


Gravatar
Jaime Bellmyer on

I was getting the following error upon deploy:

rbenv: version `2.1.2' is not installed (set by RBENV_VERSION environment variable)

I found this fix, which worked for me:

set :rbenv_path, '/home/deploy/.rbenv/'

The source said to add it to deploy.rb or it wouldn't work. Sure enough, you can't add it to the Capfile like the other rbenv settings. Not sure why. I'm posting in case it helps others, and for the next time I read this article to setup a server :)

Gravatar
Magzhan Shokparbayev on

It helped. Thanks. It should be placed in config/deploy.rb file:

set :rbenv_path, '/home/deploy/.rbenv'


Gravatar
Jaime Bellmyer on

I also had these issues:

error (upon cap production deploy): Could not find a JavaScript runtime

fix (on the server command line): sudo apt-get install nodejs
----
Postgres only allowed connections from the postgres system user, so:
sudo su postgres
psql -U postgres -h localhost
(in psql): alter user postgres with password 'yourpasswordhere'


Gravatar

I bought Passenger's enterprise license, It tell me "uninstall it by removing the directory in which you extracted Phusion Passenger". Could you tell me which directory should I remove? Thanks!

Gravatar

I think you can just run "sudo apt-get remove passenger" for that.

Gravatar

Your response is very fast! Thank you very much!


Gravatar
CM7Qp6crGEGQDfH6s on

Thanks Chris for this informative tutorial. Two questions here. What should I do if I don't want to use github or bitbucket etc? I just want to develop locally and upload to the server using ssh, ftp etc. Another question is that is it possible to deploy multiple Rails apps in a single VPS in the configuration described in your tutorial? Thanks.


Gravatar
Chirag Nayyar on

Hi i am unable to run my rails application in production mode. I am using AWS EC2 and in development mode it is working fine but in production mode it give me error "Incomplete response received from application" I searched it on google but didn't find any proper solution yet.

Anyone here to help me?

Gravatar

Hey Chirag, I might be able to help. We rescheduled on HackHands a few hours ago. Let's see what you currently have; from there I can suggest what to do. hackhands.com/oreoluwa

Gravatar

Make sure that your secrets.yml is populated with proper value of secret_key_base. I was facing the same issue and once I set the correct value of secret_key_base, error went away.

Gravatar
Chirag Nayyar on

Yes I did the same but the main issue is with faye (messaging service) it is not working properly with ssl


Gravatar

Hello,
Chris for thirst, thx for that great article. It would be
great if you write few words about scalling up application into many
passenger workers. I couldn't find any good and easy to understand
tutorial how to do that on custom vps instance.

Gravatar

Yeah! I will do that. Generally with an individual server you want to set the number of workers equal to the number of CPUs on your VPS. Digital Ocean will show you how many CPUs you have on your machine in their dashboard and you can configure that workers variable and restart nginx to make that work.

I'll make a video on this in the future!


Gravatar
Boris Tkachev on

does anybody received this error when refreshing server?
Incomplete response received from application

Gravatar

Hmm, I've had this a few times before. I think typically it is caused by an error in your application. Check your nginx and rails log files to see if you find any errors listed.


Gravatar
Magzhan Shokparbayev on

GREAT Tutorial ! I set this up with couple of hours.


Gravatar
Nikita Melnikov on

Hello @excid3:disqus ! Thanx for tutorial! I faced with problem that I trying to solve at least 4 hours..
When I create user for Postgres it returns me the next error:

createuser: could not connect to database postgres: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

It seems that postgres was installed properly

[sudo] password for deploy:
Reading package lists... Done
Building dependency tree
Reading state information... Done
libpq-dev is already the newest version.
postgresql is already the newest version.
postgresql-contrib is already the newest version.

Command ps auxwww | grep postgres shows the below

deploy 1869 0.0 0.1 13456 956 pts/1 S+ 09:16 0:00 grep --color=auto postgres

How can I fix this problem? I've already tired googling..

Gravatar
Nikita Melnikov on

It seems that I've resolved issue..
The problem was with locale.

If someone face with that problem you should uninstall postgres and reconfigure your locale.

sudo locale-gen ru_RU.UTF-8

sudo dpkg-reconfigure locales


Gravatar

There's a section of the article that says: "For the rest of this tutorial, make sure you are logged in as the deploy user on the server!"

However, starting at the section named "Capistrano Setup", you actually supposed to be on your local computer (NOT the the remote server).

Gravatar

@excid3:disqus this was confusing for me as well. MIght need to add another alert box to say when you should jump back to your local machine.

Gravatar

Whoops! Always something. I'll make sure this gets fixed shortly. :D


Gravatar

With Rails 4.2.2 (rvm) I also needed to install

sudo apt-get install libgmp-dev

in order to install 'pg' gem


Gravatar
Michael Trojanek on

Even though I have to admit that I haven't watched the full video, this seems to be a great resource for a lot of people to learn how to deploy your Rails application on a production server – so first of all, big thanks for publishing it and helping a lot of Rails developers!

However, judging from the comments, quite some people seem to have their problems in getting everything to work.

I do not know if this will be considered a shameless plug but since my whole business is about running Rails applications in production, I want to point everyone who has made it through this tutorial to https://efficientrailsdevop... – a book about managing your Rails environment with Ansible. It will be of great value if you are looking for a more controlled and reproducible approach to provisioning and deployment.

Gravatar
Rory O'Keeffe on

Wow. Just want to chime in and say holy crap that is some well-written copy. Actually felt my heart starting to beat faster reading it! Once I'm ready to deploy, you'll have another customer for sure.

Gravatar
Michael Trojanek on

Thanks a lot for these kind words, Rory – this really means a lot to me (as quite a lot of work went into that landing page).

Until you are ready to deploy, ping me at any time if you think I can help you with anything!


Gravatar

Great tutorial ! But :
What if I'd like to deploy a second rails app to my vps ? How should I modify the /etc/nginx/sites-enabled/default file to respond to
mysite.com/app1 and mysite.com/app2 ?

Gravatar

Exactly. Add a new server block to the nginx config, setup your new database, deploy your other app, and voila! Should be all you need to do.


Gravatar

How can I setup email smtp production settings after successfully installing this?


Gravatar

Hi, i'm pretty new to rails and discovered your site with this guide. I followed all the steps until the "cap production deploy" that gave me this error : (cap production deploy --trace) - Im using cloud9 online IDE to follow this guide.

/usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/i18n.rb:4: warning: duplicated key at line 6 ignored: :starting
** Invoke production (first_time)
** Execute production
** Invoke load:defaults (first_time)
** Execute load:defaults
** Invoke bundler:map_bins (first_time)
** Execute bundler:map_bins
** Invoke deploy:set_rails_env (first_time)
** Execute deploy:set_rails_env
** Invoke deploy:set_linked_dirs (first_time)
** Execute deploy:set_linked_dirs
** Invoke deploy:set_rails_env
** Invoke rbenv:validate (first_time)
** Execute rbenv:validate
cap aborted!
NoMethodError: undefined method `on' for main:Object
/usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-rbenv-2.0.4/lib/capistrano/tasks/rbenv.rake:3:in `block (2 levels) in <top (required)="">'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:240:in `call'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:240:in `block in execute'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:235:in `each'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:235:in `execute'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:179:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:172:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:165:in `invoke'
/usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/dsl/task_enhancements.rb:12:in `block in after'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:240:in `call'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:240:in `block in execute'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:235:in `each'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:235:in `execute'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:179:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:172:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/task.rb:165:in `invoke'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:150:in `invoke_task'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:106:in `block (2 levels) in top_level'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:106:in `each'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:106:in `block in top_level'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:115:in `run_with_threads'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb100in `top_level'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:78:in `block in run'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/lib/capistrano/application.rb:15:in `run'
/usr/local/rvm/gems/ruby-2.2.1/gems/capistrano-3.1.0/bin/cap:3:in `<top (required)="">'
/usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `load'
/usr/local/rvm/gems/ruby-2.2.1/bin/cap:23:in `<main>'
/usr/local/rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.2.1/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => rbenv:validate

Until the "cap production deploy" all was good. Do you have an idea on what's going on ?
Thanks

Gravatar
Vitor Rocha on

im having same problem!
Did u solve this?

Gravatar

duplicated key at line 6 ignored <<--- check this at capfile


Gravatar

Should there have been a step in this tutorial to install Rails on the server? Say around the area where Bundler is installed? Or did you pick an image that had Rails included?

Gravatar

No actually. Since you've got Bundler, Capistrano will run "bundle install" on deploy and will install Rails for you. That's the nice part about it, since you have Rails inside your Gemfile, Capistrano will automatically install it!


Gravatar

After doing everything right, and destroying almost 10 droplets. I keep getting this error.

We're sorry, but something went wrong.
We've been notified about this issue and we'll take a look at it shortly.

The Phusion Passenger application server encountered an error while starting your web application. Because you are running this web application in staging or production mode, the details of the error have been omitted from this web page for security reasons.

Please read the Passenger log file to find the details of the error.

Alternatively, you can turn on the "friendly error pages" feature (see below), which will make Phusion Passenger show many details about the error right in the browser.

To turn on friendly error pages:

Nginx integration mode

Apache integration mode

Standalone mode


Gravatar

Thank you for this great walkthrough!

I think the two lines for installing nginx are duplicates.


Gravatar

To deploy multiple Rails apps to the same server, you will need to replicate the capistrano settings for the second app, create another database, and change the default file in /etc/nginx/sites-enabled like the following:

server {
listen 80;
listen [::]:80 ipv6only=on;

server_name domain1;
passenger_enabled on;
rails_env production;
root /home/deploy/first_app/current/public;

# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

server {
listen 80 ;
listen [::]:80;

server_name domain2;
passenger_enabled on;
rails_env production;
root /home/deploy/second_app/current/public;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

Hope this helps someone. Many thanks Chris for this tutorial.


Gravatar

when i run " cap install STAGES=production " command in my local machine i am getting below error
can you please help me

/home/home/.rvm/rubies/ruby-2.2.3/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- capistrano/cli (LoadError)
from /home/home/.rvm/rubies/ruby-2.2.3/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /usr/bin/cap:3:in `<main>'

it does't create capfile in my app


Gravatar

when i run " cap install STAGES=production " command in my local machine
i get perfect result

cap install STAGES=production
mkdir -p config/deploy
create config/deploy.rb
create config/deploy/production.rb
mkdir -p lib/capistrano/tasks
create Capfile
Capified

but doesn't create capfile in my application


Gravatar

the passenger ruby lines in nginx.conf are moved to a file called passenger.conf


Gravatar
Mike Simonitsch on

Man, such a dope walkthrough and Vid. Thank you for this.

Gravatar

Thanks Mike. Doing my best to keep it updated! :D


Gravatar

@excid3:disqus I've been deploying on Digital Ocean and works so fine! But Now i had to deploy in other cloud... everything goes ok... but, when i access from browser with ip... i got nothing!

passenger-status: "Phusion Passenger is currently not serving any applications."
nginx status: "nginx is running"

On nginx.conf there is that line: include /etc/nginx/passenger.conf;
And inside de passenger.conf i put:

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /home/deployer/.rbenv/shims/ruby;

in my case, of course... Any ideas?

Gravatar

Hmm, hard to say. Maybe restart nginx to make sure you got your config for the rails app loaded?

Gravatar

Solved my friend... They (Cloud Service) kept the port 80 closed! Figuring out if that is a tipical case or a exception... :-P

Gravatar

Ah ha! I know some of them lock it down by default to improve security. Makes sense that would be the reason!


Gravatar
Shivraj Deepsagar on

Hi Chris. I followed your tutorial point to point and implemented 3 times in 2 days. But I don't seem to fix this nginx 403 forbidden error. I changed permissions. I tried many solutions on stack over flow on the same or similar issue. But nothing seems to work. Could anybody please tell me what might be the issue. I ll be attaching my stackflow thread here to follow up. http://stackoverflow.com/qu.... Please help needed.


Gravatar

Hi, great post ... I have already a ruby on rails webapp on Ubuntu 14.04 in my case I want update my Ubuntu Server version -> Ubuntu 16.04 so for that topic exists somewhere a best practice or somebody want share any advices ...? thank you in advance ...


Gravatar
Hello,

I followed the tutorial to deploy an application that is already running on another digitalocean server, but when running the application in the log I find the following message:

(RuntimeError)
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:66:in `check_rvm_using_wrapper_script'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:46:in `init'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:83:in `init_passenger'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:155:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'


Is there any idea that I can review or that I may be doing wrong?

Thank you!!

Login or create an account to join the conversation.