DevToolBoxFREE
BlogAdvertise

Validación YAML Docker Compose: 10 errores de sintaxis comunes y cómo corregirlos

9 min de lecturapor DevToolBox

Los archivos YAML de Docker Compose parecen sencillos — hasta que fallan. Un espacio mal colocado, indentación incorrecta o un carácter especial sin comillas genera errores crípticos. Aquí están los 10 errores más comunes y cómo corregirlos.

Valida tu YAML con nuestro convertidor JSON-YAML →

Error 1: Tabulaciones en lugar de espacios

Mensaje de error:

yaml: line 5: found a tab character where an indentation space is expected

Problema: YAML prohíbe estrictamente tabulaciones para indentación.

Solución: Reemplazar todas las tabulaciones por espacios (2 por nivel).

# BAD (tabs - invisible but breaks YAML)
services:
	web:
		image: nginx

# GOOD (2 spaces)
services:
  web:
    image: nginx

Consejo de editor: Activar "Render Whitespace" en el editor.

Error 2: Indentación inconsistente

Mensaje de error:

yaml: line 8: mapping values are not allowed in this context

Problema: Mezcla de niveles (2 espacios aquí, 4 allí).

# BAD (inconsistent: 2 spaces then 4 spaces)
services:
  web:
      image: nginx     # 4 spaces - inconsistent!
      ports:
        - "80:80"

# GOOD (consistent 2 spaces)
services:
  web:
    image: nginx       # 2 spaces - consistent
    ports:
      - "80:80"

Error 3: Caracteres especiales sin comillas

Mensaje de error:

yaml: line 6: did not find expected key

Problema: YAML interpreta dos puntos, almohadillas y llaves de forma especial. Hay que ponerlos entre comillas.

# BAD
services:
  web:
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/mydb  # colon in value!
      - APP_TITLE=My App: The Best                       # colon in value!

# GOOD (quote values with special characters)
services:
  web:
    environment:
      - "DATABASE_URL=postgres://user:pass@db:5432/mydb"
      - "APP_TITLE=My App: The Best"

Caracteres que requieren comillas: : { } [ ] , & * # ? | - < > = ! % @

Error 4: Formato de mapeo de puertos incorrecto

Mensaje de error:

services.web.ports contains an invalid type, it should be a number, or an object

Problema: YAML puede interpretar 80:80 como base-60 sin comillas.

# RISKY (YAML may interpret as base-60)
services:
  web:
    ports:
      - 80:80        # Works but risky
      - 5432:5432    # May cause issues

# SAFE (always quote port mappings)
services:
  web:
    ports:
      - "80:80"
      - "5432:5432"
      - "127.0.0.1:3000:3000"

Error 5: Clave version ausente o incorrecta

Mensaje de error:

(root) Additional property version is not allowed

Problema: Docker Compose v2 ya no requiere la clave version.

# OUTDATED (Docker Compose v1 format)
version: "3.8"
services:
  web:
    image: nginx

# CURRENT (Docker Compose v2 - no version needed)
services:
  web:
    image: nginx

Con docker compose (v2): eliminar version. Con docker-compose (v1): mantenerla.

Error 6: Variables de entorno mapping vs lista

Mensaje de error:

services.web.environment must be a mapping or an array

Problema: Mezcla de sintaxis mapping y lista para variables de entorno.

# Format A: List (with dashes)
services:
  web:
    environment:
      - NODE_ENV=production
      - PORT=3000

# Format B: Mapping (key: value)
services:
  web:
    environment:
      NODE_ENV: production
      PORT: 3000

# BAD: Mixing both formats
services:
  web:
    environment:
      NODE_ENV: production
      - PORT=3000          # ERROR: mixing formats!

Error 7: Valores booleanos sin comillas

Mensaje de error: Sin error visible, comportamiento inesperado.

Problema: YAML interpreta yes, no, true, false, on, off como booleanos.

# BAD (YAML converts to boolean true/false)
services:
  web:
    environment:
      FEATURE_FLAG: yes       # becomes boolean true, not string "yes"
      DEBUG: on               # becomes boolean true
      COUNTRY: NO             # becomes boolean false (Norway code!)

# GOOD (quote string values)
services:
  web:
    environment:
      FEATURE_FLAG: "yes"
      DEBUG: "on"
      COUNTRY: "NO"

Error 8: Claves duplicadas

Mensaje de error: A menudo sin error — el segundo valor sobrescribe al primero.

# BAD (duplicate 'ports' key - second one silently wins)
services:
  web:
    image: nginx
    ports:
      - "80:80"
    environment:
      - NODE_ENV=production
    ports:                    # DUPLICATE! This replaces the first ports
      - "443:443"

# GOOD (combine under single key)
services:
  web:
    image: nginx
    ports:
      - "80:80"
      - "443:443"
    environment:
      - NODE_ENV=production

Error 9: Rutas de volúmenes

Mensaje de error:

services.web.volumes contains an invalid type

Problema: Rutas Windows con barras invertidas requieren comillas.

# BAD (Windows paths without quotes)
services:
  web:
    volumes:
      - C:\Users\me\app:/app     # Backslashes cause issues

# GOOD (use forward slashes or quotes)
services:
  web:
    volumes:
      - "./app:/app"
      - "/home/user/data:/data"
      - "C:/Users/me/app:/app"      # Forward slashes on Windows

Error 10: Anclas YAML usadas incorrectamente

Mensaje de error:

yaml: unknown anchor 'common'

Problema: Referenciar ancla (*nombre) antes de definirla (&nombre).

# BAD (reference before definition)
services:
  web:
    <<: *common          # ERROR: 'common' not defined yet

x-common: &common
  restart: always

# GOOD (define anchor first, then reference)
x-common: &common
  restart: always
  logging:
    driver: json-file

services:
  web:
    <<: *common
    image: nginx
  api:
    <<: *common
    image: node:20

Lista de validación rápida

Antes de docker compose up, verifica:

  1. Ejecuta docker compose config para validar sintaxis
  2. Comprueba tabulaciones: grep -P '\t' docker-compose.yml
  3. Pon comillas a todos los mapeos de puertos
  4. Sin claves duplicadas al mismo nivel
  5. Pon comillas a valores con caracteres especiales
  6. Indentación consistente (2 espacios)

Valida tu YAML con nuestro convertidor JSON-YAML →

Formatear salida JSON de "docker compose config" →

Preguntas frecuentes

¿Cómo validar un archivo Docker Compose antes de ejecutarlo?

Ejecuta "docker compose config" para validar y mostrar la configuración resuelta.

¿Por qué "service must be a mapping"?

La sección services no está estructurada correctamente como mapping YAML. Causas comunes: indentación faltante.

¿Tabulaciones o espacios en archivos YAML Docker Compose?

Siempre espacios. YAML no permite tabulaciones para indentación. Configura el editor para insertar 2 espacios con Tab.

¿Fue útil?

Stay Updated

Get weekly dev tips and new tool announcements.

No spam. Unsubscribe anytime.

Partner Picks

Sponsor this article

Place your product next to this developer topic with tracked clicks.

Ask about article sponsorship

This site uses cookies for analytics and to display ads. By continuing to browse, you agree. Privacy Policy