How to fix yaml: line X: mapping values are not allowed in this context in Docker

DockerBEGINNERMEDIUMUpdated Dec 6, 2025· 521 views

The 'mapping values are not allowed in this context' error occurs when Docker Compose fails to parse your YAML file due to indentation issues, tabs instead of spaces, missing spaces after colons, or hidden Unicode characters. This is one of the most common YAML syntax errors.

Quick fix

Fixes yaml: line X: mapping values are not allowed in this context

# Show lines around the error (replace 5 with your error line number)
sed -n '3,7p' docker-compose.yml
  1. Identify the problematic line
  2. Check for tabs vs spaces
  3. Add missing space after colons
  4. Fix indentation alignment
docker — error
# Show lines around the error (replace 5 with your error line number)
sed -n '3,7p' docker-compose.yml
yaml: line X: mapping values are not allowed in this context

What this error means

The "yaml: line X: mapping values are not allowed in this context" error is a YAML parsing error that indicates the parser encountered a colon (`:`) in an unexpected location. In YAML, colons define key-value mappings, and the parser found one where it wasn't syntactically valid. This error almost always stems from whitespace problems. YAML is extremely sensitive to indentation - unlike JSON or XML, whitespace is part of the syntax. The error message tells you the line number where parsing failed, but the actual problem is often on the previous line or involves invisible characters. Common scenarios that trigger this error: 1. **Mixed tabs and spaces**: YAML requires spaces for indentation. A single tab character will cause this error. 2. **Missing space after colon**: Key-value pairs require a space after the colon (`key: value`, not `key:value`). 3. **Inconsistent indentation**: All items at the same level must have identical indentation. 4. **Copy-paste artifacts**: Text copied from websites or PDFs often contains hidden Unicode characters like "smart quotes" or non-breaking spaces. The YAML parser reads your file line by line, building a tree structure based on indentation. When it encounters something that breaks this structure - like a colon appearing where it expects a value - it reports this error.

Typical symptoms

  • Running `docker-compose up` or `docker compose up` shows 'mapping values are not allowed in this context'
  • The error includes a specific line number like 'yaml: line 5:'
  • Docker Compose fails immediately without starting any services
  • The YAML file works after retyping sections manually
  • Error appears after copying docker-compose.yml content from a website or documentation
  • File validates on some YAML validators but Docker Compose still rejects it
  • CI/CD pipeline fails with YAML parsing errors

Common causes

  1. Using tab characters instead of spaces for indentation (most common cause)
  2. Missing space after a colon in a key-value pair (e.g., `image:nginx` instead of `image: nginx`)
  3. Inconsistent indentation levels (mixing 2-space and 4-space indentation)
  4. Hidden Unicode characters from copy-paste (smart quotes, en-dashes, non-breaking spaces)
  5. Incorrect indentation after a multiline value or block scalar
  6. Colons in unquoted string values (e.g., `command: echo: hello` instead of `command: "echo: hello"`)
  7. Wrong nesting level for a key (item indented too much or too little)

How to fix "yaml: line X: mapping values are not allowed in this context"

1Identify the problematic line

The error message includes a line number. Start by examining that line and the line before it:

bash
# Show lines around the error (replace 5 with your error line number)
sed -n '3,7p' docker-compose.yml

Important: The actual issue is often on the line before the reported line number. The parser reports where it detected the problem, not necessarily where the mistake is.

Look for:
- Missing spaces after colons
- Keys that look misaligned
- Values that contain colons without quotes

2Check for tabs vs spaces

YAML requires spaces for indentation - tabs are not allowed. Check if your file contains tabs:

bash
# Show tabs as ^I characters
cat -A docker-compose.yml

If you see ^I characters, those are tabs that need to be converted to spaces.

Convert tabs to spaces:

bash
# Using sed (creates backup)
sed -i.bak 's/\t/  /g' docker-compose.yml

# Using expand
expand -t 2 docker-compose.yml > docker-compose.yml.fixed
mv docker-compose.yml.fixed docker-compose.yml

Configure your editor to use spaces:

- VS Code: Add to settings.json:

json
"[yaml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2
  }

- Vim: Add to .vimrc:

bash
autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab
3Add missing space after colons

Every key-value pair in YAML needs a space after the colon. This is wrong:

yaml
# WRONG - no space after colon
services:
  web:
    image:nginx
    ports:
      -"8080:80"

This is correct:

yaml
# CORRECT - space after each colon
services:
  web:
    image: nginx
    ports:
      - "8080:80"

Search for missing spaces:

bash
# Find lines with colon immediately followed by non-space/newline
grep -n ':[^ $]' docker-compose.yml | grep -v '://'

The grep -v '://' excludes URLs which legitimately have colons without spaces.

4Fix indentation alignment

All keys at the same level must have identical indentation. Check your file structure:

yaml
# WRONG - inconsistent indentation
services:
  web:
    image: nginx
     ports:        # Extra space!
      - "8080:80"
yaml
# CORRECT - consistent 2-space indentation
services:
  web:
    image: nginx
    ports:
      - "8080:80"

Use a visual approach to check alignment:

bash
# Show line numbers and content
cat -n docker-compose.yml

Or use your editor's "show whitespace" feature to visualize indentation levels.

Standard Docker Compose indentation:
- Top-level keys (services:, networks:, volumes:): 0 spaces
- Service names: 2 spaces
- Service properties (image:, ports:): 4 spaces
- Nested values: 6+ spaces

5Remove hidden Unicode characters

Copy-pasting from websites or PDFs often introduces invisible Unicode characters that break YAML parsing:

- Smart quotes: "text" or 'text' instead of "text" or 'text'
- En-dash: - (U+2013) instead of - (hyphen U+002D)
- Non-breaking spaces: (U+00A0) instead of regular space

Find problematic characters:

bash
# Show non-ASCII characters with line numbers
grep -nP '[^\x00-\x7F]' docker-compose.yml

# Or use hexdump to see byte values
hexdump -C docker-compose.yml | head -50

Fix by retyping or using sed:

bash
# Replace common smart quotes with regular quotes
sed -i "s/[""]/"/g" docker-compose.yml
sed -i "s/['']/'/g" docker-compose.yml

# Alternative: remove all non-ASCII characters
LC_ALL=C tr -cd '[:print:][:space:]' < docker-compose.yml > docker-compose.yml.clean
mv docker-compose.yml.clean docker-compose.yml

Best practice: Manually retype the section around the error line rather than trying to find invisible characters.

6Quote strings containing colons

If a value contains a colon, it must be quoted to prevent YAML from interpreting it as a nested mapping:

yaml
# WRONG - colon in value causes parsing error
services:
  web:
    command: flask run --host=0.0.0.0:5000

# CORRECT - quoted string
services:
  web:
    command: "flask run --host=0.0.0.0:5000"

Common places where this matters:

yaml
# Environment variables with values containing colons
environment:
  - "DATABASE_URL=postgres://user:pass@host:5432/db"

# Commands with port mappings
command: ["python", "-m", "http.server", "8000:8000"]

# Labels with colons
labels:
  - "traefik.http.routers.web.rule=Host(`example.com`)"

When in doubt, quote string values that contain special characters like :, #, [, ], {, }.

7Validate with yamllint

Use yamllint for detailed YAML validation with better error messages:

bash
# Install yamllint
pip install yamllint

# Or on Ubuntu/Debian
sudo apt-get install yamllint

# Run validation
yamllint docker-compose.yml

yamllint provides specific warnings about:
- Line length
- Trailing spaces
- Missing document start (---)
- Truthy values
- Indentation style

Online validators:
- https://www.yamllint.com/
- https://yamlchecker.com/

Note: A file can pass generic YAML validation but still fail Docker Compose validation. After yamllint passes, also run:

bash
# Docker Compose config validation
docker compose config

This validates both YAML syntax and Docker Compose schema.

8Use docker compose config to validate

Docker Compose has a built-in validation command that parses your file and outputs the resolved configuration:

bash
# Validate and show resolved config
docker compose config

# Just validate, don't output
docker compose config --quiet

If successful, this command outputs the fully resolved docker-compose.yml (with all variables substituted and defaults applied). If there's an error, it shows detailed information about what went wrong.

This is more thorough than generic YAML validators because it also checks:
- Service configuration validity
- Volume mount syntax
- Network configuration
- Environment variable substitution

Tip: If the error persists, try creating a minimal docker-compose.yml and adding sections back one at a time:

yaml
# Start with bare minimum
services:
  test:
    image: alpine
    command: echo "test"

Run docker compose config after each addition to isolate which section causes the error.

Advanced notes

### Understanding YAML Indentation Rules

YAML uses indentation to represent structure (like Python). Key rules:

1. Only spaces allowed: Tabs are never valid for indentation
2. Consistent indentation: Pick 2 or 4 spaces and stick with it
3. Relative indentation matters: Child elements must be indented more than parents
4. Sibling alignment: Items at the same level must have identical indentation

### The "Context" in the Error Message

"Mapping values are not allowed in this context" means the parser found a colon (:) where it was building something other than a mapping. Contexts where mappings aren't allowed:

- Inside a plain scalar (unquoted string)
- After a sequence indicator (-) without proper spacing
- When indentation suggests you're continuing a previous value

### Editor Configuration for YAML

Configure your editor to prevent these issues:

VS Code settings.json:

json
{
  "[yaml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": "keep",
    "editor.formatOnSave": false
  },
  "yaml.validate": true,
  "yaml.schemaStore.enable": true
}

Consider installing the "YAML" extension by Red Hat for enhanced validation.

### Common Docker Compose YAML Pitfalls

Environment variables:

yaml
# WRONG - YAML interprets this as key:value
environment:
  DEBUG: true    # Becomes string "true" - might not be what you want
  PORT: 3000     # Becomes integer 3000

# BETTER - explicit strings
environment:
  DEBUG: "true"
  PORT: "3000"

# BEST - list format (unambiguous)
environment:
  - DEBUG=true
  - PORT=3000

Multi-line commands:

yaml
# WRONG - bare colon in unquoted string
command: python manage.py runserver 0.0.0.0:8000

# CORRECT - quoted
command: "python manage.py runserver 0.0.0.0:8000"

# ALSO CORRECT - using list format
command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]

### Debugging Strategy

When you can't find the issue:

1. Start with a minimal working docker-compose.yml
2. Add sections from your broken file one at a time
3. Run docker compose config after each addition
4. When it breaks, you've found the problematic section
5. Examine that section character by character

This binary search approach is faster than staring at a large file looking for invisible characters.

Frequently asked questions

What does "yaml: line X: mapping values are not allowed in this context" mean?
The "yaml: line X: mapping values are not allowed in this context" error is a YAML parsing error that indicates the parser encountered a colon (:) in an unexpected location. In YAML, colons define key-value mappings, and the parser found one where it wasn't syntactically valid. This error almost always stems from whitespace problems.
How do I fix "yaml: line X: mapping values are not allowed in this context"?
The 'mapping values are not allowed in this context' error occurs when Docker Compose fails to parse your YAML file due to indentation issues, tabs instead of spaces, missing spaces after colons, or hidden Unicode characters. This is one of the most common YAML syntax errors.
What causes "yaml: line X: mapping values are not allowed in this context"?
Using tab characters instead of spaces for indentation (most common cause) Missing space after a colon in a key-value pair (e.g., image:nginx instead of image: nginx) Inconsistent indentation levels (mixing 2-space and 4-space indentation)
Is the "yaml: line X: mapping values are not allowed in this context" error serious?
It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading