Work with docker compse
A docker-compose.yml file defines and orchestrates multi-container Docker applications using a simple YAML syntax. It allows you to specify services, networks, volumes, and configurations in one place, enabling reproducible environments with commands like docker compose up. The file must be properly structured with correct indentation and syntax.
Prerequisites
-
Docker and Docker Compose installed on your system
-
A project directory where you’ll create the file
-
Basic understanding of your application’s dependencies (e.g., databases, ports, environment variables)
-
Step-by-step instructions
-
Create a project directory and navigate into it:
mkdir myproject && cd myproject -
Create a new file named
docker-compose.ymlusing a text editor:touch docker-compose.yml -
Define the version (optional in newer versions of Compose) and start the
servicessection -
Add each service (e.g., web, database) with its configuration:
-
Use
buildif you’re building an image from a Dockerfile -
Use
imageto pull a pre-built image from a registry -
Map ports using the
portskey (e.g.,"8000:5000"to expose host port 8000 to container port 5000) -
Mount volumes for persistent data or code syncing using
volumes -
Set environment variables with the
environmentkey -
Specify dependencies between services using
depends_on -
Optionally configure health checks, networks, and secrets
-
-
Save the file and test it by running:
sudo docker compose up --dry-run(to validate)sudo docker compose up(to start services)
-