brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: service_completed_successfully runs a one-off job before the app

Docker
~/tips/tip-compose-service-completed-successfully

condition: service_completed_successfully

Makes a compose service wait until another one has finished its job with exit code 0.

Some apps need a job to finish before they start, such as a database migration or a script that fixes folder permissions. A depends_on condition covers that.

Put the job in its own service and tell the app to wait until it ends well:

services:
  migrate:
    image: example/app:latest
    command: ["./migrate"]
    restart: "no"
  app:
    image: example/app:latest
    depends_on:
      migrate:
        condition: service_completed_successfully

The long form of depends_on has three conditions. service_started is what the short form does, service_healthy waits for a healthcheck, and service_completed_successfully waits until the dependency has run to a successful finish. I set restart: "no" on the job so the engine does not start it again after it exits.

Successful means exit code 0. If the job fails, the app does not start, so read the job’s logs first:

docker compose logs migrate

Caveats: the job runs every time the stack comes up, so the command has to be safe to run twice. And it has to exit. A healthcheck suits a service that keeps running, but a job that never ends leaves the app waiting forever.

Further reading: Compose workload spec: depends_on

Going deeper: Guide: replace a cron job with a systemd timer, and see when it runs next

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link