Cloud and deployment · Intermediate · 24 min
Deploy a containerised app and a volume to Fly.io
By Padding · Updated 18 Nov 2026
flyctl 0.5.19 · Node.js 26 (node:26-slim) · Fly.io Machines
You will deploy a Node.js container to Fly.io in Johannesburg with a health check, a secret, auto-stopping machines and a SQLite database on a volume, scale it, ship a new version and destroy it.
On this page
Fly.io runs your Docker image on small virtual machines, called Machines, in the region you pick. You hand it a Dockerfile, it builds the image, starts it behind its own proxy with HTTPS, and gives you a .fly.dev address. Two things make it different from a plain container host. Machines can stop when nobody is using them and start again on the next request. And a volume, the disk you can attach for data, belongs to one Machine on one physical server.
In this tutorial you take the hello-node Express app from /tutorials/write-a-dockerfile-for-a-node-app, give it a SQLite visit counter, and deploy it to the Johannesburg region. You edit fly.toml by hand so you know what each line does, store a secret without it touching your shell history, put the database on a volume, and see for yourself what happens to that data when you scale to two Machines. You finish by shipping a new version and destroying the app, so nothing keeps billing.
Fly.io bills while you follow this. The amounts for one small Machine and a 1 GB volume for an hour are small, but they are not zero, and the last step removes everything.
Step 1 · Install flyctl and sign in
flyctl is the command-line tool for Fly.io; it installs as both flyctl and the shorter fly. On macOS with Homebrew:
brew install flyctlOn Linux, or macOS without Homebrew, use the official install script. It puts the program in ~/.fly/bin and prints the line to add to your shell's startup file, so add that line and open a new terminal:
curl -L https://fly.io/install.sh | shA binary installed by the script gets no updates from your package manager. Run fly version upgrade from time to time, or brew upgrade flyctl if you used Homebrew. Then sign in. The command opens a browser window where you log in to your Fly.io account:
fly version
fly auth loginCheck it worked
fly version prints fly v0.5.19 or a newer version, and fly auth whoami prints the email address of your Fly.io account.
Step 2 · Give the app a database that lives in /data
Go to the hello-node folder from the Dockerfile tutorial. Replace server.js with a version that counts visits in a SQLite file. It uses node:sqlite, the SQLite module built into Node.js 26, so there is no package to install. The folder for the database comes from the DATA_DIR environment variable, which you will point at the volume:
cd hello-node
cat > server.js <<'JS'
const express = require('express')
const path = require('node:path')
const { timingSafeEqual } = require('node:crypto')
const { Database } = require('node:sqlite')
const dataDir = process.env.DATA_DIR || '/data'
const db = new Database(path.join(dataDir, 'visits.db'))
db.exec('CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, at TEXT NOT NULL)')
const addVisit = db.prepare('INSERT INTO visits (at) VALUES (?)')
const countVisits = db.prepare('SELECT COUNT(*) AS n FROM visits')
const app = express()
const port = process.env.PORT || 3000
// Fly.io calls this to decide whether the Machine is healthy.
app.get('/healthz', (req, res) => res.send('ok'))
app.get('/', (req, res) => {
addVisit.run(new Date().toISOString())
res.json({
message: 'Hello from Fly.io',
visits: countVisits.get().n,
machine: process.env.FLY_MACHINE_ID || 'local',
region: process.env.FLY_REGION || 'local',
})
})
// Only callers who send the ADMIN_TOKEN secret in a header get the count.
function tokenMatches(given) {
const expected = Buffer.from(process.env.ADMIN_TOKEN || '')
const actual = Buffer.from(given || '')
return expected.length > 0 && actual.length === expected.length && timingSafeEqual(actual, expected)
}
app.get('/admin/visits', (req, res) => {
if (!tokenMatches(req.get('x-admin-token'))) return res.status(401).json({ error: 'unauthorised' })
res.json({ visits: countVisits.get().n })
})
const server = app.listen(port, () => {
console.log(`Listening on port ${port}, data in ${dataDir}`)
})
// Close the database cleanly when the Machine is stopped.
process.on('SIGTERM', () => {
server.close(() => {
db.close()
process.exit(0)
})
})
JSFLY_MACHINE_ID and FLY_REGION are set by Fly.io on every Machine. Printing them lets you see which Machine answered, which matters later.
Now the Dockerfile. The app runs as the node user, so /data must exist in the image and belong to that user. Rewrite the Dockerfile with that one change added before the USER line:
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY server.js ./
ENV NODE_ENV=production
ENV DATA_DIR=/data
RUN mkdir -p /data && chown node:node /data
EXPOSE 3000
USER node
CMD ["node", "server.js"]
DOCKERBuild it and run it once on your computer, with a Docker named volume standing in for the Fly.io volume:
docker build -t hello-node:fly .
docker run -d --name hello-fly -p 127.0.0.1:3000:3000 -v hello-fly-data:/data hello-node:flyCheck it worked
Run curl -s http://localhost:3000/ twice. The second reply shows "visits":2, with "machine":"local". Node.js may also print an ExperimentalWarning about SQLite in docker logs hello-fly; the module is a release candidate in Node.js 26 and works for this. Remove the test container and its volume with docker rm -f hello-fly and docker volume rm hello-fly-data.
Step 3 · Create the app with fly launch
Every app needs a name that is unique across all of Fly.io, because it becomes <name>.fly.dev. Pick one and keep it in a shell variable. Replace yourname with something of your own:
APP=hello-node-yournameChoose the region before you launch. The region list is short, and it does change, so look at the current one:
fly platform regionsAt the time of writing, jnb (Johannesburg) is the only region in Africa. It is the obvious choice for users in southern and eastern Africa. For users in West or North Africa, traffic often travels through Europe, so lhr, ams or cdg can answer faster than jnb. Measure from your users' networks rather than going by the map; /tutorials/choose-a-cloud-region-in-africa shows how. This tutorial uses jnb.
Create the app without deploying it. fly launch reads the folder, finds your Dockerfile and writes a fly.toml configuration file:
fly launch --no-deploy --name "$APP" --region jnbIt shows the settings it plans to use (organisation, region, Machine size) and asks something like whether you want to tweak them. Answer no; you will edit fly.toml yourself next. If it offers to generate a new Dockerfile, decline and keep yours.
Check it worked
fly apps list shows your app with a status of something like pending, because nothing is deployed yet. A fly.toml file now sits next to your Dockerfile, and its first line is app = 'hello-node-yourname' with your name.
Step 4 · Write fly.toml yourself
The generated file works, but it was written for a stateless app on port 8080. Replace it with this one, so every line is something you chose. Keep the app name you picked; the $APP variable fills it in:
cat > fly.toml <<TOML
app = "$APP"
primary_region = "jnb"
kill_signal = "SIGTERM"
kill_timeout = 10
[env]
DATA_DIR = "/data"
[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = "stop"
auto_start_machines = true
min_machines_running = 0
[[http_service.checks]]
grace_period = "10s"
interval = "30s"
method = "GET"
timeout = "5s"
path = "/healthz"
[mounts]
source = "hello_data"
destination = "/data"
[[vm]]
memory = "256mb"
TOMLWhat each part does:
kill_signal = "SIGTERM": Fly.io sendsSIGINTby default when it stops a Machine. Your app listens forSIGTERM, so ask for that signal.kill_timeoutgives the app 10 seconds to finish before it is killed.internal_port = 3000: the port your app listens on inside the Machine. If this does not match, the proxy cannot reach the app and every request fails. Fly.io's own default is 8080.force_https = true: plain HTTP requests are redirected to HTTPS.auto_stop_machines = "stop"andauto_start_machines = true: when the proxy sees spare capacity for several minutes, it stops a Machine, and it starts one again when a request arrives. A stopped Machine costs much less than a running one. The price is a cold start, about two seconds or more for the first request.min_machines_running = 0: with no traffic, everything may stop. Set it to1to keep one Machine always running in the primary region, so nobody waits for a cold start. It only applies in the primary region, and only when auto stop is on.[[http_service.checks]]: every 30 seconds the proxy requests/healthz, after a 10 second grace period at start. Anything other than a 200 response, including a redirect, counts as a failure, which is why the check uses its own simple route.[mounts]: attach a volume namedhello_dataat/data. If none exists, the first deploy creates one for you. This tutorial creates it first so you choose its size and region and see the warning flyctl gives.memory = "256mb": enough for this app. Raise it if the logs show the process being killed for running out of memory.
Check it worked
Run fly config validate. It reports that the configuration is valid. If it complains, compare your file with the one above; a missing quote around a value is the usual cause.
Step 5 · Set a secret from stdin
ADMIN_TOKEN is a secret, so it does not go in fly.toml, which you commit to Git. Fly.io stores secrets on its side and gives them to the app as environment variables. The usual form, fly secrets set NAME=value, puts the value on the command line, where your shell history and other users' process lists can see it. Instead, pipe it into fly secrets import, which reads NAME=VALUE lines from stdin.
Generate a random token, then type or paste it when read asks; nothing is shown as you paste:
openssl rand -hex 32
read -rs ADMIN_TOKEN
printf 'ADMIN_TOKEN=%s\n' "$ADMIN_TOKEN" | fly secrets import --stageprintf is built into the shell, so the value never appears as a program argument. --stage stores the secret without starting a deploy, because there is nothing deployed yet. Save the token in your password manager; you need it to call /admin/visits. Keep the ADMIN_TOKEN variable in this terminal for the later checks.
Check it worked
fly secrets list shows ADMIN_TOKEN with a digest and a status of something like Staged. The value itself is never shown, by design.
Step 6 · Create the volume and deploy
From this step on, things bill. Fly.io charges running Machines by the second. As of 26 November 2026, its pricing page lists volumes at $0.15 per GB a month whether or not a Machine uses them, a stopped Machine's root filesystem at the same rate, and outbound data from Africa regions at $0.12 per GB, against $0.02 in North America and Europe. Inbound data is free. Check the current figures at fly.io/docs/about/pricing. If your users are on prepaid mobile data, keep responses small: it saves them money and saves you the outbound charge.
Create one 1 GB volume in Johannesburg with the name from [mounts]:
fly volumes create hello_data --region jnb --size 1flyctl warns that a single volume is a single point of failure and asks you to confirm. That warning is the main lesson of volumes, so read it: a volume is part of a drive on one physical server. It is not copied anywhere else. Fly.io takes daily snapshots, kept for 5 days by default, but they are a safety net, not your backup plan.
Deploy, asking for one Machine. A first deploy normally creates spare Machines for availability (--ha defaults to true). Fly.io's availability docs say that when a volume is mounted it starts only one Machine, because volumes are not replicated. Passing --ha=false makes that explicit, so you never end up with two Machines, each with its own empty hello_data volume, from the start. That split is what you see on purpose in the scaling step:
fly deploy --ha=falseFly.io builds the image on its own remote builder by default, so the upload is your source folder, not the finished image. That is useful on a slow or metered connection. Watch for the health check to pass near the end.
Check it worked
Request the app twice:
curl -s "https://$APP.fly.dev/"
curl -s "https://$APP.fly.dev/"The second reply has "visits":2, "region":"jnb" and a Machine ID. Confirm the volume is mounted and owned by the app's user:
fly ssh console -C "ls -ld /data"
fly checks listThe listing shows /data owned by node, and fly checks list shows your /healthz check as passing.
If ls -ld /data shows root instead, and fly logs shows a permission error on visits.db, the volume was mounted over your folder with root as its owner. Fix it at start-up without running the app itself as root. Add a small start.js that starts as root, hands /data to the node user (uid and gid 1000 in the official Node.js images), drops to that user and only then loads the app:
cat > start.js <<'JS'
const fs = require('node:fs')
const dataDir = process.env.DATA_DIR || '/data'
fs.chownSync(dataDir, 1000, 1000)
process.initgroups('node', 'node')
process.setgid('node')
process.setuid('node')
require('./server.js')
JSIn the Dockerfile, change COPY server.js ./ to COPY server.js start.js ./, delete the USER node line and change the last line to CMD ["node", "start.js"]. Then run fly deploy --ha=false again, and fly ssh console -C "ls -ld /data" now shows node. The process gives up root before any of your request code runs.
Finally, call the protected route. The header is read from stdin (-H @-), so the token stays off the command line:
printf 'x-admin-token: %s\n' "$ADMIN_TOKEN" | curl -s -H @- "https://$APP.fly.dev/admin/visits"It prints {"visits":2}. Without the header, the same URL answers {"error":"unauthorised"}.
Step 7 · Scale to two Machines and watch the data split
Add a second Machine in the same region:
fly scale count 2 --region jnbA Machine can mount only one volume and a volume serves only one Machine, so flyctl reports that it will create a new, empty hello_data volume for the new Machine and asks you to confirm. Say yes, then send a few requests:
for i in 1 2 3 4 5 6; do curl -s "https://$APP.fly.dev/"; echo; doneCheck it worked
The replies usually come from two different machine IDs (if they all show one, send a few more), and each has its own visits count: the first Machine carries on from 3, while the second started from 1. You now have two separate databases, not one shared one. Fly.io does not replicate volumes. For an app that keeps its state in SQLite, two Machines means two diverging copies, so either run one Machine, or replicate the database with a tool built for it, or move the data to a database server that every Machine connects to.
For this app, go back to one Machine and remove the volume that is left over, since unused volumes still bill:
fly scale count 1 --region jnb
fly volumes listfly volumes list shows two volumes. One has a Machine ID in its attached column and one has none. Destroy only the unattached one, using its ID from the list. This erases its data:
fly volumes destroy <unattached-volume-id>flyctl chooses which Machine to remove, so the one left may be the second Machine, with its newer volume and lower count. If you want to keep the original database, skip fly scale count 1 and remove the newer Machine yourself instead. fly machine list shows each Machine's ID and when it was created; then run fly machine destroy <newer-machine-id> --force.
Run fly volumes list again; one volume remains, attached to your Machine.
Step 8 · Deploy a new version
Change the message with a one-line Node.js edit, which behaves the same on macOS and Linux:
node -e "const fs=require('fs');fs.writeFileSync('server.js',fs.readFileSync('server.js','utf8').replace(\"'Hello from Fly.io'\",\"'Hello again from Fly.io'\"))"
fly deployfly deploy builds a new image and rolls it out with the rolling strategy, its default, one Machine at a time. With a single Machine and a volume, the Machine is stopped, updated to the new image and started again on the same volume. It should keep its Machine ID, so the machine value in the reply stays the same. Expect a few seconds of failed requests while it restarts. That is the cost of keeping state on one disk. fly releases lists each deploy with a version number, which is what you look at when you need to go back.
Check it worked
curl -s "https://$APP.fly.dev/" replies with "message":"Hello again from Fly.io", and the visits count carries on from before the deploy instead of starting at 1. The machine ID should match the one you saw before. The image was replaced; the volume, and the database on it, was not.
Step 9 · Destroy the app
Destroying an app deletes its Machines, its volumes and their snapshots, its IP addresses, its secrets and its images, and billing for the app stops. The database on the volume is gone for good, so copy anything you want to keep first (for example with fly ssh sftp get /data/visits.db). Then destroy it; flyctl asks you to type the app name to confirm:
fly apps destroy "$APP"Remove the local test image too, and forget the token in this terminal:
docker rmi hello-node:fly
unset ADMIN_TOKENCheck it worked
fly apps list no longer shows your app, and https://hello-node-yourname.fly.dev/ (with your name) no longer answers. In the Fly.io dashboard, the billing or usage page for your organisation shows no running Machines or volumes for the app from this point on.
Next steps
- Compare this with other hosts for a small app before you commit to one:
/tutorials/compare-fly-io-render-and-railway. - Make the image smaller so builds and cold starts are quicker:
/tutorials/make-docker-images-smaller-multi-stage. - Keep
.envfiles and tokens out of the repository you deploy from:/tutorials/keep-secrets-out-of-git.
Related tutorials
- How to Write a Dockerfile for a Node.js AppYou will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.
- Compare Fly.io, Render and Railway for hosting a small appYou will fill in a comparison table of Fly.io, Render and Railway for your own web app and database, covering builds, databases, regions, idle behaviour, disks, networking, previews, logs, pricing and how to leave, and pick one with written reasons.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials