Docker Compose File
The Docker Compose file is a YAML file used to define a multi-container Docker application. It allows you to define services, networks, and volumes in a simple and readable format.
Warning
This section is under construction.
Please do not use this section as a reference for now.
Structure of a Docker Compose File
A typical Docker Compose file consists of several sections: version, services, networks, and volumes.
Version
The version key specifies the version of the Docker Compose file format. It's important to choose the correct version that matches your Docker Compose installation.
In most cases, you can use the latest version by specifying '3.8':
version: '3.8'
Services
The services section defines the different containers that make up your application. Each service represents a container and contains configuration options such as the image to use, environment variables, ports to expose, and volumes to mount.
services:
web:
image: nginx:latest # Use the latest Nginx image
ports: # Expose port 80 on the host machine
- "80:80" # Format: "host_port:container_port"
volumes: # Mount the ngnix directory to the Nginx container
- ./ngnix:/usr/share/nginx/html # Format: "host_path:container_path"
db: # Define a PostgreSQL database service
image: postgres:latest # Use the latest PostgreSQL image
environment: # Set environment variables for the database
POSTGRES_USER: example # Format: "variable_name: value"
POSTGRES_PASSWORD: example
Networks
The networks section allows you to define custom networks for your services. By default, Docker Compose creates a network for your application, but you can define additional networks if needed.
networks:
my-network:
Volumes
The volumes section allows you to define named volumes that can be shared between services. Volumes are useful for persisting data between container restarts and sharing data between containers.
volumes:
my-volume:
Example Docker Compose File
Here's an example of a complete Docker Compose file that defines a simple web application with a web server and a database:
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./ngnix:/usr/share/nginx/html
networks:
- my-network
db:
image: postgres:latest
environment:
POSTGRES_USER: example
POSTGRES_PASSWORD: example
volumes:
- db-data:/var/lib/postgresql/data
networks:
- my-network
networks:
my-network:
volumes:
db-data:
Running a Docker Compose Application
To run your application, navigate to the directory containing your docker-compose.yml file and use the following command:
docker-compose up -d
This command creates and starts all the services defined in your Docker Compose file. To stop and remove the containers, networks, and volumes defined in the file, use:
-d This flag runs the containers in detached mode, meaning they run in the background.
docker-compose down
Next Steps
Now that you understand the basics of the Docker Compose file, continue to...