Hosting Ruby. Overview of options and example of deploying a Ruby on Rails application
In 2012, Heroku launched its famous product to make it easier to deploy applications written in Ruby on Rails. In this article we will look at several hosting options and look at how to deploy Ruby on Rails using a specific application example.
Ruby on Rails hosting. Providers
Heroku – the company that invented the GitOps approach and began its journey as a hosting service for Ruby. Simply push your ruby application to the repository via git push, and Heroku will deploy it automatically. A foreign card will be required. Tariffs start from $5-7 per month.
Amvera Cloud – Russian service. It is similar in functionality to Heroku, but you can pay with a Russian card. Supports deployment and updating via push to a linked Git repository, or through the interface if you are not familiar with Git. There is native support for both C# and other environments – just select the desired configuration in the interface. The cost starts from 170 rubles. per month, and there is a starting balance to start using for free.
Application engines from Azure, G.C.E., AWS. Allows you to easily deploy your ruby application in the data infrastructure of cloud providers.
Let's deploy a Fullstack application in Ruby with a connection to SQLite
Here is a video example and detailed instructions.
To do this we will use the service Amvera. To deploy your main application in Amvera, you need to follow these simple steps:
1. Open the page https://cloud.amvera.ru/projects (you must first register with Amvera)
2. Click the “Create” button and select the service type “Application”
3. Upload all files (you can use git, or you can use the interface). Make sure you have downloaded all the necessary files. For the example project below it is:
– static/styles.css
– app.rb
– Gemfile
– amvera.yml and/or Dockerfile
4. After this, the building and deployment of the application will begin. Wait for the “Successfully Deployed” status to appear.
Let's take a closer look at the process
Let's create a simple web application in the Ruby programming language that will track website visits. We will use the SQLite DBMS to store this information.
The application directory has the following structure:
└─ code/
├── static
│ └── styles.css
├── amvera.yml
├── app.rb
├── Gemfile
└── Dockerfile
Configuration
amvera.yml
You can either write a yaml file yourself or use our yaml generator link or in the “Configuration” section of your personal account.
Example amvera.yml file when using only amvera.yml:
meta:
environment: ruby
toolchain:
name: bundle
version: 3.0
build:
image: ruby:3.0
run:
image: ruby:3.0
mainScript: app.rb
persistenceMount: /data
containerPort: 80
Example amvera.yml file when used with Dockerfile:
meta:
environment: docker
toolchain:
name: docker
version: latest
build:
dockerfile: Dockerfile
skip: false
run:
persistenceMount: /data
containerPort: 80
Important: save modified files (database, etc.) to the permanent storage /data. This will avoid their loss during reassembly. The Data folder in the code and the permanent storage /data are different directories.
Let's consider an alternative way to set the configuration – through a Dockerfile.
Dockerfile
Note: if you are using a Dockerfile, then in most cases you do not need to add the amvera.yml configuration file.
Steps:
1. Create a Dockerfile in the project directory.
2. Specify the base image in the Dockerfile:
FROM ruby:3.0
Instead of 3.0, you can specify any other version that you need.
3. Set the working directory:
WORKDIR /app
4. Copy the file Gemfile to the current working directory:
COPY Gemfile ./
5. Install the dependencies specified in Gemfile:
RUN bundle install
6. Update information about installed dependencies:
RUN bundle update
7. Copy the remaining files inside the container:
COPY. ./
8. Open port 80 for external connections:
EXPOSE 80
9. Add a command to launch the application
CMD [“ruby”, “app.rb”]
The resulting Dockerfile:
FROM ruby:3.0
WORKDIR /app
COPY Gemfile ./
RUN bundle install
RUN bundle update
COPY . ./
EXPOSE 80
CMD ["ruby", "app.rb"]
Dependencies (Gemfile)
To create a Gemfile, you need to run the command:
$ bundle init
Don't forget to edit this file to include information about all the libraries you use. For example, the Gemfile for the example below would be:
source 'https://rubygems.org'
gem 'sqlite3'
gem 'webrick'
Creating a project in Amvera
The last step is to deploy the application itself. In file app.rb contains the main code and connects to the database.
Connecting to a repository via Git
1. Call the terminal in the IDE where the application is open, or open the project folder in the terminal
2. Initialize the local Git repository with the command
git init
3. Add a remote repository for our project (the url of your repository will be different. To avoid syntax errors, copy the link in the second step of creating the project)
git remote add amvera https://git.amvera.ru/имя_пользователя/имя_проекта
4. Add files and make the first commit
git add .
git commit -m "init"
5. Let’s push our code into the project repository
git push amvera master
After this command, your application will deploy.
Using SQLite with a Ruby application
A separate application/container is not required to use SQLite in Amvera. It is enough to specify in the code the path to store the files of this database in permanent storage. You can read more Here.
Bottom line
We deployed Ruby on Rails on the server Amvera and connected the SQLite database. Now you can roll out updates with a simple command – git push
PS
Example application code
require "webrick"
require "sqlite3"
DB_PATH = "../data/visits.db"
DB = SQLite3::Database.new DB_PATH
DB.execute <<-SQL
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY,
time_visited TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
SQL
class IndexHandler < WEBrick::HTTPServlet::AbstractServlet
def do_GET(request, response)
if request.path == "/"
DB.execute("INSERT INTO visits DEFAULT VALUES")
end
response.status = 200
response.content_type = "text/html"
response.body = generate_html
end
private
def generate_html
visits = fetch_visits
html = <<~HTML
<!DOCTYPE html>
<html>
<head>
<title>Visits</title>
<link rel="stylesheet" type="text/css" href="https://habr.com/static/styles.css">
</head>
<body>
<h1>Visits</h1>
<table border="1">
<thead>
<tr>
<th>Index</th>
<th>Time of Visiting</th>
</tr>
</thead>
<tbody>
HTML
visits.each do |visit|
html += "<tr><td>#{visit[0]}</td><td>#{visit[1]}</td></tr>"
end
html += <<~HTML
</tbody>
</table>
</body>
</html>
HTML
html
end
def fetch_visits
DB.execute("SELECT * FROM visits")
end
end
server = WEBrick::HTTPServer.new(Port: 80)
server.mount("/static", WEBrick::HTTPServlet::FileHandler, "static")
server.mount("/", IndexHandler)
server.start
```
> Не забудьте выбрать именно тот порт, который вы указали в amvera.yml и/или Dockerfile
## Проверка работоспособности
1. Переходим в настройки проекта и активируем доменное имя.
2. Теперь можно перейти по нему и откроется наше приложение.
Если что-то не работает, рекомендуем ознакомиться с логами Сборки и Приложения.
Поздравляем, вы успешно создали свое первое приложение в Amvera!
## Код styles.css из примера:
```css
body {
font-family: Arial, sans-serif;
}
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
}
thead {
background-color: #f2f2f2;
}
tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
tbody tr:hover {
background-color: #ddd;
}