Skip to content

Docker Compose Validator — TypeScript 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 TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the Docker Compose Validator (slug: compose-validator).
// Parses a compose file and checks structural rules: services mapping with
// image or build, port syntax, environment shape (map or K=V list),
// volumes lists, depends_on references and acyclicity. The rules and
// message texts are the contract a Go CLI twin must reproduce (Go side:
// yaml.v3). Not checked (by design, documented): image tag validity, build
// context paths, top-level version field semantics, profiles, extensions.
import { parse } from 'yaml';

export interface ComposeIssue {
  path: string;
  message: string;
}

export type ComposeValidateResult =
  | { valid: true; issues: []; error: null }
  | { valid: false; issues: ComposeIssue[]; error: null }
  | { valid: false; issues: []; error: string };

type Node = null | boolean | number | string | Node[] | { [k: string]: Node };

function isMap(v: Node | undefined): v is { [k: string]: Node } {
  return v !== null && typeof v === 'object' && !Array.isArray(v);
}

/** Port entries: "8080", "80:8080", "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp". */
function portIssue(entry: Node): string | null {
  if (typeof entry === 'number') {
    if (!Number.isInteger(entry)) return 'port must be a string or integer';
    if (entry < 0 || entry > 65535) return `port ${entry} out of range 0-65535`;
    return null;
  }
  if (typeof entry !== 'string') return 'port must be a string or integer';
  const proto = entry.includes('/') ? entry.slice(entry.indexOf('/') + 1) : '';
  if (proto && proto !== 'tcp' && proto !== 'udp') return `unknown protocol "${proto}" (use tcp or udp)`;
  const body = proto ? entry.slice(0, entry.indexOf('/')) : entry;
  const parts = body.split(':');
  // Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
  if (!parts.every((p) => /^\d+$/.test(p))) return null;
  if (parts.length < 1 || parts.length > 3) return 'port must have 1-3 colon-separated parts';
  for (const p of parts) {
    const n = Number(p);
    if (n < 0 || n > 65535) return `port ${p} out of range 0-65535`;
  }
  return null;
}

function check(root: Node, out: ComposeIssue[]): void {
  if (!isMap(root)) {
    out.push({ path: '$', message: 'compose root must be a mapping' });
    return;
  }
  const services = root.services;
  if (!isMap(services)) {
    out.push({ path: '$.services', message: 'missing or invalid "services" mapping' });
    return;
  }
  const ids = Object.keys(services);
  if (ids.length === 0) out.push({ path: '$.services', message: 'services must not be empty' });

  for (const id of ids) {
    const svc = services[id];
    const at = `$.services.${id}`;
    if (!isMap(svc)) {
      out.push({ path: at, message: 'service must be a mapping' });
      continue;
    }
    if (svc.image === undefined && svc.build === undefined) {
      out.push({ path: at, message: 'service needs image or build' });
    }
    if (svc.ports !== undefined) {
      if (!Array.isArray(svc.ports)) {
        out.push({ path: `${at}.ports`, message: 'ports must be a list' });
      } else {
        svc.ports.forEach((p, i) => {
          const msg = portIssue(p);
          if (msg) out.push({ path: `${at}.ports[${i}]`, message: msg });
        });
      }
    }
    if (svc.environment !== undefined) {
      const env = svc.environment;
      if (isMap(env)) {
        for (const [k, v] of Object.entries(env)) {
          if (v !== null && typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {
            out.push({ path: `${at}.environment.${k}`, message: 'environment values must be scalars' });
          }
        }
      } else if (Array.isArray(env)) {
        env.forEach((e, i) => {
          if (typeof e !== 'string' || !/^[^=]+=.*/.test(e)) {
            out.push({ path: `${at}.environment[${i}]`, message: 'list environment entries must look like KEY=value' });
          }
        });
      } else {
        out.push({ path: `${at}.environment`, message: 'environment must be a mapping or a list' });
      }
    }
    if (svc.volumes !== undefined && !Array.isArray(svc.volumes)) {
      out.push({ path: `${at}.volumes`, message: 'volumes must be a list' });
    }
    if (svc.depends_on !== undefined) {
      const deps = Array.isArray(svc.depends_on) ? svc.depends_on : [svc.depends_on];
      if (!Array.isArray(svc.depends_on) && typeof svc.depends_on !== 'string' && !isMap(svc.depends_on)) {
        out.push({ path: `${at}.depends_on`, message: 'depends_on must be a string, list or mapping' });
      } else {
        const names = isMap(svc.depends_on) ? Object.keys(svc.depends_on) : deps.map(String);
        names.forEach((n, i) => {
          if (!(n in services)) out.push({ path: `${at}.depends_on[${i}]`, message: `unknown service "${n}"` });
        });
      }
    }
  }

  // depends_on cycle detection (map-form conditions do not affect the graph).
  const color = new Map<string, 1 | 2>();
  const visit = (id: string, stack: string[]): void => {
    if (color.get(id) === 2) return;
    if (color.get(id) === 1) {
      const from = stack.indexOf(id);
      out.push({ path: '$.services', message: `depends_on cycle: ${stack.slice(from).concat(id).join(' -> ')}` });
      return;
    }
    color.set(id, 1);
    const svc = services[id];
    if (isMap(svc) && svc.depends_on !== undefined) {
      const raw = svc.depends_on;
      const names = typeof raw === 'string' ? [raw] : Array.isArray(raw) ? raw : isMap(raw) ? Object.keys(raw) : [];
      for (const n of names) if (typeof n === 'string' && n in services) visit(n, [...stack, id]);
    }
    color.set(id, 2);
  };
  for (const id of ids) visit(id, []);
}

/** Validate a Docker Compose file. */
export function validateCompose(raw: string): ComposeValidateResult {
  if (!raw.trim()) return { valid: false, issues: [], error: 'A compose document is required' };
  let root: Node;
  try {
    root = parse(raw, { merge: true }) as Node;
  } catch (e) {
    return { valid: false, issues: [], error: e instanceof Error ? e.message : 'Invalid YAML' };
  }
  const issues: ComposeIssue[] = [];
  check(root, issues);
  return issues.length === 0
    ? { valid: true, issues: [], error: null }
    : { valid: false, issues, error: null };
}

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 →