Docker Compose YAML to JSON Conversion
Convert Docker Compose YAML files to JSON and vice versa. Learn the structure of docker-compose.yml with practical examples of services, volumes, and networks.
DevOps
Detailed Explanation
Docker Compose files are one of the most common real-world uses of YAML in software development. Understanding their JSON equivalent helps when working with Docker APIs or generating configurations programmatically.
A typical docker-compose.yml:
version: "3.8"
services:
web:
build: ./app
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgres://db:5432/myapp
depends_on:
- db
- redis
volumes:
- ./app:/usr/src/app
- node_modules:/usr/src/app/node_modules
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: myapp
POSTGRES_PASSWORD: secret
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
pgdata:
node_modules:
The JSON equivalent:
{
"version": "3.8",
"services": {
"web": {
"build": "./app",
"ports": ["3000:3000"],
"environment": [
"NODE_ENV=production",
"DATABASE_URL=postgres://db:5432/myapp"
],
"depends_on": ["db", "redis"],
"volumes": [
"./app:/usr/src/app",
"node_modules:/usr/src/app/node_modules"
]
},
"db": {
"image": "postgres:16-alpine",
"environment": {
"POSTGRES_DB": "myapp",
"POSTGRES_PASSWORD": "secret"
},
"volumes": ["pgdata:/var/lib/postgresql/data"]
},
"redis": {
"image": "redis:7-alpine",
"ports": ["6379:6379"]
}
},
"volumes": {
"pgdata": null,
"node_modules": null
}
}
Notable conversion details:
- Environment variables can be either an array of strings (
- KEY=value) or an object (KEY: value). Both are valid in Docker Compose. - Empty volume definitions (
pgdata:with no value) becomenullin JSON. - Port mappings should be quoted in YAML (
"3000:3000") to prevent the colon from being interpreted as a nested key.
Use Case
Programmatically generating Docker Compose configurations from a JSON-based template system or API, then converting to YAML for Docker CLI consumption.