Wait for Compose migrations to finish first
Use long-form `depends_on` with `service_completed_successfully` so an app starts only after a migration container exits 0, and stays blocked on failed migrations.
A one-shot migration job is not the same thing as a service that becomes ready and stays ready. That sounds obvious until a Compose file starts the app early enough to hit missing tables, missing columns, or a half-applied schema. The important question is not whether Compose can launch containers in order; it is whether the app is blocked until the migration has actually finished and exited successfully. Compose can express that, but only if you choose the right dependency form.
This article focuses on that specific contract. The fixture uses a separate migration service and long-form `depends_on` with `condition: service_completed_successfully`, so the app is gated on successful completion rather than mere startup. The supporting tests check the configuration shape and the rejection paths, while the docs explain the documented behavior. The result is a narrow answer: how to model the startup relationship, what it guarantees, and where the guarantee ends.
What Compose waits for, and what it does not
The problem is easy to describe and easy to misunderstand. You want one container to prepare the database schema, then a second container to start the app only after that preparation has completed successfully. Compose can order service startup, but startup order is not the same thing as completion. A container can be running long before the work inside it is finished, and a one-shot migration is exactly the kind of service that exposes that gap.
Docker’s startup-order documentation makes the distinction explicit: Compose waits for services to be running, or for a healthcheck to pass if you ask for `service_healthy`, but a dependent service can still begin too early if you only rely on short syntax. The workload specification adds the missing piece: `service_completed_successfully` means the dependency must run to successful completion before the dependent service starts. That is the behavior you need for a migration job, because success is not just “the process began” but “the process exited 0.”
The useful boundary is that this is a Compose dependency contract, not a database contract. Compose can delay the app until the migration container exits successfully, but it does not validate that the migration actually applied the intended schema or that the app’s first query will succeed. That is still your application’s responsibility. The article’s fixture therefore focuses on the dependency rule itself, not on pretending to execute PostgreSQL migrations inside a local mock.
This distinction also explains why `healthcheck` is not the right model for a migration job. A healthcheck describes a long-lived service that becomes ready and stays available. A migration is the opposite: it should finish, and then the app should start. If you treat those two shapes as interchangeable, you end up with a Compose file that looks plausible but does not encode the real startup dependency.
export const proofBoundary =
'This module validates a Compose configuration shape only. It does not run Docker Compose and cannot prove container exit status or startup ordering; run `docker compose up` with Docker Compose to perform that integration check.';
/**
* Builds the relevant part of a Compose configuration for a one-shot migration.
* The migration command is supplied by the application rather than inferred.
*/
export function createMigrationComposeConfig({ migrationCommand }) {
if (!Array.isArray(migrationCommand) || migrationCommand.length === 0) {
throw new TypeError('migrationCommand must be a non-empty command array');
}
if (!migrationCommand.every((part) => typeof part === 'string' && part.length > 0)) {
throw new TypeError('every migrationCommand item must be a non-empty string');
}
return {
services: {
db: {
image: 'postgres:18',
},
migrate: {
image: 'example/app:latest',
command: [...migrationCommand],
depends_on: {
db: { condition: 'service_started' },
},
},
app: {
image: 'example/app:latest',
depends_on: {
migrate: { condition: 'service_completed_successfully' },
},
},
},
};
}
/**
* Checks the application-owned configuration requirement documented by Compose:
* app must use long-form depends_on and require successful migration completion.
*/
export function validateAppWaitsForMigration(config) {
const dependency = config?.services?.app?.depends_on?.migrate;
if (!dependency || Array.isArray(config?.services?.app?.depends_on)) {
throw new TypeError('services.app.depends_on.migrate must use long syntax');
}
if (dependency.condition !== 'service_completed_successfully') {
throw new RangeError(
'services.app.depends_on.migrate.condition must be service_completed_successfully',
);
}
return true;
}
SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification (opens a new tab)
Why long-form `depends_on` matters
The source of the bug is usually a shorthand that seems sufficient until you read it literally. Short-form `depends_on` can ensure creation order, but it cannot express the extra condition that the dependency must finish successfully. That means the app may start after the migration container has been created and launched, yet before the migration has actually completed its work. For a one-shot job, that is the wrong ownership boundary.
Long-form `depends_on` is where Compose exposes the additional state machine. The workload specification says the dependency relationship can include `condition`, `restart`, and `required`. For this article, the decisive field is `condition: service_completed_successfully`. The app is not waiting for a port, a log line, or an arbitrary sleep; it is waiting for the container process itself to exit with a success status. That is much closer to the intent of “run migrations first, then boot the app.”
There is another reason to keep the dependency explicit in Compose rather than in the app’s entrypoint. If the application shell script owns both migration and startup, the app container becomes responsible for two separate concerns: schema preparation and service lifetime. That makes failures harder to classify. With a separate migration service, the migration can fail independently, Compose can keep the app from starting, and the failure is visible in the dependency graph instead of being hidden inside a single startup script.
The long form also communicates intent to future readers. A Compose file that names `migrate` and sets `service_completed_successfully` tells the truth about the startup contract in one line. A plain list of dependencies only says “this service depends on another service,” which is too weak for a one-shot job. The difference matters because the next person to touch the file can see whether the app waits for readiness or for completion.
SourcesDocker Compose workload specification (opens a new tab)
Read the fixture as a contract check
The supplied example does not try to simulate Docker itself. It validates the application-owned Compose shape: the migration command is supplied explicitly, the migration depends on the database starting, and the app depends on the migration with `condition: service_completed_successfully`. That gives the reader a small, inspectable fixture whose job is to confirm the configuration expresses the intended contract.
This matters because a lot of false confidence comes from testing the wrong thing. A Node test can verify that the generated object contains the expected fields and that a helper rejects short syntax or the wrong condition. It cannot prove that Compose will behave correctly on a real engine, because the engine’s process lifecycle and container orchestration are outside Node’s control.
The happy-path test is still useful because it preserves the exact shape the article teaches. If the `app` service no longer uses long-form `depends_on`, or if the condition changes to `service_started`, the test fails before a reader copies a weaker contract. Likewise, the empty-command rejection keeps the fixture honest: a migration service must be a real command, not an implied placeholder.
That leaves a clear proof boundary. The local fixture checks that the Compose file is structured to wait for successful completion. The reader-run integration step, using Docker Compose itself, is where the actual startup sequence is observed. Keeping those responsibilities separate avoids overclaiming while still giving the article a concrete, reproducible example.
SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification (opens a new tab)
Why a failed migration blocks the app
The failure case is the whole point of the dependency choice. If the migration exits non-zero, Compose must not start the app service. That is what `service_completed_successfully` buys you: the app only becomes eligible once the migration has succeeded, and failure keeps the dependency unsatisfied. The article’s outcome should be framed around that observable effect, not around an abstract “safer deployment” claim.
This is also why the error path should remain visible instead of being swallowed by a shell wrapper. If the migration process fails and your entrypoint script still continues, the app can start against a database that has not been prepared. The problem then looks like an app bug or a database outage, when the real issue is that the migration was allowed to fail open. Compose’s completion condition prevents that mistaken start, but only if the migration is its own service.
The negative case is useful because it prevents a common incomplete fix: waiting for the database to be running, or even healthy, is not enough when the schema itself is what the app needs. A database can be up, accepting connections, and still be missing tables or columns. In that scenario, `service_healthy` tells you less than the migration completion condition does. That is the key distinction the article should preserve.
A second edge case is recovery after a failed migration. Compose’s dependency rule does not repair the database; it only blocks the app from starting until the prerequisite is satisfied. If the migration is corrected, rerun, and exits successfully, then the app may start on the next Compose operation. The orchestration rule is about gating startup, not about rolling back failed schema changes.
What the example config actually encodes
The example config is intentionally small because the interesting part is the dependency shape, not the surrounding application. It encodes three services: a database, a one-shot migration job, and the app. The database starts first, the migration waits for the database to be started, and the app waits for the migration to complete successfully. That chain is the minimum structure needed to describe the startup dependency clearly.
The migration command is passed in rather than implied, which keeps the fixture honest about ownership. Compose is not guessing what the migration should do; the application chooses the command. The validation helper then checks that the app dependency uses long syntax and the correct condition. Those checks are narrow on purpose. They reject a weaker configuration before it can be treated as equivalent to the documented behavior.
One incomplete repair would be to keep short-form `depends_on` and add a comment saying the app should not start early. Comments do not change runtime behavior. Another incomplete repair would be to point the app at a healthcheck on the migration service, but jobs are not long-lived services and the docs explicitly distinguish jobs from services.
The real value of the fixture is that it shows the app dependency as data, not folklore. If a future edit changes the condition, the helper fails. If the migration command disappears, the helper fails. If short syntax creeps back in, the helper fails. That is the kind of guardrail a debugging article needs: small enough to inspect, strict enough to catch the exact class of regression the reader came to prevent.
SourcesDocker Compose workload specification (opens a new tab)
Where this pattern stops helping
This pattern is useful, but it is not a universal startup policy. It solves one question: should the app start before a migration has succeeded? It does not solve schema drift, idempotency, or concurrent deploys. If the migration is unsafe to rerun, or if two deployments can race each other, you need a stronger release design than a single Compose dependency can provide.
It is also not a substitute for checking that the app can actually connect to the database after startup. Compose can gate startup on successful completion, but it cannot guarantee that the app’s credentials, connection string, or first query are correct. That is why a real deployment still needs application-side retries or a clear failure mode after the app starts. The Compose rule reduces one class of premature startup; it does not eliminate all runtime failure.
Another limit is operational visibility. When the migration fails, the app never starts, which is what you want, but you still need logs and alerts that point to the failing migration container. Otherwise the deployment just looks stalled. The article can mention that the orchestration decision makes failure easier to classify, but the operator still needs to inspect the migration exit status and logs to decide what to fix next.
The right closing takeaway is narrow and practical: use long-form `depends_on` with `service_completed_successfully` when the app must not start until a one-shot migration has exited 0. Use healthchecks for long-lived readiness, and keep migration success separate from app startup. That division is the mechanism the docs support, and it is the exact answer to the question the article promises.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createMigrationComposeConfig,
validateAppWaitsForMigration,
} from './main.mjs';
test('app configuration requires migration to complete successfully', () => {
const config = createMigrationComposeConfig({
migrationCommand: ['npm', 'run', 'migrate'],
});
assert.equal(validateAppWaitsForMigration(config), true);
assert.deepEqual(config.services.app.depends_on.migrate, {
condition: 'service_completed_successfully',
});
});
test('rejects a started-only migration dependency', () => {
const config = createMigrationComposeConfig({
migrationCommand: ['npm', 'run', 'migrate'],
});
config.services.app.depends_on.migrate.condition = 'service_started';
assert.throws(
() => validateAppWaitsForMigration(config),
/service_completed_successfully/,
);
});
test('rejects short depends_on syntax because it cannot express completion success', () => {
const config = createMigrationComposeConfig({
migrationCommand: ['npm', 'run', 'migrate'],
});
config.services.app.depends_on = ['migrate'];
assert.throws(
() => validateAppWaitsForMigration(config),
/long syntax/,
);
});
test('rejects an empty migration command while building the fixture', () => {
assert.throws(
() => createMigrationComposeConfig({ migrationCommand: [] }),
/non-empty command array/,
);
});
SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification (opens a new tab)


