Skip to content

Docker Compose Validator — Python source

Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""compose-validator — structural checks for a Docker Compose file. Python port
(canonical TS: src/lib/compose-validator.ts; Go twin: cli/compose-validator).
Checks: root/services mappings, per-service image or build, port syntax
("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"), environment shape
(mapping or KEY=value list), volumes lists, depends_on references and
acyclicity — same rules, paths and message texts as the TS contract. Python's
stdlib has no YAML parser, so, like every port in this set, a minimal
hand-rolled one covers the compose subset: block mappings/sequences,
single-line flow collections, quoted and plain scalars, comments.
Anchors/aliases/merge keys, block scalars (| >), multi-line plain scalars and
multi-document streams are outside the subset. Never raises — parse errors
travel in ["error"].
"""

import math
import re


class _YamlError(Exception):
    pass


INT_RE = re.compile(r"[-+]?[0-9]+\Z")
FLOAT_RE = re.compile(r"[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\Z")


def _plain(t):
    """Core-schema resolution of a plain scalar: null/bool/int/float/str."""
    if t in ("", "~", "null", "Null", "NULL"):
        return None
    if t in ("true", "True", "TRUE"):
        return True
    if t in ("false", "False", "FALSE"):
        return False
    if INT_RE.match(t):
        return int(t)
    if FLOAT_RE.match(t):
        return float(t)
    return t


def _quoted(s, i):
    """Quoted scalar at s[i]; returns (value, next index). "..." honors
    \\escapes, '...' doubles the quote."""
    q = s[i]
    i += 1
    out = []
    while i < len(s):
        ch = s[i]
        if q == '"' and ch == "\\":
            nxt = s[i + 1] if i + 1 < len(s) else ""
            out.append({"n": "\n", "t": "\t", "r": "\r"}.get(nxt, nxt))
            i += 2
        elif ch == q:
            if q == "'" and s[i + 1:i + 2] == "'":
                out.append("'")
                i += 2
            else:
                return "".join(out), i + 1
        else:
            out.append(ch)
            i += 1
    raise _YamlError("unterminated quoted scalar")


def _flow(s, i):
    """One flow node at s[i]; returns (value, next index)."""
    while s[i:i + 1] == " ":
        i += 1
    if s[i:i + 1] == "[":
        out, i = [], i + 1
        while True:
            while s[i:i + 1] in (" ",):
                i += 1
            if i >= len(s):
                raise _YamlError("unterminated flow sequence")
            if s[i] == "]":
                return out, i + 1
            v, i = _flow(s, i)
            out.append(v)
            while s[i:i + 1] in (" ", ","):
                i += 1
    if s[i:i + 1] == "{":
        out, i = {}, i + 1
        while True:
            while s[i:i + 1] == " ":
                i += 1
            if i >= len(s):
                raise _YamlError("unterminated flow mapping")
            if s[i] == "}":
                return out, i + 1
            if s[i] in "\"'":
                k, i = _quoted(s, i)
            else:
                j = i
                while j < len(s) and s[j] not in ":,}":
                    j += 1
                if s[j:j + 1] != ":":
                    raise _YamlError("flow mapping entry without a colon")
                k = s[i:j].strip()
                i = j + 1
            while s[i:i + 1] == " ":
                i += 1
            if s[i:i + 1] not in ("", ",", "}"):
                out[k], i = _flow(s, i)
            else:
                out[k] = None
            while s[i:i + 1] in (" ", ","):
                i += 1
    if s[i:i + 1] in "\"'":
        return _quoted(s, i)
    j = i
    while j < len(s) and s[j] not in ",]}":
        j += 1
    return _plain(s[i:j].strip()), j


def _key_split(s):
    """`key: rest` split; None when the line is not a mapping entry. The first
    colon followed by a space (or ending the line) wins; quoted keys first."""
    if s[:1] in "\"'":
        try:
            key, j = _quoted(s, 0)
        except _YamlError:
            return None
        rest = s[j:].lstrip(" ")
        return (key, rest[1:]) if rest[:1] == ":" else None
    for j, ch in enumerate(s):
        if ch == ":" and (j + 1 == len(s) or s[j + 1] == " "):
            return s[:j].rstrip(), s[j + 1:]
    return None


def _content_lines(text):
    """Content lines as (indent, body): blanks, comments, %directives and a
    --- marker dropped; tab indentation rejected."""
    out = []
    for raw in text.split("\n"):
        crlf = raw[:-1] if raw.endswith("\r") else raw
        body = crlf.lstrip(" ").rstrip()
        if body == "" or body.startswith(("#", "%")) or body == "---":
            continue
        indent = len(crlf) - len(crlf.lstrip(" "))
        if "\t" in crlf[:indent]:
            raise _YamlError("tab in indentation")
        out.append((indent, body))
    return out


def _is_item(s):
    return s == "-" or s.startswith("- ")


def _block(ls, i, indent):
    """The node whose first line is ls[i] at the given indent; (value, next)."""
    if _is_item(ls[i][1]):
        out = []
        while i < len(ls) and ls[i][0] == indent and _is_item(ls[i][1]):
            content = ls[i][1][2:]
            if content.strip() == "" or content.lstrip().startswith("#"):
                i += 1
                if i < len(ls) and ls[i][0] > indent:
                    v, i = _block(ls, i, ls[i][0])
                else:
                    v = None
            else:
                ls[i] = (indent + 2, content)
                v, i = _block(ls, i, indent + 2)
            out.append(v)
        return out, i
    if _key_split(ls[i][1]) is None:
        return _inline(ls[i][1]), i + 1
    out = {}
    while (i < len(ls) and ls[i][0] == indent and not _is_item(ls[i][1])
           and _key_split(ls[i][1]) is not None):
        key, rest = _key_split(ls[i][1])
        rest = rest.strip()
        i += 1
        if rest:
            out[key] = _inline(rest)
        elif i < len(ls) and ls[i][0] > indent:
            out[key], i = _block(ls, i, ls[i][0])
        elif i < len(ls) and ls[i][0] == indent and _is_item(ls[i][1]):
            out[key], i = _block(ls, i, indent)
        else:
            out[key] = None
    return out, i


def _inline(rest):
    """The value part of `key: value` — flow, quoted, or plain (comment cut)."""
    if rest[0] in "[{":
        v, j = _flow(rest, 0)
        if rest[j:].strip("# ") != "":
            raise _YamlError("trailing content after flow value")
        return v
    if rest[0] in "\"'":
        v, j = _quoted(rest, 0)
        if rest[j:].strip("# ") != "":
            raise _YamlError("trailing content after quoted value")
        return v
    cut = rest.find(" #")
    return _plain((rest[:cut] if cut >= 0 else rest).strip())


def _parse_yaml(text):
    """The minimal parser: text → tree (dicts keep document order)."""
    ls = _content_lines(text)
    if not ls:
        return None
    v, i = _block(ls, 0, ls[0][0])
    if i != len(ls):
        raise _YamlError("inconsistent indentation")
    return v


def _is_map(v):
    return isinstance(v, dict)


def _js_num(x):
    """JavaScript String(number) for the floats the messages can hit."""
    if not math.isfinite(x):
        return "null"
    if x == int(x) and abs(x) < 1e21:
        return str(int(x))
    return repr(x)


def _ts_str(v):
    """TS String(value) form for depends_on coercion and messages."""
    if v is None:
        return "null"
    if v is True:
        return "true"
    if v is False:
        return "false"
    if isinstance(v, float):
        return _js_num(v)
    if isinstance(v, int):
        return str(v)
    if isinstance(v, str):
        return v
    if isinstance(v, list):
        return ",".join(_ts_str(e) for e in v)
    return "[object Object]"


def _port_issue(entry):
    """One ports entry; an issue string or None. "8080", "80:8080",
    "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass."""
    if isinstance(entry, bool):
        return "port must be a string or integer"
    if isinstance(entry, (int, float)):
        if isinstance(entry, float) and (not math.isfinite(entry) or entry != int(entry)):
            return "port must be a string or integer"
        if entry < 0 or entry > 65535:
            return f"port {_ts_str(entry)} out of range 0-65535"
        return None
    if not isinstance(entry, str):
        return "port must be a string or integer"
    slash = entry.find("/")
    proto = entry[slash + 1:] if slash >= 0 else ""
    if proto not in ("", "tcp", "udp"):
        return f'unknown protocol "{proto}" (use tcp or udp)'
    body = entry if proto == "" else entry[:slash]
    parts = body.split(":")
    if not all(re.fullmatch(r"[0-9]+", p) for p in parts):
        return None
    if len(parts) > 3:
        return "port must have 1-3 colon-separated parts"
    for p in parts:
        if int(p) > 65535:
            return f"port {p} out of range 0-65535"
    return None


def _check(root, out):
    """Walk the document; append issues in TS order (root, services,
    per-service in document order, then depends_on cycle detection)."""
    def push(path, message):
        out.append({"path": path, "message": message})

    if not _is_map(root):
        push("$", "compose root must be a mapping")
        return
    services = root.get("services")
    if not _is_map(services):
        push("$.services", 'missing or invalid "services" mapping')
        return
    ids = list(services)
    if not ids:
        push("$.services", "services must not be empty")
    for sid in ids:
        svc = services[sid]
        at = f"$.services.{sid}"
        if not _is_map(svc):
            push(at, "service must be a mapping")
            continue
        if "image" not in svc and "build" not in svc:
            push(at, "service needs image or build")
        if "ports" in svc:
            ports = svc["ports"]
            if not isinstance(ports, list):
                push(f"{at}.ports", "ports must be a list")
            else:
                for i, p in enumerate(ports):
                    msg = _port_issue(p)
                    if msg:
                        push(f"{at}.ports[{i}]", msg)
        if "environment" in svc:
            env = svc["environment"]
            if _is_map(env):
                for k, v in env.items():
                    if v is not None and not isinstance(v, (str, int, float)):
                        push(f"{at}.environment.{k}", "environment values must be scalars")
            elif isinstance(env, list):
                for i, e in enumerate(env):
                    if not isinstance(e, str) or not re.fullmatch(r"[^=]+=.*", e, re.S):
                        push(f"{at}.environment[{i}]", "list environment entries must look like KEY=value")
            else:
                push(f"{at}.environment", "environment must be a mapping or a list")
        if "volumes" in svc and not isinstance(svc["volumes"], list):
            push(f"{at}.volumes", "volumes must be a list")
        if "depends_on" in svc:
            dep = svc["depends_on"]
            if not isinstance(dep, (str, list)) and not _is_map(dep):
                push(f"{at}.depends_on", "depends_on must be a string, list or mapping")
            else:
                names = (list(dep) if _is_map(dep)
                         else [dep] if isinstance(dep, str)
                         else [_ts_str(e) for e in dep])
                for i, n in enumerate(names):
                    if n not in services:
                        push(f"{at}.depends_on[{i}]", f'unknown service "{n}"')

    # depends_on cycle detection (map-form conditions do not affect the graph).
    color = {}

    def visit(sid, stack):
        c = color.get(sid)
        if c == 2:
            return
        if c == 1:
            chain = stack[stack.index(sid):] + [sid]
            push("$.services", "depends_on cycle: " + " -> ".join(chain))
            return
        color[sid] = 1
        svc = services.get(sid)
        if _is_map(svc) and "depends_on" in svc:
            raw = svc["depends_on"]
            if isinstance(raw, str):
                names = [raw]
            elif isinstance(raw, list):
                names = [e for e in raw if isinstance(e, str)]
            elif _is_map(raw):
                names = list(raw)
            else:
                names = []
            for n in names:
                if n in services:
                    visit(n, stack + [sid])
        color[sid] = 2

    for sid in ids:
        visit(sid, [])


def validate_compose(raw):
    """Validate a Docker Compose file → {valid, issues, error}."""
    if not raw.strip():
        return {"valid": False, "issues": [], "error": "A compose document is required"}
    try:
        root = _parse_yaml(raw)
    except _YamlError as e:
        return {"valid": False, "issues": [], "error": f"Invalid YAML: {e}"}
    issues = []
    _check(root, issues)
    return {"valid": not issues, "issues": issues, "error": None}


# Example:
# validate_compose('services:\n  web:\n    image: nginx:1.25\n    ports:\n      - "8080:80"\n  db:\n    image: postgres:16\n    depends_on: web')["valid"]
# → True
# validate_compose('services:\n  web:\n    image: nginx\n    ports: ["99999"]')["issues"]
# → [{'path': '$.services.web.ports[0]', 'message': 'port 99999 out of range 0-65535'}]
# validate_compose('services:\n  a:\n    image: x\n    depends_on: b\n  b:\n    image: y\n    depends_on: a')["issues"]
# → [{'path': '$.services', 'message': 'depends_on cycle: a -> b -> a'}]

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →