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.
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.
The error message tells you where the parser failed. Start by looking at that line and the lines around it:
# 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
YAML requires spaces for indentation - tabs are forbidden. Detect tabs in your file:
# Show all characters including tabs (^I)
cat -A docker-compose.yml
# Or search for tab characters
grep -P '\t' docker-compose.ymlIf you find tabs, convert them to spaces:
# 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.ymlEditor configuration to prevent this:
VS Code (settings.json):
"[yaml]": {
"editor.insertSpaces": true,
"editor.tabSize": 2,
"editor.detectIndentation": false
}Ensure your docker-compose.yml has the correct top-level structure:
# Modern format (Docker Compose V2+)
services:
web:
image: nginx
# Legacy format (requires version)
version: "3.8"
services:
web:
image: nginxCommon structural mistakes:
# WRONG - services not indented under root
web:
image: nginx
# WRONG - missing services key
version: "3"
web:
image: nginx
# CORRECT
services:
web:
image: nginxCheck that all your services are nested under the services: key with consistent 2-space indentation.
All elements at the same nesting level must have identical indentation. Standard Docker Compose uses 2-space indentation:
# 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:
# Show whitespace characters
cat -A docker-compose.yml
# Count leading spaces per line
awk '{match($0, /^ */); print NR": "RLENGTH" spaces: "$0}' docker-compose.ymlUse your editor's "show whitespace" feature to see indentation levels clearly.
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:
# 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 -5Remove problematic characters:
# 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.ymlBest approach: Manually retype the problematic section rather than trying to find invisible characters.
Use yamllint for detailed YAML validation with more helpful error messages:
# Install yamllint
pip install yamllint
# Or on Ubuntu/Debian
sudo apt-get install yamllint
# Run validation
yamllint docker-compose.ymlyamllint 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.
Docker Compose includes a built-in validation command:
# 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 configIf 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:
services:
test:
image: alpine2. 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
If you cannot locate the issue, recreating the file often resolves hidden character problems:
# Back up original
cp docker-compose.yml docker-compose.yml.backup
# Create new file in your editor (not copy-paste)
# Type out the configuration manuallyWhen 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:
services:
app:
image: your-image:tag
ports:
- "8080:80"
environment:
- NODE_ENV=production
volumes:
- ./data:/app/dataBuild up from this working template, adding your specific configuration piece by piece.
### YAML Block Mapping Fundamentals
A "block mapping" in YAML is a collection of key-value pairs defined using indentation:
# This is a block mapping
services: # Key
web: # Nested key (part of the mapping)
image: nginx # Key-value pairThe 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:
# Check your version
docker compose version### Handling YAML Anchors and Aliases
YAML anchors (&) and aliases (*) can cause parsing errors if misused:
# 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 keyFor multiple anchors, use a list:
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:
{
"[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
# Test with multiple files
docker compose -f docker-compose.yml -f docker-compose.override.yml configThis approach isolates problems faster than examining the entire file.
dockerfile parse error line 5: unknown instruction: RRUN
How to fix 'unknown instruction' Dockerfile parse error in Docker
Error response from daemon: manifest for nginx:nonexistent not found: manifest unknown: manifest unknown
How to fix 'manifest for image:tag not found' in Docker
Error response from daemon: invalid reference format: repository name must be lowercase
How to fix 'repository name must be lowercase' in Docker
Error response from daemon: No such image
How to fix 'No such image' in Docker
Error response from daemon: Container is not running
How to fix 'Container is not running' when using docker exec