Skip to content
Dexor Discuss your project
Menu

Repeatable Docker Compose deployments: release, verify and recover

The pipeline is green. The container is running. Yet a colleague still sees the old version—or a feature has started returning the wrong results. Now the questions begin: which image actually started? Which configuration did it receive? And what, exactly, would a rollback restore?

A repeatable Docker Compose deployment ties together the image digest, configuration, target and functional checks. We will build a small service, deploy it and deliberately introduce a faulty release. By the end, you will have a procedure for identifying a release and restoring a known working state.

A deployment workstation connected to three servers by cables

A release needs more than a name

catalog:latest is a convenient pointer. It is insufficient evidence of what is running: tomorrow, the same tag might identify another image. A digest binds the reference to particular image contents. We therefore pass a digest from the build into deployment and avoid rebuilding on the target server.

This makes the deployment repeatable. A byte-for-byte reproducible build is a further task: it requires control over tool versions, dependencies and influences such as timestamps. Here, our aim is to deploy an already built artifact reliably again. Docker’s CLI documentation explains pulling an image by digest.

  1. ImageDigest and platform identify the artifact.
  2. ConfigurationVersioned files and an explicit target complete it.
  3. DeploymentDownload first, then change the service.
  4. AcceptanceCheck readiness, version and application behaviour.
  5. Known stateOnly then record the successful release.

The platform matters too. A multi-platform digest can reference several platform variants, so we also record linux/arm64 or linux/amd64. Recovery needs the earlier Compose file and parameters as well. Combining an old image with new configuration creates a third state that nobody may have tested.

A small catalogue makes failures visible

For the exercise, use a Linux test host with Docker Engine, Compose v2, Python 3 and registry access. These procedures were executed with Engine 28.0.1 and Compose 2.33.1 on Linux/ARM64. Put the files in a dedicated working directory and run all subsequent commands there. Ports 18080 and 15000 must be available.

Our service returns three responses: /healthz reports readiness, /version returns the revision baked into the image, and /catalog returns an item priced at 1,990 cents. The site name, “Teamkatalog”, comes from the environment. This lets us distinguish a problem in the artifact from one in its configuration.

First save app.py and catalog.json. Python’s HTTP server keeps the example small and stays on the test host. For a public application, use its regular application server and operating setup; Python’s documentation explains the module’s intended limitations.

import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

REVISION = Path('/app/revision').read_text().strip()
CATALOG = json.loads(Path('/app/catalog.json').read_text())
HEALTH = int(Path('/app/health-status').read_text())


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        routes = {
            '/healthz': (HEALTH, {'ready': HEALTH == 200}),
            '/version': (200, {'revision': REVISION}),
            '/catalog': (200, {'site': os.environ['SITE_NAME'], 'items': CATALOG}),
        }
        status, data = routes.get(self.path, (404, {'error': 'not found'}))
        body = json.dumps(data).encode()
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)


ThreadingHTTPServer(('0.0.0.0', 8080), Handler).serve_forever()
[{"sku": "DX-01", "price_cents": 1990, "available": true}]

This Dockerfile takes an explicit base image and writes the revision into the image during the build. The application therefore reports its baked-in revision rather than echoing an arbitrary runtime environment variable. The additional health parameter will let us exercise a failed startup later.

ARG PYTHON_IMAGE
FROM ${PYTHON_IMAGE}
WORKDIR /app
COPY app.py catalog.json ./
ARG REVISION
ARG HEALTH_STATUS=200
RUN test -n "$REVISION" && printf '%s' "$REVISION" > revision \
    && printf '%s' "$HEALTH_STATUS" > health-status
USER 10001:10001
CMD ["python", "app.py"]

Turn the build tag into a deployment digest

Start a local registry for the exercise. Both the registry and catalogue are reachable only through the loopback address. On a real target, use your existing registry with TLS and its normal access controls. The local exercise needs no credentials.

docker pull python:3.13.13-slim
python_image=$(docker image inspect python:3.13.13-slim --format '{{index .RepoDigests 0}}')
platform=$(docker version --format '{{.Server.Os}}/{{.Server.Arch}}')
docker run -d --name dexor-release-registry \
  -p 127.0.0.1:15000:5000 \
  registry@sha256:d4032d4cc323c1731c707931ecada07a53076eac38e3b61ae57533f170f2c6c3
docker build --platform "$platform" --build-arg PYTHON_IMAGE="$python_image" \
  --build-arg REVISION=r1 -t localhost:15000/dexor-catalog:r1 .
docker push localhost:15000/dexor-catalog:r1

The build receives the pinned base image and revision r1. In a project, you would normally use the Git commit instead of this short exercise label. After the push, Docker can report the registry digest. Retain the image and registry data for as long as you need to recover that release.

Now save this compose.yaml. Deployment deliberately has no build: section. The small resource limits suit this test service; derive limits for your own application from its requirements.

services:
  web:
    image: "${DXD_IMAGE:?Set DXD_IMAGE to an image digest}"
    platform: "${DXD_PLATFORM:?Set DXD_PLATFORM}"
    environment:
      SITE_NAME: "${DXD_SITE_NAME:?Set DXD_SITE_NAME}"
    ports:
      - "127.0.0.1:18080:8080"
    read_only: true
    mem_limit: 128m
    cpus: 0.5
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=1)"]
      interval: 2s
      timeout: 2s
      retries: 5

bundle.py creates a release directory containing the Compose file, parameters and expected revision. It creates a new directory for every release and refuses to overwrite an existing one. The source hash records the example files; in your repository, add the commit and your build evidence.

import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys

revision = sys.argv[1]
tag = 'localhost:15000/dexor-catalog:' + revision
digests = json.loads(subprocess.check_output([
    'docker', 'image', 'inspect', tag, '--format', '{{json .RepoDigests}}'
]))
image = next(d for d in digests if d.startswith('localhost:15000/dexor-catalog@'))
platform = subprocess.check_output([
    'docker', 'version', '--format', '{{.Server.Os}}/{{.Server.Arch}}'
], text=True).strip()
release = Path('releases') / revision
release.mkdir(parents=True)
shutil.copy2('compose.yaml', release / 'compose.yaml')
(release / 'release.env').write_text(
    f'DXD_IMAGE={image}\nDXD_PLATFORM={platform}\nDXD_SITE_NAME=Teamkatalog\n'
)
source_hash = hashlib.sha256(b''.join(
    Path(name).read_bytes() for name in ['Dockerfile', 'app.py', 'catalog.json']
)).hexdigest()
(release / 'expected.json').write_text(json.dumps(dict(
    image=image, revision=revision, platform=platform,
    site='Teamkatalog', source_sha256=source_hash
), indent=2) + '\n')
print(release)
python3 bundle.py r1
cat releases/r1/expected.json

Inspect releases/r1/expected.json: the image digest, platform and site name should match the intended target. Version or archive the complete bundle. A digest alone preserves neither configuration files nor the availability of your registry.

An environment file does not prove the effective configuration

A subtle failure can happen before startup: an exported shell variable takes precedence over an explicit environment file during Compose interpolation. A forgotten terminal or runner setting can override a carefully versioned value. Docker’s documented precedence explains why.

Try this without changing the running service:

DXD_SITE_NAME=FalscherKatalog docker compose \
  --env-file releases/r1/release.env \
  -f releases/r1/compose.yaml config --format json

The resolved model now contains “FalscherKatalog”, meaning the wrong catalogue. --env-file does not prevent this override. A missing required variable behaves differently: our ${DXD_IMAGE:?...} expression fails while resolving the configuration. Silently falling back to latest would be unhelpful here.

The deployment helper removes the three example parameters from its process environment, then compares the resulting image, platform and site name with expected.json. Extend this contract when adding variables. It also records a hash of the resolved model to identify the remaining configuration. Compose config exposes this model for inspection.

The example contains no secrets. Resolved configuration for a real application can include passwords, so inspect what you are about to publish in job logs. Files, secrets and services outside Compose also need to fit your release procedure.

A health check answers one question

The health check requests /healthz inside the container. It tells us whether the service answers that request. Acceptance additionally checks the expected revision and a specific catalogue item from the host. Save smoke.py alongside the other files:

import json
import sys
import urllib.request


def smoke(base, revision, site):
    def get(path):
        with urllib.request.urlopen(base + path, timeout=3) as response:
            return json.load(response)

    if get('/version') != {'revision': revision}:
        raise RuntimeError('Unexpected application revision')
    expected = {'site': site, 'items': [
        {'sku': 'DX-01', 'price_cents': 1990, 'available': True}
    ]}
    if get('/catalog') != expected:
        raise RuntimeError('Catalogue does not match the acceptance case')
    print('Version and catalogue verified')


if __name__ == '__main__':
    smoke(*sys.argv[1:])

For a real application, choose a small but meaningful business operation: a search with a known result, for example, or reading a prepared test record. Tests that write data need their own fixtures and a defined cleanup procedure. A generic HTTP 200 check will catch neither an incorrect price nor an accidentally old application version.

docker compose up --wait waits for services to be running, or healthy when a health check exists. Without a suitable health check, it adds no functional assurance. The wait timeout limits the wait; it does not execute recovery. With several services, appropriate dependency readiness conditions help startup but do not replace acceptance of the complete application.

Make the next deployment repeatable too.

We connect builds, configuration, deployment and acceptance into a procedure your team can operate and improve.

Verify first, then record the successful release

Save deploy.py in the working directory. It uses a fixed project name and stores local evidence under state/. Its file lock prevents two simultaneous invocations on this host, provided both use the same state path. Another environment needs its own project name, port and state path.

import fcntl
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from datetime import datetime, timezone
from smoke import smoke

release = Path(sys.argv[1]).resolve()
project = 'dexor-release-lab'
state = Path('state').resolve()
state.mkdir(exist_ok=True)
environment = os.environ.copy()
for name in ('DXD_IMAGE', 'DXD_PLATFORM', 'DXD_SITE_NAME'):
    environment.pop(name, None)
command = ['docker', 'compose', '-p', project, '--env-file',
           str(release / 'release.env'), '-f', str(release / 'compose.yaml')]


def compose(*arguments, capture=False):
    return subprocess.run(command + list(arguments), env=environment,
                          check=True, text=True, capture_output=capture)


with (state / 'deploy.lock').open('w') as lock:
    fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    expected = json.loads((release / 'expected.json').read_text())
    model = json.loads(compose('config', '--format', 'json', capture=True).stdout)
    web = model['services']['web']
    if (web['image'] != expected['image'] or '@sha256:' not in web['image']
            or web['platform'] != expected['platform']
            or web['environment']['SITE_NAME'] != expected['site']):
        raise RuntimeError('Effective configuration differs from the release')
    model_hash = hashlib.sha256(json.dumps(model, sort_keys=True).encode()).hexdigest()
    compose('pull')
    compose('up', '--no-build', '--wait', '--wait-timeout', '20')
    smoke('http://127.0.0.1:18080', expected['revision'], expected['site'])
    record = dict(expected, project=project, release=str(release),
                  model_sha256=model_hash,
                  verified_at=datetime.now(timezone.utc).isoformat())
    with (state / 'history.jsonl').open('a') as history:
        history.write(json.dumps(record) + '\n')
    temporary = state / 'verified.tmp'
    temporary.write_text(json.dumps(record, indent=2) + '\n')
    temporary.replace(state / 'verified.json')
    print('Verified release recorded in state/verified.json')

The sequence is straightforward: resolve configuration, compare expectations, download the image, update the service and run the functional check. Only then replace verified.json and append a record to history.jsonl. That record means “last successfully accepted release”. After a failed update, something else may already be running.

python3 deploy.py releases/r1
cat state/verified.json

Deploy r1 again. In our exercise, the same container remained because its image and effective configuration were unchanged. This is a useful check for unintended changes, rather than a general guarantee for arbitrary Compose files or external dependencies. Keep release bundles unchanged throughout deployment.

Deliberately deploy the wrong price

Change the price in catalog.json to 9,999 cents and build r2. Leave acceptance unchanged: it still expects the agreed catalogue item.

python3 - <<'PY'
import json
from pathlib import Path
Path('catalog.json').write_text(json.dumps([
    {'sku': 'DX-01', 'price_cents': 9999, 'available': True}
]) + '\n')
PY
python_image=$(docker image inspect python:3.13.13-slim --format '{{index .RepoDigests 0}}')
platform=$(docker version --format '{{.Server.Os}}/{{.Server.Arch}}')
docker build --platform "$platform" --build-arg PYTHON_IMAGE="$python_image" \
  --build-arg REVISION=r2 -t localhost:15000/dexor-catalog:r2 .
docker push localhost:15000/dexor-catalog:r2
python3 bundle.py r2
python3 deploy.py releases/r2

In our execution, Compose reported a healthy container and /version returned r2, but acceptance failed on the catalogue. verified.json still referenced r1. The health check had allowed an incorrect application result through. The extra test exposed precisely that gap.

First identify the running version and the last accepted one. Then deploy the complete earlier release bundle again:

cat state/verified.json
docker ps --filter label=com.docker.compose.project=dexor-release-lab
python3 deploy.py releases/r1
python3 smoke.py http://127.0.0.1:18080 r1 Teamkatalog

Both revision and price were correct after recovery. In a second failure case, a new image’s health endpoint returned HTTP 503. Deployment failed, yet the new container remained. Again, r1 had to be deployed explicitly. A Compose update is not a transaction that automatically returns to its starting state whenever something fails.

We also moved a tag to point at r2: the digest-based release continued running r1. Conversely, an unavailable digest failed at the earlier pull step, leaving the running container untouched. Small counterexamples like these show which parts of a procedure actually protect the service.

Restoring an image does not restore data

The catalogue is stateless, which makes recovery straightforward. A database changes the decision: can the old application still read the updated schema? Has the new version already written data that the old one cannot understand?

An additive migration can initially support both application versions, while removing a column can cut off the return path. Plan incompatible changes separately from a simple image switch. Decide whether recovery means restoring the application, deploying a forward fix or restoring data from a backup.

A restore can lose data created since that backup. Agree on acceptable data loss and interruption before releasing. docker compose down -v is not a rollback procedure: it can remove volumes and their data. Our backup and recovery guide discusses the wider recovery task.

Let GitLab start the same procedure

Once the manual procedure works, the pipeline can call it. This short example assumes a dedicated shell runner on the target host, with Docker, Python and release bundles already transferred to /srv/catalog-deploy/releases/COMMIT. Building and transferring the bundle are existing earlier steps; this job does not rebuild an image in production.

deploy_catalog:
  stage: deploy
  tags: [catalog-deploy]
  resource_group: catalog-production
  environment:
    name: production
  interruptible: false
  rules:
    - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
      when: manual
  script:
    - cd /srv/catalog-deploy
    - python3 deploy.py "releases/$CI_COMMIT_SHA"

resource_group serialises these deployment jobs within the GitLab project. It does not automatically order them by the application version you intend to release. Also enable Prevent outdated deployment jobs in the project settings. GitLab determines age from the job start, not simply the commit date; check how this fits your approval process. Planned recovery should be an explicit deployment request, rather than an accidentally delayed old job.

The local lock remains useful for manual invocations. It does not coordinate across several hosts. Restrict the runner to its intended target access and protected branches, and use your existing secret mechanism for registry authentication. The resource group documentation and GitLab deployment settings describe these separate controls.

Start with the symptom and finish with evidence

SymptomWhat to inspectTargeted next step
Green job, old versionThe running container’s image digest and /version response.Compare the target and release bundle before starting another build.
Configuration differs from the environment fileResolved Compose model and exported parameters.Remove the override; use the same inputs for validation and deployment.
Healthy, but incorrect resultRun a specific acceptance case against the application.Reject the release and inspect the last accepted state.
Update ends in an errorContainer state, health check, logs and actual revision.Establish the current state and execute recovery explicitly.
Recovery will not startRegistry availability, earlier configuration and data compatibility.Retrieve the matching bundle; handle data problems separately.

A short release record is enough for handover: source revision, image digest, platform, configuration revision, target, time, acceptance result and known recovery path. Our record adds the model hash and bundle path. This is an operating record; establish image provenance and trust through your build and approval process as well.

Before adopting the procedure, repeat the exercise with your own acceptance case:

This gives the team a deployment procedure it can follow and inspect. If you then want to standardise hosts, packages and system configuration too, Ansible is the next building block. We can help with deployment automation, Linux and cloud operations, or taking over and improving a specific existing release process.