Deploying Rails 8 with Kamal: from the first deploy to zero downtime
TL;DR
Difficulty: Intermediate
A good release is a boring one: no errors while it goes live, broken code stopped before it ships, and a way back in seconds.
- Kamal 2 builds a Docker image, starts it next to the old container and lets Kamal Proxy switch traffic only when /up answers, then drains the old one. Normal releases lose no requests, even at peak.
- Two servers need a load balancer for TLS and a rolling boot (boot limit 1), so migrations run once.
- Secrets live in a password manager, fetched by commands in .kamal/secrets.
- A pre build hook runs the tests, a post deploy hook runs a smoke test and writes the release register.
- Expand and contract migrations keep old and new code compatible, which is what makes kamal rollback safe.
Deploying should be the least exciting part of running a shop. This chapter sets up Kamal 2 for an invented Rails and Solidus shop in Leeds on two servers and a managed PostgreSQL database, from the deploy file and secrets through health checks, staging and hooks to safe migrations, a first deploy and a rollback, with real configuration and timings.
A good release is a boring release
A release is the moment new code reaches the shop your customers use. For a lot of small shops it is also the moment everyone holds their breath. Someone logs into a server late on a Sunday, pulls the new code, restarts something and refreshes the home page until it comes back. If it does not come back, the evening is gone.
This chapter is about making that moment boring. Boring means three things: the shop stays up while the new version goes live, a broken version never reaches customers in the first place, and when one slips through anyway, going back takes seconds rather than an evening. The tool for it is Kamal, the deployment tool that ships with Ruby on Rails 8.
The idea that releases can be both frequent and safe is not wishful thinking. DevOps Research and Assessment (DORA), the research programme behind the best known software delivery metrics, measures throughput (how often you deploy, how long a change takes to reach production) and instability (the share of deployments that need immediate intervention, and how long recovery takes). Its finding, repeated across years of surveys, is that "speed and stability are not tradeoffs": the teams that deploy often are usually the ones whose deployments fail least1. Small, frequent releases are easier to check, easier to understand and easier to undo.
This is the first chapter of a series on running a Rails shop after launch. Later chapters cover the Rails 8 Solid libraries, backups and restores, monitoring, security, upgrades, incidents and the real monthly cost. Here the question is narrower: how do you get code from a developer's laptop onto two servers without anyone noticing?
Example: what releases cost Wrenfield Home today
Throughout this series I use one invented business. Wrenfield Home is an online homeware shop in Leeds (wrenfieldhome.example). Priya owns it. Callum is her developer, part time, and he also looks after operations. The shop runs on Ruby on Rails and Solidus with PostgreSQL. It sells about 1,400 products, takes about 1,980 orders a month at an average order value of £72 including VAT, and serves about 3.6 million requests a month from two application servers and one managed PostgreSQL database at a European cloud provider. All numbers in this example are invented.
Today Callum deploys by hand. He logs into each server over Secure Shell (SSH), pulls the code, precompiles the assets and restarts the Puma web server. While Puma boots, that server answers with errors for about a minute in total across both servers. Because a deploy feels risky, he batches changes and deploys only twice a month, on Sunday evenings. Roughly one release in five goes wrong in some way, and fixing it takes him about 40 minutes.
The expected cost of releases in a month is the number of releases times the minutes of lost trading each one causes, times what a minute of trading is worth:
where is the number of releases a month, the minutes of errors every release causes even when it goes well, the probability that a release goes wrong, the minutes it takes to recover from a bad one, the revenue per minute, and the expected revenue at risk per month. The term is an expected value: the average recovery time per release once you weigh the bad ones by how often they happen (Foundations: expected value).
The shop turns over 1,980 × £72 = £142,560 a month. A 30 day month has 30 × 24 × 60 = 43,200 minutes, so on average = £142,560 / 43,200 = £3.30 a minute.
Today: = 2 × (1 + 0.2 × 40) × £3.30 = 2 × 9 × £3.30 = £59.40 a month.
With the setup in this chapter Callum releases twice a week, so = 8. The proxy makes a normal release invisible, so = 0. Small releases go wrong less often, say = 0.05, and a rollback takes about 3 minutes from decision to recovery, so = 3. Then = 8 × (0 + 0.05 × 3) × £3.30 = 8 × 0.15 × £3.30 = £3.96 a month.
That is a fall from about £59 to about £4, which sounds like a rounding error for a shop of this size. Here is the honest part: at average traffic, a minute of downtime is not what makes deployments expensive. Two other things are.
The first is the peak. On Black Friday evening the shop takes about 95 orders in its busiest hour, so = 95 × £72 / 60 = £114 a minute. One bad release in the old style then costs 1 × £114 + 0.2 × 40 × £114 = £114 + £912 = £1,026 in expected revenue at risk. That is why shops freeze deployments in November. A freeze is sensible with a fragile process, and it also means the shop cannot ship a fix when it needs one most.
The second is everything that does not ship. Two batched releases a month means a small improvement to the product page waits up to two weeks, and every release carries two weeks of changes, so when something breaks nobody knows which change did it. Callum also spends about two hours of each Sunday evening on a release. Boring releases buy back his evenings and let the shop change as fast as Priya wants it to.
What Kamal is, and what it is not
Kamal is an open source command line tool from 37signals, the company behind Basecamp. It takes your application, packs it into a Docker image (a self contained bundle of your code, Ruby and every library it needs), and runs that image as a container on servers you rent, over plain SSH. Rails 8 generates the configuration for it in every new application, together with a Dockerfile, and Rails 8 also put Thruster inside that image: a small proxy in front of Puma that caches and compresses assets and speeds up file downloads2.
The current version as I write is Kamal 2.12.0, released on 18 June 20263. The examples in this chapter use it with Rails 8.1.4.1 and Solidus 4.8.1, both released in November 20264. Kamal changes quickly, so read the configuration documentation for your own version: kamal docs prints it in your terminal.
What Kamal does on every deploy, in the words of its own documentation: it logs in to your container registry, builds the image, pushes it and pulls it onto the servers, makes sure Kamal Proxy is running on ports 80 and 443, starts a new container with the version that matches your current Git commit, tells the proxy to send traffic to it once it answers GET /up with 200 OK, stops the old container, and prunes old images so the disks do not fill up5.
What Kamal is not: it is not Kubernetes, it does not create servers, it does not manage your database for you, and it does not balance traffic between servers. The documentation says plainly that if you run more than one server, "you need to put a load balancer in front of them"6. That is a feature for a small shop. There is no control plane to run and very little to learn beyond one YAML file, and the servers are ordinary Linux machines you can log into.
Example: the moving parts at Wrenfield Home
Callum's target picture for the shop has five parts:
- a load balancer at the cloud provider, which holds the shop's public address, ends the encrypted Transport Layer Security (TLS) connection and spreads requests over the two servers.
- two application servers,
app-1andapp-2, each running Kamal Proxy and the shop's web container, withapp-2also running the background job container. - the managed PostgreSQL database (38 GB), reached over the provider's private network.
- a container registry that stores the shop's images.
- his laptop, where Kamal runs, builds the image and talks to the servers over SSH.
Nothing runs on the servers except Docker and the containers Kamal starts. If a server dies, he can create a new one, add its address to one file and run one command.
The deploy file: config/deploy.yml
Everything Kamal knows about your application lives in config/deploy.yml. Kamal refuses keys it does not recognise, which is a quiet blessing: a typo fails loudly instead of being ignored7.
Example: the deploy file for Wrenfield Home
This is the whole production file for the example shop, with the explanation underneath.
# config/deploy.yml for Kamal 2.12
minimum_version: 2.12.0
service: wrenfield
image: wrenfield-home/shop
servers:
web:
hosts:
- 10.0.1.11 # app-1
- 10.0.1.12 # app-2
job:
hosts:
- 10.0.1.12 # app-2 also runs the jobs
cmd: bin/jobs
stop_timeout: 60
proxy:
app_port: 80 # Thruster listens on port 80 inside the container
forward_headers: true # keep the client address the load balancer sends
response_timeout: 30
healthcheck:
path: /up
registry:
server: ghcr.io
username: wrenfield-home
password:
- KAMAL_REGISTRY_PASSWORD
builder:
arch: amd64
cache:
type: registry
options: mode=max
image: wrenfield-home/shop-build-cache
env:
clear:
DB_HOST: shop-db.private.example
RAILS_LOG_LEVEL: info
WEB_CONCURRENCY: 2
secret:
- RAILS_MASTER_KEY
- WRENFIELD_DATABASE_PASSWORD
ssh:
user: deploy
asset_path: /rails/public/assets
boot:
limit: 1
wait: 5
deploy_timeout: 60
drain_timeout: 30
retain_containers: 5
aliases:
console: app exec --interactive --reuse "bin/rails console"
logs: app logs -f
dbc: app exec --interactive --reuse "bin/rails dbconsole --include-password"
Read it from the top.
servicenames the containers,imagenames the image in the registry.minimum_versionstops anyone with an older Kamal on their laptop from deploying with settings it does not understand7.serverslists two roles. Thewebrole is the primary role and the only one behind the proxy by default. Thejobrole runsbin/jobs, the Solid Queue supervisor, onapp-2only8.proxyconfigures Kamal Proxy for this application. There is nossland nohosthere on purpose, because the load balancer handles TLS. More on that below.registrysays where images go.KAMAL_REGISTRY_PASSWORDis the name of a secret, never the password itself.builderbuilds foramd64servers and keeps a layer cache in the registry, so a routine build only rebuilds what changed.envsplits configuration intoclearvalues, which are fine to read in Git, andsecretnames, whose values come from.kamal/secrets.sshlogs in as an ordinary user calleddeployinstead of root.asset_path,boot, the three timeouts andretain_containerseach solve one specific problem, and each gets its own section below.aliasesturn long commands into short ones:bin/kamal consoleopens a Rails console in the running container.
One more file needs a line. The Rails 8 config/database.yml for PostgreSQL reads the password from WRENFIELD_DATABASE_PASSWORD but has no host in production, so Callum adds host: <%= ENV["DB_HOST"] %> to the production block.
Secrets: what goes in .kamal/secrets, and what never does
A secret is any value that would hurt if it leaked: the Rails master key that decrypts the credentials file, the database password, the registry token, an API key for the payment provider. The rule that keeps them safe is old and simple: configuration that changes between environments belongs in the environment, not in the code9.
Kamal reads secrets from .kamal/secrets using dotenv, and it runs the shell commands you put in that file10. That is the trick: the file can be committed to Git because it holds commands that fetch values, not the values themselves. The Rails template even writes it that way, with a warning in capitals not to put raw credentials in it11. Kamal ships helpers that fetch secrets from password managers, documented for 1Password, LastPass and Bitwarden, with adapters in the source for others such as AWS Secrets Manager and Doppler12.
On the servers, Kamal does not pass secret values on the command line. It uploads them into an environment file that only the owner can read (file mode 0600) and hands that file to the container13.
Example: the secrets file for Wrenfield Home
Callum keeps the production values in a 1Password vault called Production, in one item called Shop.
# .kamal/secrets (committed: it contains commands, not values)
SECRETS=$(kamal secrets fetch --adapter 1password --account wrenfield --from Production/Shop KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY WRENFIELD_DATABASE_PASSWORD)
KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD $SECRETS)
RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY $SECRETS)
WRENFIELD_DATABASE_PASSWORD=$(kamal secrets extract WRENFIELD_DATABASE_PASSWORD $SECRETS)
When he runs bin/kamal deploy, 1Password asks him to unlock once, Kamal fetches all three values in one call, and nothing is written to his disk. If his laptop is stolen, there is no .env file full of passwords on it. Priya can deploy from her own laptop with her own 1Password login, and if Callum ever leaves, revoking his vault access is the whole offboarding for deployment.
Two habits complete it. config/master.key stays in .gitignore, as Rails sets it up. And bin/kamal secrets print exists for debugging, so it is worth knowing that anyone who can run Kamal on that laptop can read every production secret. Treat the deploy laptop as a production machine.
How zero downtime actually works
Zero downtime sounds like magic. It is a queue being handed over politely.
Kamal Proxy sits in front of the application container on each server. When a new version boots, the proxy keeps sending all traffic to the old container and checks the new one: by default GET /up once a second, with a 5 second timeout per request, until the deploy timeout runs out14. As soon as the new container answers 200, the proxy sends every new request to it. Requests that are already in progress on the old container are allowed to finish, which is called draining. Only after draining does the old container stop. If the new container never becomes healthy, the deploy fails and the old one simply keeps serving15.
How much does draining matter? There is a neat law for that. Little's law says that the average number of requests in a system equals the arrival rate times the average time each request spends inside it16. In symbols:
where is the average number of requests in progress at any moment, the arrival rate in requests per second, and the average time one request takes, in seconds. It is a ratio of rates, nothing more (Foundations: ratios and rates).
Example: a release during Black Friday at Wrenfield Home
On an ordinary evening the shop sees its average load. 3.6 million requests a month over 30 days is 3,600,000 / (30 × 86,400 seconds) = 1.39 requests a second. With an average response time of 0.18 seconds, = 1.39 × 0.18 = 0.25 requests in progress at any moment. A restart in the old style kills whatever is in flight and refuses everything that arrives while Puma boots. Booting a Solidus application takes the example shop about 20 seconds, so an old style restart fails about 1.39 × 20 = 28 requests on an ordinary evening.
On Black Friday the shop peaks at 40 requests a second and responses slow to 0.25 seconds under load, so = 40 × 0.25 = 10 requests in progress at any moment, and an old style restart fails about 40 × 20 = 800 requests. Some of those are people pressing "Place order".
With Kamal Proxy the new container boots next to the old one, the old one keeps answering during those 20 seconds, and the 10 requests in progress at the switch are drained, not dropped. The count of failed requests is zero in both cases.
The drain timeout (30 seconds by default) is the longest a request may take before the old container is stopped anyway7. Set it longer than your slowest legitimate request. If an admin export runs for two minutes inside a web request, that export is the thing to fix, by moving it into a background job.
Health checks: what /up proves and what it does not
The whole handover depends on one question: is the new container healthy? Rails 8 answers it with a built in route, get "up" => "rails/health#show". Its documentation is careful about what that means: it returns 200 "if the app has booted with no exceptions, and a 500 status code otherwise", and it "does not reflect the status of all of your application's dependencies, such as the database"17.
That is the right default. The Rails documentation also warns that checking third party services in a health check can get healthy containers restarted because someone else is having a bad day17. And Kamal Proxy only uses the health check during a deploy: once the app is up, the proxy stops checking14. So /up is a gate for releases, not a monitor. Watching the live shop is the job of the monitoring chapter later in this series.
Two settings in config/environments/production.rb keep the health check quiet. config.silence_healthcheck_path = "/up" keeps a request a second out of the logs during deploys and load balancer checks18. And the deploy timeout must be long enough for the slowest healthy boot: the default is 30 seconds7.
Example: a release with a broken initialiser
Callum adds a new payment setting and makes a typo in an initialiser, the file Rails runs once at boot. His tests use a different code path and pass. Here is what happens on deploy, with invented timings:
- 0 to 100 seconds: the image builds and is pulled onto
app-1. - 100 seconds: the new container starts on
app-1. Rails raises an error while booting, the server never starts, and/upnever answers 200. - 100 to 160 seconds: the proxy checks once a second. The deploy timeout of 60 seconds runs out.
- 160 seconds: Kamal stops the new container, prints its last log lines with the error, and fails the deploy. Because
boot.limitis 1,app-2was never touched.
Customers saw nothing. The old version served every request throughout, on both servers. Callum reads the error in his terminal, writes a test that boots the application in production mode, fixes the typo and deploys again.
Why 60 seconds instead of 30? Because the example shop's container needs about 20 seconds to boot and the release may also run a short migration first (see the migrations section). A timeout of three times the normal boot leaves room without making a real failure wait for minutes.
TLS and the load balancer in front of two servers
Every shop needs HTTPS. Kamal Proxy can get and renew certificates from Let's Encrypt by itself, with ssl: true and a host, but its documentation is precise about the condition: it works only when you deploy to one server, the host must point at that server, and port 443 must be open for the challenge14. The Rails template says the same in its comments: do not use it with multiple web servers, terminate TLS at your load balancer instead11.
So a shop on one server lets Kamal Proxy do TLS, and a shop on two servers puts a load balancer in front that holds the certificate. The alternative for several servers is a certificate you bring yourself, loaded from secrets as certificate_pem and private_key_pem14, which suits some setups but means you renew it yourself.
When the load balancer ends TLS, Rails sees plain HTTP from it. Two settings tell Rails the truth. config.assume_ssl = true makes the application believe every request arrived over HTTPS, which is exactly the case behind a TLS terminating load balancer, and config.force_ssl = true redirects any plain HTTP and marks cookies as secure18. The Rails 8 production template already sets both.
Example: the path of one request to Wrenfield Home
A customer in Leeds opens https://wrenfieldhome.example/products/hollin-oak-side-table.
- The domain points at the load balancer. The load balancer completes the TLS handshake with the shop's certificate.
- It sends the request as plain HTTP over the private network to port 80 on
app-1orapp-2, addingX-Forwarded-Forwith the customer's address andX-Forwarded-Proto: https. - Kamal Proxy on that server receives it and, because
forward_headersis true, passes those headers on to the web container14. - Thruster inside the container compresses the response and serves fingerprinted assets, Puma runs the Rails code, and the page for the Hollin oak side table at £189 goes back the same way.
The load balancer runs its own health check against /up on each server every few seconds and stops sending traffic to a server that fails it. One trap is worth knowing: if you set a host in the proxy settings, Kamal Proxy only routes requests for that host name14, so the load balancer's health check must send the shop's host name too, or every server looks dead. With one application per server, leaving host out avoids the problem.
Several servers: roles, rolling boots and where the jobs run
With two servers, the order in which they switch matters.
Kamal boots new containers on all hosts at the same time by default. The boot setting changes that: limit is how many hosts (or what percentage) boot at once, and wait is how many seconds to pause between groups19. Roles also have an order. Kamal boots the primary role first, and containers of other roles, such as job, wait until the first web container is healthy. If no web container becomes healthy, the other roles are never booted13.
The Rails 8 template starts small: it runs Solid Queue inside the Puma process with SOLID_QUEUE_IN_PUMA: true, and its comment says that once you use several servers you "should split out job processing to a dedicated machine"11. Solid Queue's own documentation describes running bin/jobs on a separate server for exactly this reason20. A later chapter in this series goes deep into Solid Queue. For deployment, the point is simpler: jobs get their own role, so web servers and job workers restart independently and do not compete for memory.
Example: one routine release across both servers
With boot.limit: 1 and boot.wait: 5, a release at Wrenfield Home goes like this (invented timings, after the image is built and pulled):
app-1: the new web container starts, runs any pending migrations, answers/upafter 22 seconds, the proxy switches traffic and drains the old container.- Kamal waits 5 seconds.
app-2: the new web container starts and becomes healthy in 19 seconds. Because the first web container is healthy, the new job container starts as well and the old job container receives its stop signal.
For about 25 seconds, app-1 runs the new version while app-2 still runs the old one. The load balancer sends some customers to each. That is fine as long as both versions can run against the same database at the same time, which is the most important rule in this chapter, and the subject of the migrations section.
Accessories: services you run yourself next to the app
Kamal can also run supporting services, called accessories: a database, a Redis server, a search engine. You give it an image, a host, a port and directories to keep data in, and kamal accessory boot starts it21.
Read the first lines of the accessory documentation before you put production data in one: accessories are not updated when you deploy, and they get no zero downtime handover21. That is the honest design. A database is not something to restart casually, and backups, upgrades, failover and monitoring remain your job. For a shop whose database is the business, a managed PostgreSQL service that does point in time recovery for you is usually money well spent. Rails 8 also removed the most common reason for a Redis accessory: Solid Queue, Solid Cache and Solid Cable keep jobs, cache and WebSocket messages in the database you already have2.
Accessories shine where a failure costs nothing: staging, review environments, an internal tool.
Example: the staging database as an accessory
Wrenfield Home's staging server is a single small machine. It does not need the managed database, so Callum runs PostgreSQL 18 as an accessory on the same server:
# part of config/deploy.staging.yml
accessories:
db:
image: postgres:18
host: 10.0.3.21
port: "127.0.0.1:5432:5432" # reachable from the server only, never from the internet
env:
clear:
POSTGRES_USER: wrenfield
POSTGRES_DB: wrenfield_production
secret:
- POSTGRES_PASSWORD:WRENFIELD_DATABASE_PASSWORD
directories:
- data:/var/lib/postgresql
Four details carry the weight. The port is bound to 127.0.0.1, so the database is not exposed to the internet, a point the Kamal documentation makes with a link to Docker's warning on publishing ports21. The secret POSTGRES_PASSWORD:WRENFIELD_DATABASE_PASSWORD is an aliased secret: the container gets POSTGRES_PASSWORD, filled from the same value the app uses10. The database name ends in _production because the image always runs Rails in the production environment, staging included. And the data directory is /var/lib/postgresql, not the older /var/lib/postgresql/data, because the official image moved its data directory from PostgreSQL 18 onwards22. Mount the old path on an 18 image and your data quietly lives inside the container, which is gone at the next reboot.
The app reaches it under the name wrenfield-db: an accessory's service name defaults to the service name plus the accessory name, and the Rails template comment points to exactly that name for a database on the same machine1121.
Staging: the same deploy, a different destination
A staging environment is a copy of the shop where releases go first. With Kamal it is not a second set of scripts. It is a destination: bin/kamal deploy -d staging reads config/deploy.yml and then merges config/deploy.staging.yml over it7. Secrets follow the same pattern: Kamal reads .kamal/secrets-common first, then .kamal/secrets.staging, and with a destination it does not read the plain .kamal/secrets at all10. If you want nobody to deploy without saying where, require_destination: true makes the destination compulsory7.
Staging also needs its own data, and here the law has a word. Under the UK GDPR, personal data must be "adequate, relevant and limited to what is necessary" for the purpose23, and the Information Commission (formerly the Information Commissioner's Office, ICO) guidance on data minimisation explains what that means in practice24. A full copy of the customer table on a less protected staging server is hard to justify when invented or properly anonymised data would test the same code. This is general information, not legal advice.
Example: the staging file for Wrenfield Home
# config/deploy.staging.yml, merged over config/deploy.yml by "bin/kamal deploy -d staging"
servers:
web:
hosts:
- 10.0.3.21
job:
hosts:
- 10.0.3.21
proxy:
ssl: true # one server, so Kamal Proxy can get a Let's Encrypt certificate
host: staging.wrenfieldhome.example
env:
clear:
DB_HOST: wrenfield-db
SOLID_QUEUE_SKIP_RECURRING: true # no nightly feeds or emails from staging
WEB_CONCURRENCY: 1
boot:
limit: 1
wait: 0
The merge is a deep merge: lists such as hosts are replaced, while maps such as env.clear are combined, so staging keeps RAILS_LOG_LEVEL from the base file and overrides DB_HOST. Staging runs on one server, so Kamal Proxy handles its certificate itself. SOLID_QUEUE_SKIP_RECURRING stops the scheduler, which Solid Queue documents for exactly this case: staging should not send the nightly marketing email to real customers20. The staging database is filled by a seed task with 200 invented customers and the real product catalogue, which contains no personal data.
.kamal/secrets-common holds the registry token both environments share, and .kamal/secrets.staging fetches the staging database password and master key from a separate 1Password item. A staging secret can never end up in production by accident, because the files never meet.
Hooks: the test gate before, the smoke test after
Hooks are small scripts that Kamal runs at fixed points of a deploy. They live in .kamal/hooks, are named exactly after the hook with no file extension, and if one exits with a status other than zero, Kamal aborts the command25. Kamal 2.12 knows nine: docker-setup, pre-connect, pre-build, pre-deploy, post-deploy, pre-app-boot, post-app-boot, pre-proxy-reboot and post-proxy-reboot. Each gets environment variables describing the deploy, such as KAMAL_VERSION (the full version being deployed), KAMAL_PERFORMER (who runs it), KAMAL_COMMAND and KAMAL_DESTINATION25.
Two hooks do most of the work for a shop. pre-build runs before anything is built, which makes it the place for a test gate: if the tests fail, nothing ships. post-deploy runs after a deploy, a redeploy or a rollback, and gets KAMAL_RUNTIME, the seconds the deploy took26. It is the place for a smoke test, a quick check that the most important pages of the live shop work.
This is how I work too: every release goes through a test gate and into a release register, a plain record of what went live, when, by whom and with what result. Why that register matters, and what it proves to an auditor or an insurer, is the subject of evidencing compliance with release registers. Why the tests come first in the first place is in test driven development explained.
Rails 8.1 makes the test gate easy. It added a local continuous integration (CI) runner: bin/ci runs the steps declared in config/ci.rb, by default setup, style checks, security audits of gems and code, and the test suite27, and it exits with a non zero status if any step fails28.
Example: the test gate hook for Wrenfield Home
#!/usr/bin/env sh
# .kamal/hooks/pre-build
# Test gate: nothing is built unless the committed code passes bin/ci.
set -e
if [ -n "$(git status --porcelain)" ]; then
echo "Uncommitted changes. Commit or stash them before deploying." >&2
git status --porcelain >&2
exit 1
fi
branch=$(git branch --show-current)
if [ "${KAMAL_DESTINATION:-production}" = "production" ] && [ "$branch" != "main" ]; then
echo "Production deploys come from main only (this is $branch)." >&2
exit 1
fi
echo "Test gate for $KAMAL_SERVICE_VERSION (${KAMAL_DESTINATION:-production})"
bin/ci
Line by line: the first check refuses to deploy with uncommitted changes. Kamal builds from a clean Git clone of your repository by default, so uncommitted work would not even be in the image, and the check stops anyone thinking it is29. The second check allows production deploys only from main. The last line runs the full local CI. If any step fails, bin/ci exits with an error, set -e passes it on, and Kamal stops before building anything.
Example: the smoke test hook for Wrenfield Home
The smoke test needs one small helper in the app. Kamal passes KAMAL_VERSION into every container it starts30, so the app can say which version it is:
# config/routes.rb
get "version" => "versions#show"
# app/controllers/versions_controller.rb
class VersionsController < ActionController::Base
def show
render plain: ENV.fetch("KAMAL_VERSION", "unknown")
end
end
The commit hash it reveals is harmless, but you can restrict the route to the load balancer's network if you prefer. Now the hook, in plain Ruby with only the standard library:
#!/usr/bin/env ruby
# .kamal/hooks/post-deploy
# Smoke test after every deploy and rollback, plus one line in the release register.
require "net/http"
require "uri"
require "csv"
base = ENV["KAMAL_DESTINATION"] == "staging" ? "https://staging.wrenfieldhome.example" : "https://wrenfieldhome.example"
base = ENV.fetch("SMOKE_BASE_URL", base)
expected = ENV.fetch("KAMAL_VERSION")
failures = []
def get(url)
uri = URI(url)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
http.get(uri.request_uri, "User-Agent" => "wrenfield-smoke-test")
end
end
# 1. Every request must reach the new version. New connections let the load balancer pick both servers.
6.times do
served = get("#{base}/version").body.strip
failures << "version #{served} served, expected #{expected}" unless served == expected
end
# 2. The pages that earn money must answer 200 and show what they should.
{ "/up" => nil,
"/" => "Wrenfield Home",
"/t/living-room/side-tables" => "Hollin oak side table",
"/products/hollin-oak-side-table" => "£189.00",
"/cart" => nil }.each do |path, text|
response = get("#{base}#{path}")
if response.code != "200"
failures << "#{path} returned #{response.code}"
elsif text && !response.body.force_encoding("UTF-8").include?(text)
failures << "#{path} does not contain #{text.inspect}"
end
end
# 3. The stylesheet the home page links to must exist (catches asset problems).
css = get("#{base}/").body[%r{/assets/application-[0-9a-f]+\.css}]
failures << "no stylesheet link on the home page" unless css
failures << "#{css} is missing" if css && get("#{base}#{css}").code != "200"
result = failures.empty? ? "passed" : "FAILED: #{failures.uniq.join('; ')}"
register = ENV.fetch("RELEASE_REGISTER", File.expand_path("~/wrenfield/release-register.csv"))
CSV.open(register, "a") do |csv|
csv << [ENV["KAMAL_RECORDED_AT"], ENV["KAMAL_PERFORMER"], ENV["KAMAL_COMMAND"],
ENV.fetch("KAMAL_DESTINATION", "production"), expected, ENV["KAMAL_RUNTIME"], result]
end
puts "Smoke test #{result}"
exit(failures.empty? ? 0 : 1)
What it checks, in order: that six fresh connections all reach the version Kamal just deployed, which proves both servers switched. Then that the health check, home page, a category page, the product page with its price and the basket answer 200 and contain what they should. And finally that the stylesheet the home page links to actually exists. The paths follow the Solidus starter frontend, where products live under /products/:id, categories under /t/ and the basket at /cart31. It never places an order, because a smoke test must not create real orders or touch real payments. Then it writes one line to the release register: when, who, which command, where, which version, how long, and the result.
One fact about post-deploy shapes how you use it. It runs after the deploy has finished and after Kamal has released its deploy lock32. So a failing smoke test does not undo anything: the new version is already live. The hook's job is to tell you, loudly and within seconds, and to leave a record. What to do next is the rollback section. Because the hook also runs after kamal rollback, with KAMAL_VERSION set to the version you rolled back to, the same script checks the rollback too32.
Migrations: the part of a deploy that can hurt
Almost everything in a Kamal deploy is reversible, because old containers stay on the server. The database is the exception. A migration that drops a column cannot be undone by switching containers.
Three facts from the Rails and Kamal source explain where the danger lies.
First, the Rails 8 Docker entrypoint runs ./bin/rails db:prepare whenever the container starts the Rails server33. On an existing database, that runs any pending migrations. So migrations run inside the boot of the new web container, before it can answer /up.
Second, Rails takes a PostgreSQL advisory lock around migrations so that two processes never migrate at once. It uses pg_try_advisory_lock, which does not wait: a second process that cannot get the lock raises ActiveRecord::ConcurrentMigrationError instead34. If two web servers boot in parallel and one runs a slow migration, the other can fail to start. That is why the example shop uses boot.limit: 1: app-1 migrates, then app-2 finds nothing left to do.
Third, during every release, old and new code run against the same database at the same time. The old container keeps serving until the new one is healthy, and with two servers one of them runs the old version for half a minute. So every migration must leave a schema that the old code can still use.
The pattern for that has a name: parallel change, also called expand and contract. You break one incompatible change into three steps: expand (add the new thing next to the old one), migrate (move the code and the data over), and contract (remove the old thing once nothing uses it)35. Each step is its own release, and each release is safe to roll back.
The strong_migrations gem by Andrew Kane checks migrations for exactly these dangers and refuses unsafe ones in development, with an explanation of the safe way36. Two of its rules matter in almost every shop. Removing a column needs ignored_columns first, because Active Record caches the column list and the old code will otherwise fail on a column that has disappeared3637. And in PostgreSQL an ordinary CREATE INDEX locks the table against writes until it finishes, while CREATE INDEX CONCURRENTLY does not38. On spree_orders, writes blocked for a minute means checkouts blocked for a minute.
Long migrations add one more constraint: they run inside the container's boot, so a migration longer than the deploy timeout makes the deploy fail. Schema changes should be fast. Moving or rewriting millions of rows belongs in a background job that works in batches after the release, not in the migration.
Example: removing the legacy price column in three releases
Wrenfield Home's old platform import left a column legacy_price_float on spree_variants (invented, it is not part of Solidus), holding prices as floating point numbers. Nothing should read it any more, and Callum wants it gone.
Release 1, tell the code to forget the column. The model ignores it, and no migration runs:
# app/overrides/wrenfield/variant_ignored_columns.rb
module Wrenfield
module VariantIgnoredColumns
def self.prepended(base)
base.ignored_columns += ["legacy_price_float"]
end
::Spree::Variant.prepend self
end
end
He deploys. Both servers now run code that never mentions the column. Rolling back is safe, because the column is still there.
Release 2, drop the column:
# db/migrate/20270216093000_remove_legacy_price_float_from_spree_variants.rb
class RemoveLegacyPriceFloatFromSpreeVariants < ActiveRecord::Migration[8.1]
def change
safety_assured { remove_column :spree_variants, :legacy_price_float, :float }
end
end
safety_assured is how strong_migrations lets you say that you followed the safe steps. During this deploy, the old container still running on app-2 has the release 1 code, which already ignores the column, so nothing breaks while app-1 migrates. In PostgreSQL, dropping a column only marks it invisible and does not rewrite the table, so it is quick39, well inside the 60 second deploy timeout. It still needs a brief exclusive lock on the table, which is why it belongs in a quiet hour rather than the Black Friday peak. Giving remove_column the type keeps the migration reversible.
Release 3, remove the override. The column is gone, so ignoring it no longer matters.
In the same weeks Callum adds an index to speed up the order export:
# db/migrate/20270216094500_add_index_on_spree_orders_completed_at_and_state.rb
class AddIndexOnSpreeOrdersCompletedAtAndState < ActiveRecord::Migration[8.1]
disable_ddl_transaction!
def change
add_index :spree_orders, [:completed_at, :state], algorithm: :concurrently
end
end
algorithm: :concurrently builds the index without blocking checkouts, and disable_ddl_transaction! is required because PostgreSQL cannot build an index concurrently inside a transaction3638. Three releases instead of one sounds slow, but each takes about seven minutes, and none of them is ever a reason to hold your breath.
Long running jobs: what a deploy does to work in progress
Web requests last a fraction of a second. Background jobs can run for minutes. A deploy has to stop the old job container, and the question is what happens to the job inside it.
The chain of signals is documented. Kamal stops a container with SIGTERM and waits for the stop timeout before Docker kills it outright. Since Kamal 2.12 you can set stop_timeout per role. For roles without the proxy, such as job, the default is the drain timeout740. On SIGTERM, the Solid Queue supervisor tells its workers to finish, waits up to SolidQueue.shutdown_timeout (5 seconds by default), then sends QUIT. Jobs still running at that point "will be returned to the queue" and start again later from the beginning20.
So a job interrupted by a deploy runs twice: once partly, then again in full. That is only safe if the job is idempotent, meaning that running it twice has the same effect as running it once. The background workers article explains idempotency in depth. For deployment, two settings and one habit are enough.
Example: the warehouse import during a deploy
Every 15 minutes, a job at Wrenfield Home reads the warehouse's CSV of shipments and marks orders as shipped. It takes about 40 seconds (invented). One afternoon Callum deploys 20 seconds into a run.
With the defaults, the job container gets SIGTERM, Solid Queue gives the worker 5 seconds, then sends QUIT. The job, halfway through the file, goes back to the queue and starts again on the new container. If the job sends the shipping confirmation email as it marks each order, the first 120 customers in the file get their email twice.
The fix has three parts:
# config/environments/production.rb
config.solid_queue.shutdown_timeout = 50.seconds
- Give jobs time to finish: Solid Queue waits up to 50 seconds, and the
jobrole'sstop_timeout: 60indeploy.ymlkeeps Docker from killing the container before that. - Make the job idempotent: it marks an order as shipped and enqueues its email in one transaction, and only for orders not already marked, so a second run skips them.
- Keep long jobs short: the nightly product feed for all 1,400 products is split into batches of 100, each its own job, so an interruption repeats at most one batch.
With that, a deploy in the middle of the import costs nothing: the job finishes within its 50 seconds, or runs again harmlessly.
Assets and uploads: files that must survive a release
Two kinds of files cause trouble in releases, and Kamal solves one of them.
The first is compiled assets: CSS and JavaScript. Rails gives each file a fingerprint, a hash of its contents in the name, such as application-8f3e1c.css. A customer who loaded a page from the old container a second before the switch will ask for the old file names, and the new container only has the new ones. The result is a page without its styling. Kamal's asset_path setting fixes this: it mounts a volume at that path containing the assets of both the old and the new version, so either set of names works during the handover7. The Rails template sets asset_path: /rails/public/assets for you11.
The second is uploaded files: product images, invoices, anything stored with Active Storage. A new Solidus installation uses Active Storage for product and category images by default41. Active Storage can keep files on the local disk or in a cloud storage service such as Amazon S3 or a compatible one42. On two servers, local disk is wrong twice over: an image uploaded through the admin on app-1 does not exist on app-2, and a file inside a container disappears with that container. A shop with more than one server keeps uploads in object storage, which most European cloud providers sell as an S3 compatible service.
Example: the old stylesheet during a release
At 14:00:10 a customer opens the Hollin oak side table page, served by the old container on app-1. The HTML links to application-8f3e1c.css. At 14:00:11 the proxy switches app-1 to the new container, whose stylesheet is application-b27d90.css because Callum changed a button colour. At 14:00:12 the customer's browser asks for application-8f3e1c.css.
Without asset_path, the new container answers 404 and the customer sees an unstyled page with the "Add to basket" button in the wrong place. With asset_path, the shared volume holds both files, the old stylesheet loads, and the customer never notices. The smoke test's stylesheet check would catch the opposite failure: a new release whose own CSS is missing.
The first deploy, step by step
The first deploy differs from every later one in three ways: the servers need Docker, Kamal Proxy has to be started, and the image has no build cache yet. kamal setup does all of it in one command: it installs Docker where it has the rights to, boots the accessories and runs a normal deploy43. Installing Docker needs root over SSH6, so with a deploy user the servers need Docker installed when they are created, usually by the provider's server image or a short start up script.
Example: moving Wrenfield Home onto Kamal
Callum does not convert the old servers in place. He creates two new servers next to them, with Docker installed by the provider's start up script and a deploy user in the docker group, and moves traffic over only when the new pair has proved itself. The old servers stay untouched as the way back. The steps, with invented timings:
- Preparation, the day before. He writes the files that
bin/kamal initstarts for you: thedeploy.ymlabove,.kamal/secretsand the two hooks. He opens port 80 on the new servers to the load balancer's network only. - Test gate, 260 seconds.
bin/ciruns setup, style checks,bundler-audit, Brakeman and 1,850 tests. - Kamal Proxy, 14 seconds.
kamal setupfinds Docker present, pulls the Kamal Proxy image and starts it on both servers. - Build, 410 seconds. The first build has no cache: Ruby gems compile, the assets precompile.
- Push and pull, 120 seconds. The image goes to the registry and down to both servers.
- Boot
app-1, 48 seconds.db:preparefinds the existing production database with no pending migrations, Solidus boots,/upanswers. - Boot
app-2, 31 seconds. Five seconds ofboot.wait, then the web container and the job container. - Prune, 6 seconds.
- Smoke test, 18 seconds. Run with
SMOKE_BASE_URLset to a temporary host name on a second load balancer that points at the new servers only, because the main one still points at the old pair.
Total: 260 + 14 + 410 + 120 + 48 + 31 + 6 + 18 = 907 seconds, about 15 minutes. Then the cutover: in the provider's console Callum adds the new servers to the main load balancer, watches the error rate for ten minutes, removes the old servers, and leaves them switched off but intact for a week.
One thing makes this safe: during the cutover, old and new servers run the same commit against the same database, so it does not matter which one a customer reaches.
Every later deploy is bin/kamal deploy, and it is shorter because the cache is warm and the proxy is already running.
A routine deploy takes 260 + 3 + 75 + 25 + 22 + 24 + 6 + 18 = 433 seconds, a little over seven minutes. The largest part of it is the test gate, and that is how it should be: the time a release spends proving itself is not waste, it is the reason the remaining three minutes are boring.
Rollbacks: one command, and when not to use it
When a release is bad, Kamal can put the previous version back quickly, because the old containers are still on the servers. kamal app containers -q lists them with their versions, and kamal rollback <version> stops the current container and starts a new one from the old image. In the words of the documentation: "Nothing needs to be downloaded from the registry"44. Kamal keeps the last five containers and images by default, a number you can change with retain_containers7.
A rollback goes through the same proxy handover as a deploy, so it is also free of downtime. It runs the pre-deploy hook before and the post-deploy hook after32, so the release register records it and the smoke test checks it.
The limit is the database. A rollback swaps code, never data. If the bad release ran a migration that the old code cannot live with, rolling back the code makes things worse. That is the second reason for expand and contract: if every migration leaves a schema the previous version can use, a rollback is always safe. When it is not, you fix forward: a small, tested change on top, through the full gate.
If a deploy is interrupted halfway, for example because the laptop lost its connection, Kamal may leave its deploy lock behind. kamal lock status shows who holds it and since when, and kamal lock release clears a leftover lock45. Check that nobody else is deploying before you release it.
kamal app maintenance makes Kamal Proxy answer every request with a 503 page, with an optional message, and kamal app live ends it46. It is the emergency brake, not a release tool.
Example: a rollback at Wrenfield Home, minute by minute
On a Tuesday afternoon Callum deploys version 4f1c2e9, which changes how delivery costs show in the basket. All times are invented.
- 14:02:10 The deploy finishes after 433 seconds. Both servers run
4f1c2e9. - 14:02:28 The post deploy smoke test fails:
/cart returned 500. A partial in a Solidus view override calls a helper that was renamed, and the only test for the basket view used an empty basket, which skips that partial. The hook prints the failure and writes it to the register. - 14:02:50 Callum checks the release in the register and the diff: no migration. A rollback is safe.
- 14:03:05
bin/kamal app containers -qshows the previous version,a81d3b0, still on both servers. - 14:03:12
bin/kamal rollback a81d3b0. No build, no pull.app-1boots the old image and becomes healthy in 9 seconds,app-2follows after the 5 second wait. - 14:03:33 The rollback is complete. The post deploy hook runs the smoke test against
a81d3b0: passed, and recorded as a rollback in the register.
From the failed smoke test to a working shop took 65 seconds, and the rollback itself 21. How many customers noticed? The basket gets about 6% of requests (invented). At 1.39 requests a second over the 65 seconds, about 1.39 × 65 × 0.06 = 5.4, so about five basket views failed. Before the smoke test existed, the first sign would have been an email from a customer the next morning.
Then the calm part. Callum writes a test that renders the basket with an item and a delivery estimate, watches it fail on 4f1c2e9, fixes the helper call, and deploys 7c90b4d at 15:10 through the full gate. The register now tells the whole story in four lines, which is exactly what a postmortem needs.
What goes wrong, and what prevents it
Most deployment trouble in a Rails shop falls into a short list. Here it is in one place, with the cause and the guard.
| What goes wrong | Why it happens | What prevents it |
|---|---|---|
| Errors during every release | The app restarts in place, nothing answers while it boots | Kamal Proxy hands over only after /up is healthy, then drains the old container |
| A broken build reaches customers | Nothing checks the code before it ships | pre-build hook running bin/ci |
| Something broke and nobody noticed | Health check only proves the app booted | post-deploy smoke test on the pages that earn money |
| Unstyled pages for a few seconds | Old HTML asks for old fingerprinted assets | asset_path set to /rails/public/assets |
| Second server fails to boot | Two containers migrate at once, the advisory lock does not wait | boot.limit: 1 |
| Deploy fails on a long migration | Migrations run inside the boot, longer than the deploy timeout | Fast schema changes, data moved by batched jobs |
| Old server errors during the switch | New schema, old code | Expand and contract, ignored_columns, concurrent indexes |
| Jobs run twice or half | Job container stopped mid job | shutdown_timeout, stop_timeout, idempotent jobs in batches |
| Images missing on one server | Uploads on local disk | Active Storage on S3 compatible object storage |
| Secrets in Git or on a laptop | Values written into files | .kamal/secrets with commands and a password manager |
| Rollback makes it worse | Old code cannot use the new schema | Every migration compatible with the previous release |
| Nobody can deploy | A leftover deploy lock | kamal lock status, then kamal lock release |
| Disk full on a server | Old images pile up | Kamal prunes on every deploy, retain_containers |
My view
My view: for a shop with one to a handful of servers, Kamal is the right amount of machinery. It does the one thing that most hand built deploy scripts get wrong, the handover from old to new without dropping a request, and it leaves everything else plain enough to understand on a bad day. You give up automatic scaling and self healing clusters, and a shop with 40 requests a second at its busiest peak does not need either.
What makes releases boring, though, is not the tool. It is three habits around it. A test gate that runs before every build, so broken code never ships. Migrations written in expand and contract style, so the old and the new version can share the database and every release can be rolled back. And a smoke test and a release register after every deploy, so that when something does slip through, you know within seconds, you can go back in one command, and you have a record of what happened.
Get those three right and deploying twice a week becomes the safe option, not the brave one. Skip them and Kamal will deploy your mistakes beautifully, with zero downtime.
Conclusion
A Rails shop on Kamal keeps its whole deployment in one YAML file, a secrets file of commands, and two hooks. Kamal Proxy switches traffic only when the new version answers its health check and drains the old one, so normal releases cost no requests at all, even at peak. Two servers need a load balancer for TLS and a rolling boot so that migrations run once. Accessories suit staging better than production data. Long jobs need time to finish and must be safe to repeat, assets need asset_path, uploads need object storage. And a rollback is a 20 second command, as long as every migration has left the previous version something it can work with.
For the example shop the result is simple to state. Deploys went from two nervous Sunday evenings a month to two calm afternoons a week, at about seven minutes each, most of it spent proving the code works. The next chapters in this series build on this setup: the Rails 8 Solid libraries in production, then backups and restores of the PostgreSQL database.
