Day 18 Task: Docker for DevOps EngineersDocker Compose
Docker Compose
Docker Compose is a tool that was developed to help define and share multi-container applications.
With Compose, we can create a YAML file to define the services and with a single command, can spin everything up or tear it all down.
What is YAML?
YAML is a data serialization language that is often used for writing configuration files. Depending on whom you ask, YAML stands for yet another markup language or YAML ain’t markup language (a recursive acronym), which emphasizes that YAML is for data, not documents.
YAML is a popular programming language because it is human-readable and easy to understand.
YAML files use a .yml or .yaml extension.
ompose.yml). This file specifies the services, networks, and volumes required for your application. Here is a basic example:yamlCopy codeversion: '3' services: web: image: nginx:latest ports: - "8080:80" db: image: postgres:latest environment: POSTGRES_DB: mydatabase POSTGRES_USER: user POSTGRES_PASSWORD: passwordIn this example, two services (
webanddb) are defined. Thewebservice uses the latest Nginx image and maps port 8080 on the host to port 80 on the container. Thedbservice uses the latest PostgreSQL image and sets environment variables for database configuration.You can run this application with:
bashCopy codedocker-compose upAnd stop it with:
bashCopy codedocker-compose downTask-2: Working with Docker Compose and Existing Images
Pull a Docker Image:
You can pull an image from Docker Hub using
docker-compose.yml. Add aservicessection for the image you want to use and define its configuration. Example:yamlCopy codeversion: '3' services: web: image: nginx:latest ports: - "8080:80"Run it with:
bashCopy codedocker-compose upRun as Non-Root User:
To run Docker commands without sudo, ensure your user is added to the
dockergroup:bashCopy codesudo usermod -aG docker $USERAfter making this change, you need to reboot your machine for the changes to take effect.
Inspect Running Processes and Exposed Ports:
Use
docker psto see running containers anddocker inspectfor detailed information:bashCopy codedocker ps docker inspect <container_id>View Container Logs:
You can view logs using
docker logs:bashCopy codedocker logs <container_id>Stop and Start Container:
bashCopy codedocker-compose stop docker-compose startRemove Container:
bashCopy codedocker-compose downIf you want to remove the image as well:
bashCopy codedocker-compose down --volumes
Remember to replace <container_id> with the actual container ID.