Module 8: Docker Compose Advanced
So far, you’ve learned how to use Docker Compose to define and run multi-container applications. In this module, we’ll go deeper into advanced features that make Compose powerful for real-world projects.
🔹 1. Environment Variables in docker-compose.yml
Instead of hardcoding values in your Compose file, you can use environment variables for flexibility and security.
👉 Example: .env file
MYSQL_ROOT_PASSWORD=secret123
MYSQL_DATABASE=mydb
👉 Example: docker-compose.yml
version: "3.9"
services:
db:
image: mysql:8
environment:
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- MYSQL_DATABASE=${MYSQL_DATABASE}
✅ This way, sensitive data (like passwords) stays outside your codebase.
🔹 2. Scaling Services
You can run multiple instances of a service using the --scale flag. This is useful for scaling apps in development.
👉 Example:
docker-compose up --scale web=3 -d
This will create 3 containers for the web service, all connected to the same network.
🔹 3. Using Profiles in Docker Compose
Profiles allow you to define optional services that should only run in specific scenarios.
👉 Example: docker-compose.yml
version: "3.9"
services:
app:
image: myapp:latest
ports:
- "8080:8080"
db:
image: postgres:14
profiles: ["dev"]
redis:
image: redis:7
profiles: ["cache"]
👉 Run with profiles:
docker-compose --profile dev up
docker-compose --profile cache up
✅ This helps separate development, testing, and production environments.
🔹 4. Networking with Docker Compose
By default, Docker Compose creates a network so services can communicate by name.
👉 Example:
version: "3.9"
services:
web:
image: nginx
ports:
- "80:80"
networks:
- mynet
api:
image: myapi:latest
networks:
- mynet
networks:
mynet:
✅ Now, web can reach api using http://api:port.
🎯 Wrap Up
In this module, you learned how to:
Use environment variables in Compose files
Scale services with
--scaleEnable/disable services using profiles
Manage networks with Docker Compose
With these skills, you can manage flexible, scalable, and environment-specific setups in your projects.
