Сервис приложения
Сервисы/Ruby (Rails)

Сервис Ruby (Rails)

Среда выполнения Ruby для веб-приложений и API на Rails и воркеров Sidekiq.

Этот сервис запускает ваш код: его образ собирается из Git-репозитория, а каждая сборка развёртывается в окружение.

В StackMaster

Как Ruby (Rails) работает в StackMaster

What Wodby sets up for an application that runs on this service. Check it before adding a server configuration or connection settings to the code.

How the application is started

The container runs Puma with a configuration file the image writes on every start:

puma -C /usr/local/etc/puma.rb
  • Puma loads the Rack application from /usr/src/app/config.ru (PUMA_RACKUP), in the directory /usr/src/app (PUMA_DIRECTORY). The repository must have a config.ru at its root, or the variable must point to it.
  • Puma listens on 0.0.0.0:8080. The port is fixed in the generated configuration and is the port of the service's HTTP endpoint.
  • The image does not include Puma. It must be in the application's Gemfile.
  • A config/puma.rb in the repository is not loaded by this command. Set these variables on the service instead: PUMA_WORKERS, PUMA_THREADS, PUMA_WORKER_TIMEOUT, PUMA_WORKER_BOOT_TIMEOUT, PUMA_PRELOAD_APP, PUMA_PRUNE_BUNDLER, PUMA_QUIET, PUMA_TAG. A change applies with the next deployment of the service.
  • The generated configuration sets Puma's environment from PUMA_ENVIRONMENT, and the image's default for it is development. The service does not set PUMA_ENVIRONMENT or RACK_ENV. An application that depends on them sets them on the service or in its Dockerfile.

Linked services

Links to other services reach the application as environment variables. Nothing in the image reads them: the application reads them itself. Do not hardcode hosts or credentials.

LinkVariables
Database (MariaDB, MySQL or PostgreSQL)DB_HOST, DB_PORT, DB_NAME (also DB_DATABASE), DB_USERNAME, DB_PASSWORD, DB_DRIVER (also DB_CONNECTION)
MailSMTP_HOST, SMTP_PORT
Redis or ValkeyREDIS_HOST, REDIS_PORT, REDIS_PASSWORD
OpenTelemetry CollectorOTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf), OTEL_EXPORTER_OTLP_HEADERS (the Collector's ingest token)

All links are optional. A variable is present only while its link exists and the linked service is enabled. The mail link carries no credentials. The OpenTelemetry variables are the standard SDK settings: an application or agent that uses an OpenTelemetry SDK exports to the Collector without further configuration; set OTEL_SERVICE_NAME to name the application in traces.

Environment

  • WODBY_HOSTS is a JSON array of the environment's hosts, not a comma-separated string. WODBY_PRIMARY_HOST and WODBY_PRIMARY_URL are the canonical ones for links generated outside a request.
  • WODBY_APP_SERVICE_NAME is this service's host name inside the environment. Other services reach the application at that name on port 8080.
  • WODBY_ENV_TYPE tells a development environment from a production-like one.

Build

The code is copied to /usr/src/app, the working directory. The service's own Dockerfile then runs bundle install when a Gemfile exists, and nothing else. A pipeline that passes a Dockerfile from the repository (wodby ci build ruby -f Dockerfile) uses that file instead, and the repository's Dockerfile then owns gem installation.

The service declares no volume of its own: files written inside the container are lost when it is replaced.

In a development workspace

  • The checkout is mounted at /usr/src/app and served as it is on disk.
  • Workspace setup installs gems with workspace-ruby prepare: a frozen bundle install, development and test groups included. Gemfile.lock must be committed; preparation fails without it and never updates it. Run it again after changing dependencies.
  • Gems are installed under .wodby-workspace/ in the checkout, which is kept out of Git status without touching .gitignore.
  • The application is started with bundle exec puma --bind "tcp://$HOST:$PORT", with HOST and PORT defaulting to 0.0.0.0 and 8080. The generated Puma configuration and the PUMA_* variables are not used here. RACK_ENV and RAILS_ENV are development.
  • WORKSPACE_RUBY_COMMAND on the service replaces that start command.
  • Puma does not watch files: a code change needs a restart of the service.
  • A change to variables or linked services still needs a deployment of the environment.

Check the result

  • curl -s -o /dev/null -w '%{http_code}' localhost:8080 from the container shows whether the application answers on the expected port.
  • printenv | grep -E '^(DB|SMTP|REDIS)_' | cut -d= -f1 lists the link variables that are present.

Rails on Wodby

What this service adds to the Ruby service it is based on. Check it before adding database, secret key, host or job queue settings to the application.

Variables the service sets

VariableMeaning
RAILS_ENVdevelopment in environments of type dev, production in every other type (prod, staging, test, feature). An environment of type test is a deployed application, not Rails' test environment.
SECRET_KEY_BASEA secret generated by Wodby for the service. Rails reads it by itself. Do not generate or commit another one.
WORKSPACE_RUBY_COMMANDThe start command of a development workspace, see below.

RAILS_MASTER_KEY is not set. An application with encrypted credentials provides its own key as a secret variable on the service.

Linked services

In addition to the variables of the Ruby service:

LinkVariable
DatabaseDATABASE_URL, the whole connection as one URL, with credentials
Redis or ValkeyREDIS_URL, a redis:// URL with the password, database 0

Rails reads DATABASE_URL by itself, and its values take precedence over the same keys in config/database.yml. Do not put a host, user or password in database.yml. Nothing configures a job queue, cache or mailer for the application: it decides what to do with REDIS_URL, SMTP_HOST and SMTP_PORT, and must start without them when the link is absent. Both URL variables hold a password: never print or commit their values.

Host authorization

The service mounts a config file, named Host authorization, into the container at /usr/src/app/config/initializers/wodby_host_authorization.rb. It is not part of the repository, and it is changed as a config of the service on Wodby, not in the code. When WODBY_HOSTS or WODBY_APP_SERVICE_NAME is present it:

  • adds every host of the environment and the service's internal host name to config.hosts;
  • sets config.host_authorization to exclude requests whose path is /healthz.

Do not add the environment's hosts to config.hosts in the code. Serve the health endpoint at /healthz so that it works without a known host header.

Build

The service's Dockerfile installs vips, runs bundle install, and runs rails assets:precompile with RAILS_ENV=production and a dummy secret key when the application has that task. The runtime variables and the database are not available during the build.

Database preparation

  1. bundle exec rails db:prepare runs on every deployment of the service, in a job of the new version, before its pods are replaced. On the first deployment it runs right after the install. It prepares the linked database: schema and pending migrations. If it fails, the deployment stops before the rollout. The previous version keeps serving until the new one is ready, and keeps serving if the deployment fails, so migrations must keep working with the previous version: add columns and tables first, remove or rename them in a later release.
  2. bundle exec rails db:seed runs after the rollout, during the first deployment only.

The start command and the pipeline do not have to run migrations.

Server

The container starts Puma as described for the Ruby service: port 8080, the image's generated configuration, not the application's config/puma.rb. Rails takes its environment from RAILS_ENV.

Sidekiq worker

The optional rails-sidekiq service runs bundle exec sidekiq instead of Puma. It needs sidekiq in the Gemfile. Sidekiq reads REDIS_URL by itself.

In a development workspace

  • The application is started with bundle exec rails server --binding "$HOST" --port "$PORT", on port 8080, with RAILS_ENV=development whatever the environment type.
  • Migrations and seeds are not run by starting the server.
  • Rails reloads application code between requests in development. The checkout is on network storage, where an evented file watcher is not reliable: config.file_watcher must be ActiveSupport::FileUpdateChecker, which is Rails' default.

Check the result

  • bundle exec rails runner 'puts ActiveRecord::Base.connection.adapter_name' shows whether the database link works.
  • bundle exec rails runner 'puts Rails.application.config.hosts.inspect' shows the allowed hosts.
  • bundle exec rails db:migrate:status shows the applied migrations.

Обзор

Технический профиль Ruby (Rails)

Здесь перечислены версии, которые можно выбрать для Ruby (Rails) в стеке или окружении. Сам сервис публикуется ревизиями, и стек ссылается на конкретную ревизию.

Тип сервиса

Сервис приложения

Версии

4.0, 3.4, 3.3

Стеки

Стеки, в которые входит Ruby (Rails)

Ruby (Rails) входит в этот публичный стек. Можно создать приложение из публичного стека как есть или добавить сервис в собственный стек.

CI/CD

Сборка Ruby (Rails) из Git-репозитория

Начните с публичного шаблона проекта или подключите собственный репозиторий. В StackMaster CI push в ветку, за которой следит окружение, запускает сборку Ruby (Rails), а пайплайн её развёртывает.

Rails boilerplate

Используйте его как есть или клонируйте в свой Git-аккаунт.

wodby/rails-boilerplate

Git-провайдеры

Репозиторий подключается через интеграцию с его Git-провайдером.

CI-провайдеры

StackMaster CI встроен в платформу: пайплайн описывается в файле .wodby/pipeline.yml в репозитории. Для подключённого репозитория те же шаги может выполнять внешний CI-провайдер с помощью StackMaster CLI.

Реестры контейнеров

Собранные образы по умолчанию попадают в StackMaster Registry или во внешний реестр, подключённый как интеграция.

Переменные окружения из интеграций

Интеграция с переменными один раз сохраняет учётные данные стороннего сервиса. Подключите её к Ruby (Rails), и StackMaster передаст их в контейнер как переменные окружения во время работы, а не при сборке образа.

Конфигурация

Конфигурация сервиса Ruby (Rails)

Сервис Ruby (Rails) объявляет следующее. Если значение можно изменить, его задаёт стек, а каждое окружение может его переопределить.

Технические домены

StackMaster выдаёт каждому публичному HTTP-порту технический домен с TLS-сертификатом и продлевает сертификат. Порт, который сервис помечает как частный, домен не получает. Можно добавить собственные домены.

Файлы конфигурации

1 файл конфигурации, который стек или окружение могут переопределить.

Действия

2 действия. Действие — это команда, которую вы запускаете из панели управления или которую StackMaster выполняет после развёртывания или обновления стека.

Связи сервиса

Каждая связь — это подключение Ruby (Rails) к другому сервису. На какой сервис указывает связь, задаёт стек. На карточках перечислены публичные сервисы, которые подходят для каждой связи.

redis

Сервисы, которые подходят для этой связи

sendmail

Сервисы, которые подходят для этой связи