Docker Compose File Structure
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/
Key Things to Note About the YAML File
1. Indentation is Important
Indentation is very important in YAML files — always use proper spacing (spaces, not tabs).
Even a small indentation mistake can break the configuration.
2. Services
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 |
3. No Network Defined
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:
- All services are automatically connected
- Containers can communicate using service names
- No need to manually create a Docker network
Example:
mongo-express → connects to → mongo
Here mongo works as a hostname inside the Docker network.
4. Two Ways to Define Environment Variables
Method 1: List Style (- key=value)
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=qwerty
Method 2: Key-Value Style (Preferred)
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: qwerty
This second format is more readable and commonly preferred.
5. Adding More Services
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.
Example
services:
mongo:
image: mongo
mongo-express:
image: mongo-express
redis:
image: redis
Each service can have:
- Its own image
- Ports
- Environment variables
- Volumes
- Networks (if needed)
6. Why This Structure is Powerful
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.
Summary
- Docker Compose uses a YAML file to define containers.
- Each container is called a service.
- Docker Compose automatically creates a default network.
- Environment variables can be defined in two formats.
- Multiple services can be added easily in the same file.
- The structure is simple, scalable, and easy to maintain.