Skip to content

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

// compose-validator — structural checks for a Docker Compose file. Java 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. Java's
// stdlib has no YAML parser, so, like every port in this set, a minimal
// hand-rolled parser 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 throws out of the
// entry point — parse errors travel in Result.error. The document tree keeps
// key order with LinkedHashMap; a final class name need not match this file.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

final class ComposeValidator {

    /** One structural finding at one YAML path (TS ComposeIssue). */
    static final class Issue {
        final String path;
        final String message;
        Issue(String path, String message) { this.path = path; this.message = message; }
    }

    /** TS ComposeValidateResult: error is null unless parsing failed. */
    static final class Result {
        final boolean valid;
        final List<Issue> issues;
        final String error;
        Result(boolean valid, List<Issue> issues, String error) {
            this.valid = valid;
            this.issues = issues;
            this.error = error;
        }
    }

    /** One content line: indent + body (blanks/comments/directives dropped). */
    private static final class Line {
        final int indent;
        final String body;
        Line(int indent, String body) { this.indent = indent; this.body = body; }
    }

    private static boolean intRe(String t) { return t.matches("[-+]?[0-9]+"); }

    private static boolean floatRe(String t) {
        return t.matches("[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?");
    }

    /** Core-schema resolution of a plain scalar: null/bool/Long/Double/String. */
    private static Object plainScalar(String t) {
        switch (t) {
            case "": case "~": case "null": case "Null": case "NULL": return null;
            case "true": case "True": case "TRUE": return Boolean.TRUE;
            case "false": case "False": case "FALSE": return Boolean.FALSE;
            default:
                if (intRe(t)) {
                    try { return Long.parseLong(t); } catch (NumberFormatException e) { return Double.parseDouble(t); }
                }
                if (floatRe(t)) return Double.parseDouble(t);
                return t;
        }
    }

    private static String ltrim(String s) {
        int i = 0;
        while (i < s.length() && s.charAt(i) == ' ') i += 1;
        return s.substring(i);
    }

    private static String rtrim(String s) {
        int e = s.length();
        while (e > 0 && s.charAt(e - 1) == ' ') e -= 1;
        return s.substring(0, e);
    }

    /** Quoted scalar at s[i]; "..." honors escapes, '...' doubles the quote. */
    private static String quotedAt(String s, int i, int[] next) {
        char q = s.charAt(i);
        i += 1;
        StringBuilder out = new StringBuilder();
        while (i < s.length()) {
            char ch = s.charAt(i);
            if (q == '"' && ch == '\\') {
                char nxt = i + 1 < s.length() ? s.charAt(i + 1) : '\0';
                if (nxt == 'n') out.append('\n');
                else if (nxt == 't') out.append('\t');
                else if (nxt == 'r') out.append('\r');
                else out.append(nxt);
                i += 2;
            } else if (ch == q) {
                if (q == '\'' && i + 1 < s.length() && s.charAt(i + 1) == '\'') { out.append('\''); i += 2; }
                else { next[0] = i + 1; return out.toString(); }
            } else { out.append(ch); i += 1; }
        }
        throw new IllegalStateException("Invalid YAML: unterminated quoted scalar");
    }

    /** One flow node at s[i] (spaces already skipped); next[0] = end index. */
    private static Object flowAt(String s, int i, int[] next) {
        while (i < s.length() && s.charAt(i) == ' ') i += 1;
        if (i < s.length() && s.charAt(i) == '[') {
            List<Object> out = new ArrayList<>();
            i += 1;
            for (;;) {
                while (i < s.length() && s.charAt(i) == ' ') i += 1;
                if (i >= s.length()) throw new IllegalStateException("Invalid YAML: unterminated flow sequence");
                if (s.charAt(i) == ']') { next[0] = i + 1; return out; }
                out.add(flowAt(s, i, next));
                i = next[0];
                while (i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == ',')) i += 1;
            }
        }
        if (i < s.length() && s.charAt(i) == '{') {
            Map<String, Object> out = new LinkedHashMap<>();
            i += 1;
            for (;;) {
                while (i < s.length() && s.charAt(i) == ' ') i += 1;
                if (i >= s.length()) throw new IllegalStateException("Invalid YAML: unterminated flow mapping");
                if (s.charAt(i) == '}') { next[0] = i + 1; return out; }
                String k;
                if (s.charAt(i) == '"' || s.charAt(i) == '\'') {
                    k = quotedAt(s, i, next);
                } else {
                    int j = i;
                    while (j < s.length() && ":,}".indexOf(s.charAt(j)) < 0) j += 1;
                    if (j >= s.length() || s.charAt(j) != ':') {
                        throw new IllegalStateException("Invalid YAML: flow mapping entry without a colon");
                    }
                    k = s.substring(i, j).trim();
                    i = j + 1;
                }
                while (i < s.length() && s.charAt(i) == ' ') i += 1;
                Object v = null;
                if (i < s.length() && s.charAt(i) != ',' && s.charAt(i) != '}') { v = flowAt(s, i, next); i = next[0]; }
                out.put(k, v);
                while (i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == ',')) i += 1;
            }
        }
        if (i < s.length() && (s.charAt(i) == '"' || s.charAt(i) == '\'')) return quotedAt(s, i, next);
        int j = i;
        while (j < s.length() && ",]}".indexOf(s.charAt(j)) < 0) j += 1;
        next[0] = j;
        return plainScalar(s.substring(i, j).trim());
    }

    /** `key: rest` split; null when the line is not a mapping entry. */
    private static String[] keySplit(String s) {
        if (!s.isEmpty() && (s.charAt(0) == '"' || s.charAt(0) == '\'')) {
            int[] next = new int[1];
            String key;
            try { key = quotedAt(s, 0, next); } catch (IllegalStateException e) { return null; }
            String rest = ltrim(s.substring(next[0]));
            return rest.startsWith(":") ? new String[]{key, rest.substring(1)} : null;
        }
        for (int j = 0; j < s.length(); j++) {
            if (s.charAt(j) == ':' && (j + 1 == s.length() || s.charAt(j + 1) == ' ')) {
                return new String[]{rtrim(s.substring(0, j)), s.substring(j + 1)};
            }
        }
        return null;
    }

    private static List<Line> contentLines(String text) {
        List<Line> out = new ArrayList<>();
        for (String raw : text.split("\n", -1)) {
            String crlf = raw.endsWith("\r") ? raw.substring(0, raw.length() - 1) : raw;
            String indented = ltrim(crlf);
            int indent = crlf.length() - indented.length();
            String body = rtrim(indented);
            if (body.isEmpty() || body.startsWith("#") || body.startsWith("%") || body.equals("---")) continue;
            if (crlf.substring(0, indent).indexOf('\t') >= 0) {
                throw new IllegalStateException("Invalid YAML: tab in indentation");
            }
            out.add(new Line(indent, body));
        }
        return out;
    }

    private static boolean isItem(String s) { return s.equals("-") || s.startsWith("- "); }

    /** The node whose first line is ls[i] at the given indent; next[0] = next line. */
    private static Object blockAt(List<Line> ls, int i, int indent, int[] next) {
        if (isItem(ls.get(i).body)) {
            List<Object> out = new ArrayList<>();
            while (i < ls.size() && ls.get(i).indent == indent && isItem(ls.get(i).body)) {
                String content = ls.get(i).body.length() > 2 ? ls.get(i).body.substring(2) : "";
                Object v;
                if (content.trim().isEmpty() || ltrim(content).startsWith("#")) {
                    i += 1;
                    if (i < ls.size() && ls.get(i).indent > indent) { v = blockAt(ls, i, ls.get(i).indent, next); i = next[0]; }
                    else v = null;
                } else {
                    ls.set(i, new Line(indent + 2, content));
                    v = blockAt(ls, i, indent + 2, next);
                    i = next[0];
                }
                out.add(v);
            }
            next[0] = i;
            return out;
        }
        if (keySplit(ls.get(i).body) == null) { next[0] = i + 1; return inlineValue(ls.get(i).body); }
        Map<String, Object> out = new LinkedHashMap<>();
        while (i < ls.size() && ls.get(i).indent == indent && !isItem(ls.get(i).body)
               && keySplit(ls.get(i).body) != null) {
            String[] kv = keySplit(ls.get(i).body);
            String key = kv[0];
            String rest = kv[1].trim();
            i += 1;
            if (!rest.isEmpty()) out.put(key, inlineValue(rest));
            else if (i < ls.size() && ls.get(i).indent > indent) { out.put(key, blockAt(ls, i, ls.get(i).indent, next)); i = next[0]; }
            else if (i < ls.size() && ls.get(i).indent == indent && isItem(ls.get(i).body)) {
                out.put(key, blockAt(ls, i, indent, next));
                i = next[0];
            }
            else out.put(key, null);
        }
        next[0] = i;
        return out;
    }

    /** The value part of `key: value` — flow, quoted, or plain (comment cut). */
    private static Object inlineValue(String rest) {
        char c0 = rest.isEmpty() ? '\0' : rest.charAt(0);
        if (c0 == '[' || c0 == '{') {
            Object v = flowAt(rest, 0, new int[1]);
            int[] next = new int[1];
            v = flowAt(rest, 0, next);
            if (!rest.substring(next[0]).replace(" ", "").replace("#", "").isEmpty()) {
                throw new IllegalStateException("Invalid YAML: trailing content after flow value");
            }
            return v;
        }
        if (c0 == '"' || c0 == '\'') {
            int[] next = new int[1];
            String v = quotedAt(rest, 0, next);
            if (!rest.substring(next[0]).replace(" ", "").replace("#", "").isEmpty()) {
                throw new IllegalStateException("Invalid YAML: trailing content after quoted value");
            }
            return v;
        }
        int cut = rest.indexOf(" #");
        return plainScalar(rtrim(cut >= 0 ? rest.substring(0, cut) : rest).trim());
    }

    /** The minimal parser: text → tree (LinkedHashMaps keep document order). */
    private static Object parseYaml(String text) {
        List<Line> ls = contentLines(text);
        if (ls.isEmpty()) return null;
        int[] next = new int[1];
        Object v = blockAt(ls, 0, ls.get(0).indent, next);
        if (next[0] != ls.size()) throw new IllegalStateException("Invalid YAML: inconsistent indentation");
        return v;
    }

    /** JavaScript String(number) for the values the messages can hit. */
    private static String numStr(Object v) {
        if (v instanceof Long) return v.toString();
        double d = (Double) v;
        if (!Double.isFinite(d)) return "null";
        if (d == Math.rint(d) && Math.abs(d) < 1e21) return String.valueOf((long) d);
        return String.valueOf(d);
    }

    /** TS String(value) form for depends_on coercion and messages. */
    private static String tsStr(Object v) {
        if (v == null) return "null";
        if (v instanceof Boolean) return v.toString();
        if (v instanceof Long || v instanceof Double) return numStr(v);
        if (v instanceof String) return (String) v;
        if (v instanceof List) {
            StringBuilder b = new StringBuilder();
            for (Object e : (List<?>) v) {
                if (b.length() > 0) b.append(',');
                b.append(tsStr(e));
            }
            return b.toString();
        }
        return "[object Object]";
    }

    /** One ports entry; an issue string or null. "8080", "80:8080",
     * "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass. */
    static String portIssue(Object entry) {
        if (entry instanceof Long) {
            long n = (Long) entry;
            if (n < 0 || n > 65535) return "port " + n + " out of range 0-65535";
            return null;
        }
        if (entry instanceof Double) {
            double d = (Double) entry;
            if (!Double.isFinite(d) || d != Math.rint(d)) return "port must be a string or integer";
            if (d < 0 || d > 65535) return "port " + numStr(entry) + " out of range 0-65535";
            return null;
        }
        if (entry instanceof String) {
            String s = (String) entry;
            int slash = s.indexOf('/');
            String proto = slash >= 0 ? s.substring(slash + 1) : "";
            if (!proto.isEmpty() && !proto.equals("tcp") && !proto.equals("udp")) {
                return "unknown protocol \"" + proto + "\" (use tcp or udp)";
            }
            String body = proto.isEmpty() ? s : s.substring(0, slash);
            String[] parts = body.split(":");
            // Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
            for (String p : parts) if (!p.matches("[0-9]+")) return null;
            if (parts.length > 3) return "port must have 1-3 colon-separated parts";
            for (String p : parts) {
                double n = Double.parseDouble(p);
                if (n < 0 || n > 65535) return "port " + p + " out of range 0-65535";
            }
            return null;
        }
        return "port must be a string or integer"; // Boolean, null, maps, lists
    }

    /** Walk the document; append issues in TS order (root, services,
     * per-service in document order, then depends_on cycle detection). */
    @SuppressWarnings("unchecked")
    static void check(Object root, List<Issue> out) {
        if (!(root instanceof Map)) { out.add(new Issue("$", "compose root must be a mapping")); return; }
        Object servicesObj = ((Map<String, Object>) root).get("services");
        if (!(servicesObj instanceof Map)) {
            out.add(new Issue("$.services", "missing or invalid \"services\" mapping"));
            return;
        }
        Map<String, Object> services = (Map<String, Object>) servicesObj;
        List<String> ids = new ArrayList<>(services.keySet());
        if (ids.isEmpty()) out.add(new Issue("$.services", "services must not be empty"));
        for (String id : ids) {
            Object svcObj = services.get(id);
            String at = "$.services." + id;
            if (!(svcObj instanceof Map)) { out.add(new Issue(at, "service must be a mapping")); continue; }
            Map<String, Object> svc = (Map<String, Object>) svcObj;
            if (!svc.containsKey("image") && !svc.containsKey("build")) {
                out.add(new Issue(at, "service needs image or build"));
            }
            if (svc.containsKey("ports")) {
                Object ports = svc.get("ports");
                if (!(ports instanceof List)) out.add(new Issue(at + ".ports", "ports must be a list"));
                else {
                    List<?> items = (List<?>) ports;
                    for (int i = 0; i < items.size(); i++) {
                        String msg = portIssue(items.get(i));
                        if (msg != null) out.add(new Issue(at + ".ports[" + i + "]", msg));
                    }
                }
            }
            if (svc.containsKey("environment")) {
                Object env = svc.get("environment");
                if (env instanceof Map) {
                    for (Map.Entry<String, Object> e : ((Map<String, Object>) env).entrySet()) {
                        Object v = e.getValue();
                        if (v != null && !(v instanceof String) && !(v instanceof Boolean)
                            && !(v instanceof Long) && !(v instanceof Double)) {
                            out.add(new Issue(at + ".environment." + e.getKey(), "environment values must be scalars"));
                        }
                    }
                } else if (env instanceof List) {
                    List<?> items = (List<?>) env;
                    for (int i = 0; i < items.size(); i++) {
                        Object e = items.get(i);
                        if (!(e instanceof String) || !((String) e).matches("(?s)[^=]+=.*")) {
                            out.add(new Issue(at + ".environment[" + i + "]",
                                "list environment entries must look like KEY=value"));
                        }
                    }
                } else out.add(new Issue(at + ".environment", "environment must be a mapping or a list"));
            }
            if (svc.containsKey("volumes") && !(svc.get("volumes") instanceof List)) {
                out.add(new Issue(at + ".volumes", "volumes must be a list"));
            }
            if (svc.containsKey("depends_on")) {
                Object dep = svc.get("depends_on");
                if (!(dep instanceof List) && !(dep instanceof String) && !(dep instanceof Map)) {
                    out.add(new Issue(at + ".depends_on", "depends_on must be a string, list or mapping"));
                } else {
                    List<String> names = new ArrayList<>();
                    if (dep instanceof Map) names.addAll(((Map<String, Object>) dep).keySet());
                    else if (dep instanceof List) for (Object e : (List<?>) dep) names.add(tsStr(e));
                    else names.add((String) dep);
                    for (int i = 0; i < names.size(); i++) {
                        if (!services.containsKey(names.get(i))) {
                            out.add(new Issue(at + ".depends_on[" + i + "]", "unknown service \"" + names.get(i) + "\""));
                        }
                    }
                }
            }
        }
        // depends_on cycle detection (map-form conditions do not affect the graph).
        Map<String, Integer> color = new HashMap<>();
        for (String id : ids) visit(services, id, new ArrayList<>(), color, out);
    }

    @SuppressWarnings("unchecked")
    private static void visit(Map<String, Object> services, String sid, List<String> stack,
                              Map<String, Integer> color, List<Issue> out) {
        Integer c = color.get(sid);
        if (c != null && c == 2) return;
        if (c != null && c == 1) {
            List<String> chain = new ArrayList<>(stack.subList(stack.indexOf(sid), stack.size()));
            chain.add(sid);
            out.add(new Issue("$.services", "depends_on cycle: " + String.join(" -> ", chain)));
            return;
        }
        color.put(sid, 1);
        Object svc = services.get(sid);
        if (svc instanceof Map && ((Map<String, Object>) svc).containsKey("depends_on")) {
            Object raw = ((Map<String, Object>) svc).get("depends_on");
            List<String> names = new ArrayList<>();
            if (raw instanceof String) names.add((String) raw);
            else if (raw instanceof List) {
                for (Object e : (List<?>) raw) if (e instanceof String) names.add((String) e);
            } else if (raw instanceof Map) names.addAll(((Map<String, Object>) raw).keySet());
            for (String n : names) {
                if (services.containsKey(n)) {
                    List<String> next = new ArrayList<>(stack);
                    next.add(sid);
                    visit(services, n, next, color, out);
                }
            }
        }
        color.put(sid, 2);
    }

    /** Validate a Docker Compose file. */
    static Result validateCompose(String raw) {
        if (raw.trim().isEmpty()) {
            return new Result(false, new ArrayList<>(), "A compose document is required");
        }
        Object root;
        try {
            root = parseYaml(raw);
        } catch (IllegalStateException e) {
            return new Result(false, new ArrayList<>(), e.getMessage());
        }
        List<Issue> issues = new ArrayList<>();
        check(root, issues);
        return issues.isEmpty() ? new Result(true, new ArrayList<>(), null) : new Result(false, issues, null);
    }

    public static void main(String[] args) {
        Result ok = validateCompose("services:\n  web:\n    image: nginx:1.25\n    ports:\n      - \"8080:80\"\n      - 6053:53/udp\n  db:\n    image: postgres:16\n    depends_on: web");
        System.out.println("valid: " + ok.valid); // valid: true
        Result bad = validateCompose("services:\n  web:\n    image: nginx\n    ports: [\"99999\"]");
        for (Issue i : bad.issues) System.out.println(i.path + ": " + i.message);
        System.out.println(validateCompose("services:\n  a:\n    image: x\n    depends_on: b\n  b:\n    image: y\n    depends_on: a").issues.get(0).message);
        System.out.println(validateCompose("   ").error); // A compose document is required
    }
}

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 →