Containers and Kubernetes · Intermediate · 15 min
Run migrations and admin tools as optional Compose services with profiles
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Docker Engine 29.10 · Docker Compose 5.8 · PostgreSQL 18 · PostgREST 16.6 · Adminer 6.3.1
You will have a Compose project where a one-shot migration finishes before the API starts, while Adminer and a seed job stay switched off until you ask for them with a profile or a one-off run.
On this page
Most Compose projects grow a few containers that should not run all the time. A database migration has to run once, before the app, and then stop. A database admin tool is handy on the day you debug something and a needless open port the rest of the week. A seed job that fills the tables with sample data must never run by accident against data you care about.
Compose has two features for this. A one-shot service with restart: "no" and a service_completed_successfully dependency runs to the end before the services that need it start. Profiles keep a service out of docker compose up until you switch its profile on, or name the service yourself.
In this tutorial you will build a small notes API: PostgreSQL 18, PostgREST 16.6 serving the notes table as JSON, a migrate job that creates the table, and two optional services, Adminer and a seed job. You will check every variant of the file with docker compose config, which reads and resolves the file without starting anything, then start the stack and run the optional pieces on demand.
Step 1 · Check Compose and create the project
Confirm the Compose plugin is installed and is version 5:
docker compose versionThe output reads something like Docker Compose version v5.8.0. Profiles and service_completed_successfully have been in Compose for years, so any v5 release works.
Create a throwaway project folder and a private .env file for the database password. The file is created with mode 600 before anything is written into it, and the password comes from a random generator, so it never sits in your shell history or in compose.yaml:
mkdir -p ~/notes-demo/migrations ~/notes-demo/seeds
cd ~/notes-demo
install -m 600 /dev/null .env
echo "POSTGRES_PASSWORD=$(openssl rand -hex 16)" >> .env
ls -l .envCheck it worked
ls -l shows -rw------- for .env, and ls ~/notes-demo lists the empty migrations and seeds folders. If this folder becomes a Git repository, add .env to .gitignore first.
Step 2 · Write the migration and the seed data
The migration creates the notes table and a web_anon role, which PostgREST switches to for requests that carry no login. It runs every time the stack comes up, so each statement has to be safe to repeat: IF NOT EXISTS for the table, a check before creating the role, and grants, which do nothing the second time.
cat > migrations/001_notes.sql <<'SQL'
CREATE TABLE IF NOT EXISTS notes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'web_anon') THEN
CREATE ROLE web_anon NOLOGIN;
END IF;
END
$$;
GRANT USAGE ON SCHEMA public TO web_anon;
GRANT SELECT ON notes TO web_anon;
SQLThe seed file inserts three sample notes, only when the table is empty, so running it twice does not double the rows. The notes are greetings in Swahili, Yoruba and Amharic. Sample data with tone marks and non-Latin scripts shows early whether every layer, from the database to the JSON response, keeps UTF-8 text intact.
cat > seeds/sample-notes.sql <<'SQL'
INSERT INTO notes (body)
SELECT v FROM (VALUES
('Habari za asubuhi'),
('Báwo ni'),
('ሰላም')
) AS t(v)
WHERE NOT EXISTS (SELECT 1 FROM notes);
SQLCheck it worked
ls migrations seeds lists 001_notes.sql and sample-notes.sql. Real projects usually hand migrations to a tool that records which files it has applied, such as the one built into your web framework. The pattern in this tutorial stays the same: that tool's command becomes the migrate service's command.
Step 3 · Write compose.yaml with a one-shot migrate service
Write the file. The top-level volumes key comes first and services last, so the next step can add services by appending to the end of the file:
cat > compose.yaml <<'YAML'
name: notes-demo
volumes:
dbdata:
services:
db:
image: postgres:18
restart: unless-stopped
environment:
POSTGRES_USER: app
POSTGRES_DB: notesdb
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
volumes:
- dbdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U app -d notesdb"]
interval: 3s
timeout: 3s
retries: 10
start_period: 20s
migrate:
image: postgres:18
restart: "no"
depends_on:
db:
condition: service_healthy
environment:
PGHOST: db
PGUSER: app
PGDATABASE: notesdb
PGPASSWORD: ${POSTGRES_PASSWORD}
volumes:
- ./migrations:/migrations:ro
command:
- sh
- -c
- for f in /migrations/*.sql; do echo "applying $$f"; psql -v ON_ERROR_STOP=1 -q -f "$$f" || exit 1; done
api:
image: postgrest/postgrest:v16.6
restart: unless-stopped
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
environment:
PGRST_DB_URI: postgres://app:${POSTGRES_PASSWORD}@db:5432/notesdb
PGRST_DB_SCHEMAS: public
PGRST_DB_ANON_ROLE: web_anon
ports:
- "127.0.0.1:3000:3000"
YAMLThe parts that make migrate a one-shot job:
migratereuses thepostgres:18image only for itspsqlclient. The image's entrypoint runs any command that is notpostgresas it is, so the container runs the loop over/migrations/*.sqland exits.ON_ERROR_STOP=1turns the first failed statement into a non-zero exit code, and|| exit 1stops the loop there. The doubled$$stops Compose from treating$fas one of its own variables.restart: "no"keeps Docker from starting the container again once it exits. The quotes matter: unquoted, YAML readsnoas the booleanfalse. Never give a job like thisunless-stoppedoralways, or it reruns in a loop.apiwaits on two conditions.service_healthyondbmeans PostgreSQL accepts connections.service_completed_successfullyonmigratemeans the job ran and exited with code 0. If the migration fails, Compose does not start the API at all, which is better than an API answering requests against a half-built schema.migratehas no profile, on purpose. A service the API depends on must start whenever the API starts. Compose's profile rules say a dependency has to share the dependent service's profile or have none, so the job stays in the default set. It is cheap: on a database that is already migrated, every statement is a no-op.
Only api publishes a port, and only on 127.0.0.1. The database is reachable from the other services on the project network and nowhere else.
Check it worked
Ask Compose to validate the file and list the services it would start:
docker compose config --quiet && echo "compose.yaml is valid"
docker compose config --services | sortYou see compose.yaml is valid, then api, db and migrate, one per line. An indentation mistake shows up here as an error with a line number, before anything is pulled or started.
Step 4 · Put Adminer and the seed job behind profiles
Append the two optional services. Each gets a profiles list, which takes it out of the default set:
cat >> compose.yaml <<'YAML'
adminer:
image: adminer:6.3.1
profiles: [tools]
restart: "no"
depends_on:
db:
condition: service_healthy
environment:
ADMINER_DEFAULT_SERVER: db
ports:
- "127.0.0.1:8081:8080"
seed:
image: postgres:18
profiles: [seed]
restart: "no"
depends_on:
migrate:
condition: service_completed_successfully
environment:
PGHOST: db
PGUSER: app
PGDATABASE: notesdb
PGPASSWORD: ${POSTGRES_PASSWORD}
volumes:
- ./seeds:/seeds:ro
command: ["psql", "-v", "ON_ERROR_STOP=1", "-f", "/seeds/sample-notes.sql"]
YAMLThe two profiles have different jobs. tools holds things you open by hand while you work, and you could add a log viewer or a mail catcher to it later. seed holds the one job that writes sample data, kept apart so that switching on tools never seeds anything. Both services depend only on services without a profile, so they can always reach a running database.
seed waits for migrate to finish, so on a fresh volume the table exists before the insert runs. Adminer gets restart: "no" too: when you stop it, it stays stopped.
Check it worked
Run the same two checks again:
docker compose config --quiet && echo "compose.yaml is valid"
docker compose config --services | sort
docker compose config --profilesThe services list still shows only api, db and migrate. Adminer and the seed job are in the file but not in the default set. --profiles prints the profile names the file defines, seed and tools.
Step 5 · Switch profiles on with --profile and COMPOSE_PROFILES
--profile goes before the subcommand and can be repeated. Look at what each choice would start:
docker compose --profile tools config --services | sort
docker compose --profile tools --profile seed config --services | sort
docker compose --profile "*" config --services | sortThe first command adds adminer to the list, the second adds adminer and seed, and --profile "*" switches on every profile in the file.
The COMPOSE_PROFILES environment variable does the same job, with profile names separated by commas:
COMPOSE_PROFILES=tools docker compose config --services | sortTo make a profile your default for this project, add a line COMPOSE_PROFILES=tools to .env. A value set in your shell takes precedence over the one in .env, so COMPOSE_PROFILES= docker compose up -d still gives you the plain stack for one command. Keep seed out of that default: a profile you have to type each time is a small guard against seeding by habit.
Profiles also save downloads. docker compose up only pulls images for the services it starts, so the Adminer image is never fetched until you ask for it. On a metered or prepaid connection, that is a few tens of megabytes you choose when to spend.
Check it worked
You have seen four service lists from one file: three services by default, four with tools, five with both profiles or "*", and four again with COMPOSE_PROFILES=tools. No container ran to produce any of them.
Step 6 · Start the stack and run the one-off tasks
Start the default set in the background:
docker compose up -dCompose starts db, waits for its healthcheck, runs migrate to the end and only then starts api. The output includes lines such as Container notes-demo-migrate-1 Exited before Container notes-demo-api-1 Started. A plain docker compose ps hides stopped containers, so add -a to see the job:
docker compose ps -a
docker compose logs migrate
curl -s http://127.0.0.1:3000/notesmigrate shows a status like Exited (0), its log contains applying /migrations/001_notes.sql, and the API answers []: the table exists and is empty.
Now seed it. docker compose run starts a fresh container for one service, plus the services it depends on, and runs it in the foreground. Naming a service starts it even when its profile is off, so you do not need --profile seed here. --rm deletes the container when it exits:
docker compose run --rm seed
curl -s "http://127.0.0.1:3000/notes?select=id,body"psql prints INSERT 0 3, and the API returns three notes, with the Yoruba tone marks and the Amharic script exactly as written. Run the seed command a second time and it prints INSERT 0 0, because the table is no longer empty.
When you add a migration file later, apply it without restarting anything else:
docker compose run --rm migrateOpen Adminer when you need it
docker compose run does not publish a service's ports unless you add --service-ports, so for a tool you open in the browser, start it as a normal service with its profile:
docker compose --profile tools up -dOpen http://127.0.0.1:8081, choose PostgreSQL as the system, and log in with server db, user app, database notesdb and the password from .env (grep POSTGRES_PASSWORD .env shows it; do not run that on a shared screen). The notes table is listed with three rows. When you are done, stop Adminer alone and leave the rest running:
docker compose stop adminerIf the Compose project runs on a remote server, keep the 127.0.0.1 binding and reach Adminer through an SSH tunnel (ssh -L 8081:127.0.0.1:8081 you@server) rather than publishing it to the internet.
Check it worked
docker compose ps -a lists api and db as running, migrate as exited with code 0 and adminer as exited after you stopped it. There is no seed container, because --rm removed it. The API returns the three seeded notes.
Step 7 · Read the effective file and clean up
docker compose config prints the file as Compose will use it: defaults filled in, short syntax expanded, paths made absolute and variables replaced. That last part includes the database password, so for a copy you can paste into a review or a chat, skip interpolation:
docker compose --profile "*" config --no-interpolateThe output shows ${POSTGRES_PASSWORD} as a reference, not its value, and each dependency in long form with its condition, for example condition: service_completed_successfully under api and seed.
The next command deletes every container in the project, in every profile, and, because of -v, the dbdata volume with all the notes in it. A plain docker compose down would leave Adminer behind, because without a profile it only touches services that have none:
docker compose --profile "*" down -v
cd ~
rm -r ~/notes-demoCheck it worked
docker ps -a --filter name=notes-demo and docker volume ls --filter name=notes-demo both print only their header lines. The postgres:18, postgrest/postgrest:v16.6 and adminer:6.3.1 images stay on disk for next time; remove them with docker rmi when you want the space back.
Next steps
- Learn what happens to the
dbdatavolume acrossdown,upand image upgrades in /tutorials/keep-container-data-with-docker-volumes. - Build your own app image into a stack like this one with /tutorials/docker-compose-app-with-postgres, then turn its migration command into a
migrateservice. - Keep your app on your own machine and only its backing services in Compose, with profiles for the optional ones, in /tutorials/run-your-local-dev-services-with-docker-compose.
- Set up the Docker Engine and Compose plugin on a fresh server with /tutorials/install-docker-engine-on-ubuntu-26-04.
Related tutorials
- Keep container data safe with Docker volumes and bind mountsYou will keep data in a named volume, edit files through a read-only bind mount, fix a user ID mismatch, use tmpfs for scratch files, and back up and restore a volume with a throwaway container and tar.
- How to Run an App and PostgreSQL Together with Docker ComposeYou will describe a Node.js app and a PostgreSQL 18 database in one compose.yaml, start both with one command, keep the data in a named volume, and keep the database password out of the file.
- Run local development services with Docker Compose while you code on your machineYou will have PostgreSQL 18, Redis 8, a Mailpit inbox and a small stub payments API running in Docker Compose on 127.0.0.1, with healthchecks, optional profiles, a personal override file and a one-command data reset, while your app keeps running on your own machine.
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