How to Create docker-compose.yml for Easy Docker Setup
docker-compose.yml file, write a YAML file that defines your services, networks, and volumes. Use the version key to specify the Compose file format, then list each service with its image, ports, and other settings. Save this file as docker-compose.yml in your project folder to run with docker-compose up.Syntax
The docker-compose.yml file uses YAML format to define your Docker app setup. It starts with a version key to specify the Compose file format version. Then, under services, you list each container with its configuration like image, ports, and volumes. You can also define networks and volumes globally.
version: '3.9' services: service_name: image: image_name:tag ports: - "host_port:container_port" volumes: - host_path:container_path networks: network_name: driver: bridge volumes: volume_name: {}
Example
This example shows a simple docker-compose.yml that runs a web server using the official Nginx image. It maps port 8080 on your computer to port 80 inside the container.
version: '3.9' services: web: image: nginx:1.23 ports: - "8080:80"
Common Pitfalls
Common mistakes when creating docker-compose.yml include incorrect indentation, missing quotes around port mappings, and using unsupported Compose file versions. YAML is sensitive to spaces, so always use consistent indentation (usually 2 spaces). Also, forgetting to map ports correctly can cause your app to be unreachable.
version: '3.9' services: web: image: nginx:1.23 ports: - 8080:80 # Wrong: missing quotes # Correct way: version: '3.9' services: web: image: nginx:1.23 ports: - "8080:80"
Quick Reference
- version: Compose file format version (e.g., '3.9')
- services: Define containers with
image,ports,volumes, etc. - ports: Map host to container ports as strings, e.g., "8080:80"
- volumes: Mount host folders or named volumes
- networks: Define custom networks if needed