Skip to main content

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:

Bash
docker compose version

The 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:

Bash
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 .env

Check 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.

Bash
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;
SQL

The 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.

Bash
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);
SQL

Check 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:

Bash
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"
YAML

The parts that make migrate a one-shot job:

  • migrate reuses the postgres:18 image only for its psql client. The image's entrypoint runs any command that is not postgres as it is, so the container runs the loop over /migrations/*.sql and exits. ON_ERROR_STOP=1 turns the first failed statement into a non-zero exit code, and || exit 1 stops the loop there. The doubled $$ stops Compose from treating $f as one of its own variables.
  • restart: "no" keeps Docker from starting the container again once it exits. The quotes matter: unquoted, YAML reads no as the boolean false. Never give a job like this unless-stopped or always, or it reruns in a loop.
  • api waits on two conditions. service_healthy on db means PostgreSQL accepts connections. service_completed_successfully on migrate means 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.
  • migrate has 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:

Bash
docker compose config --quiet && echo "compose.yaml is valid"
docker compose config --services | sort

You 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:

Bash
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"]
YAML

The 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:

Bash
docker compose config --quiet && echo "compose.yaml is valid"
docker compose config --services | sort
docker compose config --profiles

The 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:

Bash
docker compose --profile tools config --services | sort
docker compose --profile tools --profile seed config --services | sort
docker compose --profile "*" config --services | sort

The 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:

Bash
COMPOSE_PROFILES=tools docker compose config --services | sort

To 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:

Bash
docker compose up -d

Compose 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:

Bash
docker compose ps -a
docker compose logs migrate
curl -s http://127.0.0.1:3000/notes

migrate 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:

Bash
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:

Bash
docker compose run --rm migrate

Open 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:

Bash
docker compose --profile tools up -d

Open 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:

Bash
docker compose stop adminer

If 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:

Bash
docker compose --profile "*" config --no-interpolate

The 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:

Bash
docker compose --profile "*" down -v
cd ~
rm -r ~/notes-demo

Check 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 dbdata volume across down, up and 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 migrate service.
  • 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.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.