Previously, we added in the SSH Keys to secure a connection between your computer and the Droplet, installed rbenv, Ruby and Rails.
Installing PostgreSQL
Rails, by default, uses a sqlite3 which is a single file in your application that is being read and written and which stores your tables, indexes, triggers, and views. This works great for a small number of users accessing your site. However, sqlite3 uses the same disk as your application, reducing the performance of your application. This article should help to answer why sqlite3 will not work on a production server.
PostgreSQL, on the other hand, is a database server that securely stores data. It can also handle a variety of workloads from small applications to large web applications with many concurrent users. This makes it ideal as a production database.
When you are going to use apt-get, it is important to look for the latest versions of any packages since they are being updated a daily basis
$ sudo apt-get update
Once apt-get is updated. Install PostgreSQL and its development libraries:
$ sudo apt-get install postgresql postgresql-contrib libpq-dev
Create Database User
You will need to create a user which will be able to access the database for your application. I will be using pguser as the user name. You should change the name to whichever you like
$ sudo -u postgres createuser -s pguser
It is always good to have a password for any user you create and a database user is no different.
Go into the PostgreSQL console by typing in this command:
$ sudo -u postgres psql
When you see postgres=#, it means you are now in the PostgreSQL console. Next enter the command, which will change the password for pguser
postgres=# \password pguser
You will be prompted to enter in a password, do so and press enter. The pguser now has a password. To quit PostgreSQL console, type this command:
postgres=# \q
Setting Up Deployment with Git
According to git-scm.com, which manages Git, it is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.
In our case we will be using it to get files from your development repo into the production server. The main result is you do not want to copy files from development environment to your production since you may not know which files are ready for production and which ones are still being developed. By using Git to push to production a snapshot of the current environment, you will know if the same files can be used on production and thus know if it will work.
If you are planning on having an application with no development, then you can skip this part and go to Create New Rails Application section.
Step One — Creating a Bare Git
First you will need to be in your home directory and create two directories for the Git repo and another where the actual files of the application will go. I will be using appname, as the name of the application. Please change the name of the application to the name you would like to use.
$ cd ~
$ mkdir repo/
$ mkdir appname
Next we will go into the repo directory and create a bare initial version of Git which will have only the folders and files needed to run Git but no other configuration since we will be creating them ourselves.
$ cd repo
$ mkdir appname.git
$ cd appname.git
$ git init — bare
Step Two — Setting Up Git Hooks
Git hooks are actions that Git can take when Git does something. According to the Git documentation there are three possible server hooks: ‘pre-receive’, ‘post-receive’ and ‘update’.
pre-receive: Executes as soon as the server receives a ‘push’
post-receive: Executes when a ‘push’ is completely finished
update: Similar to pre-receive, however, executes once for each branch
We will be using post-receive while in appname.git to change directories to hook. Using your favourite editor, create a file called post-receive
$ cd hooks
$ nano post-receive
Then add in this line so that when you push your code from your local machine onto this server it will automatically take the files from the repo and add them to the application folder
git — work-tree=/home/[your user name]/appname — git-dir=/home/[your user name]/appname.git checkout -f
Save and exit the file
Finally, change the permission of the post-receive file to allow it to be executed
$ chmod +x post-receive
Step Three — Setting Up Local Git
Exit out of your ssh by using
$ exit
When you are on your local computer, go to your application and, if you have not done so, enter this command to set up your Git
$ git init
Now add in a Git remote to your Droplet which will create a remote URL called live by typing in this command
$ git remote add live ssh://[your Droplet ip address]/home/[your user name]/appname.git
If you do not have any commits on this Git, type in this command in order to test that the connection to your Droplet works
$ git add .
$ git commit -m ‘Init commit’
This command will add everything that has been changed into Git staging and then commit it to the branch, in this case, master branch. To find out more about Git, click on this link.
Now any time you would like to update the files on your Droplet, enter in this Git command:
$ git push live master
This will send your commits to the Droplet from your master branch and load the files into your application folder. Go to your Droplet and see if the files have been uploaded.
$ ssh [name of user name]@[your Droplet ip address]
$ cd ~/[your user name]/appname/
$ ls
If you see the files, you are ready to go to the next part. Go to the Installing figaro Gem section of Create New Rails Application which will show how to store both your database password and secret keys.
Create New Rails Application
I will be creating a Rails application to show how to configure it from start to finish. I will be using appname as the name of the application. Change it to the application you would like to use.
Go to the folder where you would like the application to be located. I will be using my current user's home directory since it is easy to access and this user should be the only one to access the web site using ssh.
Step One — Create Application Folder & Files
$ cd ~
We will also be using -d postgresql which will automatically use PostgreSQL instead of Rails’ default database SQLite3.
$ rails new appname -d postgresql
Go into your new application directory
$ cd appname
Step Two — Configuration Database
Using your favourite editor go into the configuration for the database
$ nano config/database.yml
Find ‘production:’ which will be near the bottom of database.yml and change the name of the username to the name of the database user.
production:
<<: *default
database: Appname_production
username: pguser
password: <%= ENV[‘APPNAME_DATABASE_PASSWORD’] %>
Exit and save config/database.yml
Step Three — Generated Secret Keys
Secret keys are used by your application to verify that user sessions and cookies are unique from any other application, so that one application does not log into a user from another application. If anyone finds out your Secret Keys they could login as a user and break your application.
We will need to run rake secret to generate a random key that will be unique for this application. Also, you will need to run rake in production mode. To do so, add in this command RAILS_ENV=production in front of any other Rails command. By adding it to any command, you switch from development mode into production mode.
$ RAILS_ENV=production rake secret
Copy the key from the console and add it to a notepad in order to retrieve later when we add it to figaro gem.
Step Four — Install figaro gem
Figaro gem hides sensitive information from being accidentally committed to your version control where bad hackers could use that information to access your application. By doing this, you are protecting the data from being used outside the server.
Open Gemfile using your favourite editor
$ nano Gemfile
Then add in the gem figaro
$ gem ‘figaro’
Exit and save Gemfile then run bundle to install figaro
$ bundle install
Open config/application.yml using your favourite editor, here we will be adding our database password and secret key which will be in the environment variables on the server.
production:
SECRET_KEY_BASE: [Enter Secret Key]
APPNAME_DATABASE_PASSWORD: [Enter Database Password]
Exit and save config/application.yml
Step Five — Create Production Database
We can now create our database for use in production.
$ RAILS_ENV=production rake db:create
If you see any errors which say you cannot connect to the database, double check either config/application.yml or config/database.yml to ensure there are no spelling mistakes for the environment variables. If you are migrating from your development environment you should run those commands
$ RAILS_ENV=production rake db:migrate
Also if you have database seeds you could run them as well.
$ RAILS_ENV=production rake db:seed
Step Six — Testing Our Application
It is now time to test that the application is running correctly. However, first go to your Digital Ocean console and find out the IP address for your server, then type this command:
$ rails server — binding=[your Droplet ip address]
This will run the default application server for Rails, WEBrick, an application server to run Rails and since we bind it to an IP Address, you can go to your server public id using port 3000 to see your site online. Enter this address in your browser
http://[your Droplet ip address]:3000
If you see the Rails Welcome page or the homepage of your site then we are good to go. Go back to your console and press CRTL+C to stop WEBrick since now we are going to use Passenger instead.
Installing Passenger & Nginx
Before we start installing both Passenger and Nginx, a little background on what both of them do. When you are interacting with Web Applications such as Rails or Meteor, there are actually two servers that are being used to run your application, a web server and an application server. A web server gets the request from your user’s computer and sends it to the application server. Then sends back a response to your user’s computer. Application server actually runs your application and returns the response back to the user in the form of a view, JSON or any other data type the user has requested.
While there is a debate on which ones are the best, we will be using Passenger and Nginx, since they are both fast and reliable. You may wish to do your own research and see which one works for you.
Step One — Adding APT Source File
To start up we will be using Advanced Packaging Tool (APT) but first we will need to add a new source where the Passenger package is located on the internet, to apt-get. To install Passenger run this command
$ sudo apt-key adv — keyserver keyserver.ubuntu.com — recv-keys 561F9B9CAC40B2F7
Create a new APT source file using your favourite editor
$ sudo nano /etc/apt/sources.list.d/passenger.list
Add in this line and save and exit the file
deb [https://oss-binaries.phusionpassenger.com/apt/passenger](https://oss-binaries.phusionpassenger.com/apt/passenger) trusty main
Finally we will be updating the owner and permission of the new APT source file to be the root user and have that user able to read and write to the file.
$ sudo chown root: /etc/apt/sources.list.d/passenger.list
$ sudo chmod 600 /etc/apt/sources.list.d/passenger.list
Step Two — Install Passenger Using APT
First as always update apt-get
$ sudo apt-get update
Install both Nginx and Passenger from apt-get
$ sudo apt-get install nginx-extras passenger
Setting Up Nginx the web server
Open up the configuration for Nginx, using your favourite editor
$ sudo nano /etc/nginx/nginx.conf
Find the following lines located at the bottom of the file. This is how Nginx knows to use Passenger as the application server and run Ruby from it.
# passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
# passenger_ruby /usr/bin/ruby;
Remove the # in order to uncomment those lines and allow Passenger to use them
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/bin/ruby;
Save the file and exit
Finally, Deployment
First, we need to disable the default Nginx configuration in your favourite editor by using this command
sudo nano /etc/nginx/sites-available/default
Find these lines they are located at the top of the file
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
Add # in front of them to comment them out
# listen 80 default_server;
# listen [::]:80 default_server ipv6only=on;
Save and exit the file
Next, we will be creating a configuration for your application. Replace appname with the name of your application, again you will need to use your favourite editor
$ sudo nano /etc/nginx/sites-available/appname
Add the file server block which will tell Nginx how to run the web server for this application
server {
listen 80 default_server;
server_name [www.mydomain.com;](http://www.mydomain.com;)
passenger_enabled on;
passenger_app_env production;
root /home/[your user name]/appname/public;
}
The server block has different parts as follows:
listen 80: tells Nginx to listen on port 80, the port where the Internet traffic comes from
server_name: the name of the domain the application is on. This is optional and you can use your Droplet IP address to access this application from the browser
passenger_enabled on: enables Nginx to use Passenger application server for this application
passenger_app_env: Set the type of application to use development or production, which is default. If the application is not running correctly you can switch this to development mode and see a more detailed error message. Please note that for security reasons you should never have this set to development and forget about it, since bad hackers could use the detailed error messages as a way to access your application.
root: Location of where to load the files, this points to the public folder of an application to only load the HTML files since HTML files can access CSS and JavaScript outside of the public folder. Thus a user would not be able to access either the CSS or JavaScript and see how they work. This is a secure way of providing your application from being hacked.
Save and exit the file
Finally, we will be copying your application Nginx configuration from the available folder to the enabled folder so that Nginx can run it when the user types in the domain name or IP address.
$ sudo ln -s /etc/nginx/sites-available/appname /etc/nginx/sites-enabled/appname
Restart Nginx, since Nginx only enables sites when it first loads up
$ sudo nginx -s reload
To test your application in your browser, enter in the IP address for this Droplet, or if you have a domain name, use that instead.
http://[your Droplet ip address]
If you see the Rails Welcome page or the homepage of your site all is good and your application is officially deployed.
General Maintenance
Just because you deploy your application does not mean you no longer have to worry about your server. You will need to do regular updates to all of the packages you have installed, as well as any gems that you have installed.
For the packages, run this command on a regular basis
$ sudo apt-get update && sudo apt-get upgrade
Which will update your APT and upgrade any packages that need to be updated
Then run this command which is the same as sudo nginx -s reload to reset your server
$ sudo service nginx restart
For any gems in your Rails application you should run bundle install which will go to rubygems.org and find the latest version of the gems, if the Gemfile allows it to update.
Conclusion
Your application should now be live. Take a moment to realize how far you have come. Of course this is only setting up a basic server, there is always room to grow. I hope your installation went smoothly over the course of this tutorial and that you have found it to be helpful. Please leave comments below.
Reference
The articles that were used in the creation of this post:
How To Use PostgreSQL with Your Ruby on Rails Application on Ubuntu 14.04
How To Set Up Automatic Deployment with Git with a VPS
How To Deploy a Rails App with Passenger and Nginx on Ubuntu 14.04
Top comments (0)