This is what the equivalent YAML file looks like for the MongoDB and Mongo Express setup we did earlier with Docker commands:
version: '3.8'
services:
mongo:
image: mongo
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: qwerty
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: qwerty
ME_CONFIG_MONGODB_URL: mongodb://admin:qwerty@mongo:27017/Indentation is very important in YAML files — always use proper spacing (spaces, not tabs).
Even a small indentation mistake can break the configuration.
All the containers we want to run are defined under services.
Each service represents one container.
Example:
| Service Name | Container |
|---|---|
| mongo | MongoDB container |
| mongo-express | Mongo Express UI container |
Notice there is no network option in the YAML file.
This is because Docker Compose automatically creates a default network for all containers defined in the YAML file.
So when using a Docker Compose file:
Example:
mongo-express → connects to → mongoHere mongo works as a hostname inside the Docker network.
- key=value)environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=qwertyenvironment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: qwertyThis second format is more readable and commonly preferred.
If we want to add more services in the future (for example Redis, Node.js, or backend APIs), we simply define a new service in the same file.
services:
mongo:
image: mongo
mongo-express:
image: mongo-express
redis:
image: redisEach service can have:
Docker Compose file structure allows us to define an entire application stack in one place.
Instead of running multiple commands like:
docker run ...
docker run ...
docker network create ...We define everything in a single YAML file and manage it as one system.