skip to content

Deploying rails app to fly

Preface

(Skip this if you want only the commands).

Deploying rails in production mode to fly.io is little tricky with the secret credentials. Quite possible that you can run into the following errors:

ActiveSupport::MessageEncryptor::InvalidMessage
ActiveSupport::EncryptedFile::MissingContentError
ArgumentError: Missing secret_key_base for ‘production’ environment, set this string with bin/rails credentials:edit

Overall, setting up the secret keys and deploying to fly.io can be quite non-intuitive looking at all the tutorials as they don’t talk about it. I have summarised the steps below

Steps

Rails version: 7.0.2
Ruby version: 3.2.1

First we need the secret key for secret_key_base; Generate a secret using

Terminal window
rake secret
#=> 75afb4d7408b0ec350421773d3611be46d62b25de6fea2613ae791ad9a81ce2fb7cba99da07f3231488dedfd56dc3d704d198f452e5d7073ff0e7431c5705456

Keep this secret safe and private.

From Rails 6 multi environment credentials are supported, hence we can now go ahead and create one for production.

Generate a credential file for production

Terminal window
bin/rails credentials:edit --environment production

Inside that file add the keys

secret_key_base: 75afb4d7408b0ec350421773d3611be46d62b25de6fea2613ae791ad9a81ce2fb7cba99da07f3231488dedfd56dc3d704d198f452e5d7073ff0e7431c5705456

In rails config/environments/production.rb do

config.require_master_key = true

This will make sure that the value is present.

Then do

Terminal window
flyctl launch

To make sure the key is set at fly.io do

fly secrets set RAILS_MASTER_KEY=$(cat config/credentials/production.key)

Now we can deploy the app with

fly deploy --remote-only --build-arg RAILS_MASTER_KEY=$(cat config/credentials/production.key)

If you note, I am passing it as build-arg since a command in my dockerfile requires the value. The secret added at fly is available during run time only


Updated on