How to Use Docker Compose for Development: Simple Guide
Use
docker-compose.yml to define your development services, volumes, and ports. Run docker compose up to start your environment with live code updates and shared resources.Syntax
A docker-compose.yml file defines your development environment with services, volumes, and ports.
- services: List of containers to run.
- build: Path to Dockerfile for building images.
- volumes: Share code between host and container for live updates.
- ports: Map container ports to your machine.
yaml
version: '3.8' services: app: build: ./app volumes: - ./app:/app ports: - '3000:3000' command: npm start
Example
This example shows a Node.js app running in Docker Compose with live code updates and port forwarding.
yaml
version: '3.8' services: web: build: ./web volumes: - ./web:/usr/src/app ports: - '8080:8080' command: npm run dev
Output
Starting web service...
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Common Pitfalls
Common mistakes include not mounting volumes, which stops live code updates, and forgetting to expose ports, making the app unreachable.
Also, avoid running production commands in development containers.
yaml
version: '3.8' services: app: build: ./app # Missing volume mount - no live code update ports: - '3000:3000' command: npm start # Corrected version with volume version: '3.8' services: app: build: ./app volumes: - ./app:/app ports: - '3000:3000' command: npm run dev
Quick Reference
Tips for smooth Docker Compose development:
- Use
volumesto sync code changes instantly. - Map ports to access your app from the browser.
- Use
commandto run development servers (e.g., nodemon). - Keep your Dockerfile optimized for fast rebuilds.
Key Takeaways
Define your development environment in docker-compose.yml with services, volumes, and ports.
Mount your code directory as a volume for live updates inside containers.
Expose container ports to your host machine to access apps in the browser.
Use development commands like nodemon or hot reloaders in your container.
Avoid missing volume mounts or ports to prevent common development issues.