Skip to content
R.

Start Compose with an optional dependency

Use profiles and long-form depends_on with required: false to keep Compose startup orderly when an optional service is absent.

About 10 min readComments

Docker Compose can express two different relationships that often get conflated: a service may need another service to start first, and a service may also want to keep running when an optional integration is absent. Those are separate decisions.

This article uses a small fixture to show the difference between a required dependency edge and an optional one hidden behind a profile. The goal is not a readiness tutorial; it is a startup contract that still works when the optional service is not enabled.

The key idea is simple: profiles decide whether the service exists in the active model, and required:false decides whether the missing edge blocks startup. When the profile is enabled, normal ordering still applies.

The problem is not readiness; it is absence

A Compose stack can fail for two very different reasons. In one case, the dependent service starts too early and the provider is present but not ready yet. In the other case, the provider is not supposed to be present at all unless a profile is enabled. Those are not the same failure, and they should not be fixed with the same knob.

The official startup-order guide explains that Compose starts containers in dependency order, but it does not wait for a container to become ready unless you declare a health-based condition. That is useful when a backend exists and just needs time. It does not answer the separate question of what should happen when an integration is optional and intentionally omitted.

The useful outcome here is degraded startup, not delayed startup. The application should still come up, print the warning path, and keep operating with the feature disabled when the optional service is not enabled. When the profile is present, the same dependency edge should still impose normal ordering so the integration starts before the consumer.

main.mjs / javascript
/**
 * A Compose configuration fixture for an application whose telemetry service is
 * optional. This module only builds and validates configuration data; it does
 * not invoke Docker Compose.
 */
export function buildComposeFixture({ integrationRequired = false } = {}) {
  if (typeof integrationRequired !== 'boolean') {
    throw new TypeError('integrationRequired must be a boolean');
  }

  return {
    services: {
      app: {
        image: 'busybox:1.36',
        command: ['sh', '-c', 'echo app-started-with-optional-telemetry'],
        depends_on: {
          telemetry: {
            // This orders startup when telemetry is enabled; it is not a
            // readiness/healthcheck wait.
            condition: 'service_started',
            required: integrationRequired,
          },
        },
      },
      telemetry: {
        image: 'busybox:1.36',
        command: ['sh', '-c', 'echo telemetry-started'],
        profiles: ['telemetry'],
      },
    },
  };
}

/**
 * Produces the command a reader can run against a real Docker Compose engine.
 * Omitting the profile leaves telemetry unavailable to this invocation.
 */
export function composeUpCommand({ enableTelemetry = false } = {}) {
  if (typeof enableTelemetry !== 'boolean') {
    throw new TypeError('enableTelemetry must be a boolean');
  }

  return enableTelemetry
    ? ['docker', 'compose', '--profile', 'telemetry', 'up', 'app']
    : ['docker', 'compose', 'up', 'app'];
}

/** Validates the narrow shape this fixture relies on before writing it to YAML. */
export function validateComposeFixture(fixture) {
  const dependency = fixture?.services?.app?.depends_on?.telemetry;
  const profiles = fixture?.services?.telemetry?.profiles;

  if (!dependency || typeof dependency.required !== 'boolean') {
    throw new TypeError('app.depends_on.telemetry.required must be a boolean');
  }
  if (dependency.condition !== 'service_started') {
    throw new RangeError('telemetry must use condition: service_started');
  }
  if (!Array.isArray(profiles) || !profiles.includes('telemetry')) {
    throw new RangeError('telemetry must be behind the telemetry profile');
  }

  return fixture;
}

export const proofBoundary =
  'These tests validate generated Compose configuration and commands only. Run the returned commands with a real Docker Compose implementation to observe its warning and continuation behavior when the optional profile is omitted.';

SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification: depends_on (opens a new tab)

Put the optional service behind a profile

Docker’s profiles guide explains how a profile selects services for a run. A service assigned to a profile runs when that profile is enabled or when you target the service explicitly. Keep the core application unprofiled and put the optional integration behind its own profile.

This is a better fit than deleting the service from the file or inventing a second Compose file for the common case. The service definition can stay in one place, its image and runtime arguments remain visible, and the operator chooses whether the integration participates in the run. That means the stack shape changes intentionally, not by editing the file to suit one environment.

In the fixture, the optional service is telemetry and the profile name is also telemetry. That keeps the dependency obvious: the app can refer to telemetry, but telemetry only exists in the active Compose model when the profile is enabled. The absence is therefore deliberate, not an error in the file.

SourcesDocker Compose profiles (opens a new tab)

Use required: false to keep the app running

Docker’s workload specification documents the long form of depends_on. An entry with required: false lets Compose continue with a warning when the named service cannot be started or is unavailable. The option was introduced in Compose 2.20.0. Set it on the individual dependency, alongside the condition that applies when the service participates.

With the telemetry profile disabled, the optional service is outside the active model. With the profile enabled, the dependency still expresses startup order. Check both configurations with docker compose config --services, first without a profile and then with --profile telemetry. The included Node tests verify the dependency flag and command arguments in the fixture. Check runtime warnings and application readiness separately during an actual start.

The startup-order guide also distinguishes ordering from readiness. In this fixture, the dependency condition is service_started, which means Compose only needs the dependency container to be started, not healthy. That is intentional. The article is about whether startup can continue when the service is optional, not about waiting for a healthcheck to pass.

SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification: depends_on (opens a new tab)

What the broken case looks like

The failure mode is easiest to recognize when the profile is omitted and the app still declares the dependency as required. In that configuration, the optional service is absent from the active model, but the app still asks Compose to treat it as mandatory. The result is a startup that cannot reconcile the declared dependency graph with the services actually present.

That is different from a slow backend. A slow backend is present but not yet ready, so a readiness condition or healthcheck can solve it. An absent backend is simply not there. If the dependency remains required in that situation, the app is no longer describing an optional integration; it is demanding an unavailable one.

The article's fixture contrasts these cases directly. One variant keeps required:false and allows the app to continue when telemetry is not in the run. The other variant flips the dependency to required:true to show the opposite ownership rule: the same Compose model can express a hard edge, but then the omission is no longer graceful.

SourcesDocker Compose startup order (opens a new tab)

Why this is not a healthcheck story

It is tempting to file every Compose startup issue under readiness, because Compose has a well-documented service_healthy condition. But that solves only the case where the dependency exists and needs time. It does not answer whether a dependency may be absent and still leave the rest of the stack usable.

That distinction matters operationally. A healthcheck can tell you whether a database is ready to accept traffic. It cannot tell you whether a telemetry collector should even be in the run. Profiles and required:false work at a different level: they decide whether the dependency participates at all, and whether the missing edge should block startup.

This is why the fixture keeps the condition at service_started instead of service_healthy. The article is not trying to teach Compose readiness, and it is not pretending that a healthcheck is a substitute for optionality. The question is about ownership of the dependency graph when the integration is turned off by design.

SourcesDocker Compose workload specification: depends_on (opens a new tab)

What this pattern does and does not guarantee

This pattern guarantees a cleaner Compose contract, not application-level fallback logic. Compose can decide whether the optional service participates, can preserve ordering when it does, and can tolerate the missing service when required:false is set. It cannot decide what your application should do after startup if telemetry is missing.

That means the application still owns the degraded-mode behavior. It must be able to start without the integration, choose a sensible default, and emit whatever warning or note is useful for operators. Compose only supplies the shape of the run. It does not replace feature flags, environment-based defaults, or runtime branching inside the app.

There are two useful edge cases to keep in mind. First, if the optional service is present but unhealthy, required:false does not magically make a broken integration usable; you still need to decide whether the app should tolerate that failure. Second, if you later promote the optional service into a mandatory one, the dependency should be changed deliberately instead of assuming the old optional edge will fail closed.

main.test.mjs / javascript
import test from 'node:test';
import assert from 'node:assert/strict';
import {
  buildComposeFixture,
  composeUpCommand,
  validateComposeFixture,
} from './main.mjs';

test('enabled telemetry profile retains the app-to-telemetry startup edge', () => {
  const fixture = buildComposeFixture();
  const command = composeUpCommand({ enableTelemetry: true });

  assert.equal(validateComposeFixture(fixture), fixture);
  assert.deepEqual(command, [
    'docker',
    'compose',
    '--profile',
    'telemetry',
    'up',
    'app',
  ]);
  assert.deepEqual(fixture.services.app.depends_on.telemetry, {
    condition: 'service_started',
    required: false,
  });
});

test('omitting the optional profile keeps the dependency explicitly non-required', () => {
  const fixture = buildComposeFixture({ integrationRequired: false });
  const command = composeUpCommand({ enableTelemetry: false });

  assert.equal(validateComposeFixture(fixture), fixture);
  assert.deepEqual(command, ['docker', 'compose', 'up', 'app']);
  assert.equal(fixture.services.telemetry.profiles.includes('telemetry'), true);
  assert.equal(fixture.services.app.depends_on.telemetry.required, false);
});

test('required-edge variant marks the absent-profile dependency as required', () => {
  const fixture = buildComposeFixture({ integrationRequired: true });
  const command = composeUpCommand({ enableTelemetry: false });

  assert.equal(validateComposeFixture(fixture), fixture);
  assert.deepEqual(command, ['docker', 'compose', 'up', 'app']);
  assert.equal(fixture.services.app.depends_on.telemetry.required, true);
});

test('fixture builder rejects a non-boolean required setting', () => {
  assert.throws(
    () => buildComposeFixture({ integrationRequired: 'false' }),
    /integrationRequired must be a boolean/,
  );
});

SourcesDocker Compose startup order (opens a new tab)Docker Compose workload specification: depends_on (opens a new tab)

Share LinkedIn Email Subscribe

Discussion

Leave a comment

Comments appear after review. No email needed.

Image preview

Follow the blog

Choose email updates or your favorite RSS reader.

The weekly email

New articles on code, design, and AI. Fridays, only when there is something new.

By subscribing, you agree to weekly blog emails.
Confirm in your inbox. Unsubscribe anytime. Privacy

Use OpenRSS

Preview the feed, then choose a reader to subscribe.

Open in OpenRSS (opens a new tab)

Already have a reader?

Paste this link into your reader's Add feed option.

Prefer a reader? RSS does not require an email address. View XML feed