How to fix ERROR: yaml.parser.ParserError: while parsing a block mapping in Docker

DockerBEGINNERLOWUpdated Dec 6, 2025· 343 views

The 'yaml.parser.ParserError: while parsing a block mapping' error occurs when Docker Compose encounters invalid YAML syntax, typically due to incorrect indentation, tabs instead of spaces, or structural issues in your docker-compose.yml file.

Quick fix

Fixes ERROR: yaml.parser.ParserError: while parsing a block mapping

# Replace LINE_NUMBER with the number from your error
sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p' docker-compose.yml

# Or view with line numbers
cat -n docker-compose.yml | sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p'
  1. Examine the error line number
  2. Check for tabs vs spaces
  3. Verify the basic structure
  4. Fix indentation consistency
docker — error
# Replace LINE_NUMBER with the number from your error
sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p' docker-compose.yml
# Or view with line numbers
cat -n docker-compose.yml | sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p'
ERROR: yaml.parser.ParserError: while parsing a block mapping

What this error means

The "yaml.parser.ParserError: while parsing a block mapping" error indicates that the YAML parser failed while trying to interpret a block mapping (key-value structure) in your docker-compose.yml file. This is a fundamental YAML syntax error that prevents Docker Compose from understanding your configuration. In YAML, a "block mapping" is a collection of key-value pairs where each key is followed by a colon and its value. When the parser encounters this error, it means the structure of your YAML file has broken the expected mapping format. The error message typically includes additional context: - A line number showing where the error was detected - Sometimes a column number indicating the exact position - Occasionally a description of what was expected vs. what was found Common patterns that trigger this error include: 1. **Incorrect indentation**: YAML uses whitespace to define structure. Even a single space difference can break parsing. 2. **Tabs vs spaces**: YAML strictly requires spaces for indentation. Tab characters will cause this error. 3. **Missing version declaration**: Older docker-compose files require a version field, and its absence can cause parsing issues. 4. **Structural hierarchy errors**: When keys are not properly nested under their parent elements. The YAML parser reads your file sequentially, building a tree structure based on indentation levels. When it encounters a line that doesn't fit the expected structure, it reports this error.

Typical symptoms

  • Running `docker-compose up` or `docker compose up` fails immediately with 'yaml.parser.ParserError: while parsing a block mapping'
  • The error message includes a specific line and column number reference
  • Docker Compose cannot parse the configuration file at all
  • The error appears after editing the docker-compose.yml file or copying content from online sources
  • CI/CD pipelines fail during the Docker Compose parsing phase
  • Other YAML validators may show different or no errors for the same file
  • The file worked previously but now fails after minor edits

Common causes

  1. Inconsistent indentation - mixing different numbers of spaces for nested elements
  2. Using tab characters instead of spaces for indentation
  3. Missing or malformed `services:` declaration at the root level
  4. Keys not properly nested under their parent elements (wrong indentation level)
  5. Missing space after colons in key-value pairs
  6. Copy-pasting content that introduced invisible Unicode characters (smart quotes, non-breaking spaces)
  7. BOM (Byte Order Mark) character at the beginning of the file
  8. Duplicate YAML merge keys (<<) in the same mapping
  9. Incorrect placement of list items (using `-` without proper indentation)

How to fix "ERROR: yaml.parser.ParserError: while parsing a block mapping"

1Examine the error line number

The error message tells you where the parser failed. Start by looking at that line and the lines around it:

bash
# Replace LINE_NUMBER with the number from your error
sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p' docker-compose.yml

# Or view with line numbers
cat -n docker-compose.yml | sed -n 'LINE_NUMBER-3,LINE_NUMBER+3p'

Important: The actual mistake is often on the line *before* the reported line number. The parser reports where it detected the problem, which may be after the actual error.

Look for:
- Lines that seem misaligned compared to siblings
- Missing spaces after colons
- Keys that appear at the wrong indentation level

2Check for tabs vs spaces

YAML requires spaces for indentation - tabs are forbidden. Detect tabs in your file:

bash
# Show all characters including tabs (^I)
cat -A docker-compose.yml

# Or search for tab characters
grep -P '\t' docker-compose.yml

If you find tabs, convert them to spaces:

bash
# Convert tabs to 2 spaces
sed -i 's/\t/  /g' docker-compose.yml

# Or use expand for more control
expand -t 2 docker-compose.yml > docker-compose.yml.new
mv docker-compose.yml.new docker-compose.yml

Editor configuration to prevent this:

VS Code (settings.json):

json
"[yaml]": {
  "editor.insertSpaces": true,
  "editor.tabSize": 2,
  "editor.detectIndentation": false
}
3Verify the basic structure

Ensure your docker-compose.yml has the correct top-level structure:

yaml
# Modern format (Docker Compose V2+)
services:
  web:
    image: nginx

# Legacy format (requires version)
version: "3.8"
services:
  web:
    image: nginx

Common structural mistakes:

yaml
# WRONG - services not indented under root
web:
  image: nginx

# WRONG - missing services key
version: "3"
web:
  image: nginx

# CORRECT
services:
  web:
    image: nginx

Check that all your services are nested under the services: key with consistent 2-space indentation.

4Fix indentation consistency

All elements at the same nesting level must have identical indentation. Standard Docker Compose uses 2-space indentation:

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

# CORRECT - consistent 2-space indentation
services:          # Level 0 (no indent)
  web:             # Level 1 (2 spaces)
    image: nginx   # Level 2 (4 spaces)
    ports:         # Level 2 (4 spaces)
      - "8080:80"  # Level 3 (6 spaces)

To visualize indentation:

bash
# Show whitespace characters
cat -A docker-compose.yml

# Count leading spaces per line
awk '{match($0, /^ */); print NR": "RLENGTH" spaces: "$0}' docker-compose.yml

Use your editor's "show whitespace" feature to see indentation levels clearly.

5Remove hidden Unicode characters

Copy-pasting from websites, documentation, or PDFs often introduces invisible problematic characters:

- Smart quotes: " and " instead of straight "
- Non-breaking spaces: Different from regular spaces
- BOM marker: Invisible character at file start

Detect non-ASCII characters:

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

# Check for BOM at start of file
file docker-compose.yml
# Should say "ASCII text" not "UTF-8 Unicode (with BOM)"

# View hex dump of first few bytes
xxd docker-compose.yml | head -5

Remove problematic characters:

bash
# Remove BOM if present
sed -i '1s/^\xEF\xBB\xBF//' docker-compose.yml

# Convert smart quotes to regular quotes
sed -i 's/[""]/"/g; s/[''']/'''/g' docker-compose.yml

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

Best approach: Manually retype the problematic section rather than trying to find invisible characters.

6Validate with yamllint

Use yamllint for detailed YAML validation with more helpful 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 feedback about:
- Indentation problems
- Line length issues
- Trailing spaces
- Key ordering
- Document start markers

Online validators (paste your YAML content):
- https://www.yamllint.com/
- https://yamlchecker.com/
- https://codebeautify.org/yaml-validator

Note: Generic YAML validators might pass a file that Docker Compose still rejects. The Docker Compose schema has additional requirements beyond basic YAML syntax.

7Use docker compose config to validate

Docker Compose includes a built-in validation command:

bash
# Validate and display resolved configuration
docker compose config

# Quiet mode - only shows errors
docker compose config --quiet

# Specify a different file
docker compose -f my-compose.yml config

If the YAML is valid, this outputs the fully resolved configuration with all variables substituted. If there's an error, it provides detailed information.

When other methods fail, use the binary search approach:

1. Create a minimal working file:

yaml
services:
  test:
    image: alpine

2. Verify it works: docker compose config

3. Add sections from your broken file one at a time

4. Run docker compose config after each addition

5. When it breaks, you've found the problematic section

8Recreate the file from scratch

If you cannot locate the issue, recreating the file often resolves hidden character problems:

bash
# Back up original
cp docker-compose.yml docker-compose.yml.backup

# Create new file in your editor (not copy-paste)
# Type out the configuration manually

When recreating:
1. Use a code editor with YAML support (VS Code, Sublime Text)
2. Enable "show whitespace" characters
3. Type each line manually instead of copying
4. Use 2 spaces consistently for each indentation level
5. Validate frequently with docker compose config

Template to start with:

yaml
services:
  app:
    image: your-image:tag
    ports:
      - "8080:80"
    environment:
      - NODE_ENV=production
    volumes:
      - ./data:/app/data

Build up from this working template, adding your specific configuration piece by piece.

Advanced notes

### YAML Block Mapping Fundamentals

A "block mapping" in YAML is a collection of key-value pairs defined using indentation:

yaml
# This is a block mapping
services:      # Key
  web:         # Nested key (part of the mapping)
    image: nginx  # Key-value pair

The parser error occurs when this structure is violated. Understanding the rules helps prevent errors:

1. Indentation defines scope: Children must be indented more than parents
2. Siblings must align: All keys at the same level need identical indentation
3. Spaces only: Tabs are illegal for indentation
4. Colon spacing: Key-value pairs need a space after the colon

### Common Parsing Error Variations

Different versions of the parser may report this error differently:

- yaml.parser.ParserError: while parsing a block mapping
- yaml: unmarshal errors: line X: cannot unmarshal
- expected '<block end>', but found '<block mapping start>'
- mapping values are not allowed in this context

These all indicate similar structural issues in your YAML.

### Docker Compose V1 vs V2 Differences

Docker Compose V1 (python-based, docker-compose command):
- Stricter about the version field
- Different error message formatting
- Some older tutorials reference V1 syntax

Docker Compose V2 (Go-based, docker compose command):
- The version field is optional and informational
- Better error messages in some cases
- Slight differences in how some configurations are parsed

If you're following old tutorials, ensure your syntax matches your Docker Compose version:

bash
# Check your version
docker compose version

### Handling YAML Anchors and Aliases

YAML anchors (&) and aliases (*) can cause parsing errors if misused:

yaml
# Correct anchor usage
x-common: &common
  restart: always
  logging:
    driver: json-file

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

# WRONG - duplicate merge keys
services:
  web:
    <<: *config1
    <<: *config2  # Error: duplicate merge key

For multiple anchors, use a list:

yaml
services:
  web:
    <<: [*config1, *config2]  # Correct way to merge multiple
    image: nginx

### IDE/Editor Setup for YAML

Proper editor configuration prevents most YAML errors:

VS Code with Docker extension:

json
{
  "[yaml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": "full",
    "editor.formatOnSave": false
  },
  "yaml.schemas": {
    "https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json": ["docker-compose*.yml", "compose*.yml"]
  }
}

This enables schema-based validation that catches errors before you run docker compose.

### Debugging Strategy for Complex Files

For large docker-compose.yml files:

1. Comment out sections: Use # to disable parts of the file
2. Binary search: Disable half the file, test, then narrow down
3. Split into multiple files: Docker Compose supports multiple -f flags
4. Use includes: Modern Docker Compose supports the include directive

bash
# Test with multiple files
docker compose -f docker-compose.yml -f docker-compose.override.yml config

This approach isolates problems faster than examining the entire file.

Frequently asked questions

What does "ERROR: yaml.parser.ParserError: while parsing a block mapping" mean?
yml file. This is a fundamental YAML syntax error that prevents Docker Compose from understanding your configuration. In YAML, a "block mapping" is a collection of key-value pairs where each key is followed by a colon and its value.
How do I fix "ERROR: yaml.parser.ParserError: while parsing a block mapping"?
The 'yaml.parser.ParserError: while parsing a block mapping' error occurs when Docker Compose encounters invalid YAML syntax, typically due to incorrect indentation, tabs instead of spaces, or structural issues in your docker-compose.yml file.
What causes "ERROR: yaml.parser.ParserError: while parsing a block mapping"?
Inconsistent indentation - mixing different numbers of spaces for nested elements Using tab characters instead of spaces for indentation Missing or malformed services: declaration at the root level
Is the "ERROR: yaml.parser.ParserError: while parsing a block mapping" error serious?
It is a low-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading