Docker compose

To demonstrate how to use Docker Compose to manage complex application setups, let's create a Docker Compose YAML file for a sample web application consisting of multiple services, including a web server, a database server, and a cache server. We'll define the services, networks, volumes, and other components using Docker Compose syntax.

  • Create a Docker Compose YAML file:
  • Let's create a file named "docker-compose.yml" and define the services for our sample web application:

    version: '3.8'
    
    services:
      web:
        image: nginx:latest
        ports:
          - "8080:80"
        volumes:
          - ./html:/usr/share/nginx/html
        depends_on:
          - db
    
      db:
        image: mysql:5.7
        environment:
          MYSQL_ROOT_PASSWORD: root_password
          MYSQL_DATABASE: sample_db
        volumes:
          - db_data:/var/lib/mysql
    
      cache:
        image: redis:latest
    
    volumes:
      db_data:
  • Explanation of the Docker Compose file:
    • We've defined three services: "web", "db", and "cache".
    • The "web" service uses the NGINX image, exposes port 8080 on the host, mounts a volume for static HTML files, and depends on the "db" service.
    • The "db" service uses the MySQL 5.7 image, sets environment variables for root password and database name, and mounts a volume for database data storage.
    • The "cache" service uses the Redis image.
    • We've defined a volume named "db_data" for persisting MySQL data.
  • Running the Docker Compose file:
  • After saving the "docker-compose.yml" file, navigate to the directory containing the file in your terminal and run the following command to start the application:

    docker-compose up -d

    This command will create and start all the services defined in the Docker Compose file in detached mode ("-d"), allowing them to run in the background.

  • Verifying the application setup:
  • You can verify that the services are running correctly by checking their status and logs using the following commands:

    • To view the status of all services:
    • docker-compose ps
    • To view the logs of a specific service (e.g., "web" service):
    • docker-compose logs web
  • Interacting with the application:
  • You can access the web application running on port 8080 of your host machine's IP address. Open a web browser and navigate to "http://localhost:8080" or "http://:8080" to view the NGINX default page.

  • Stopping and cleaning up:
  • To stop and remove the containers created by Docker Compose, use the following command:

    docker-compose down

    This command will stop and remove all containers, networks, and volumes defined in the Docker Compose file.

By following these steps, you can use Docker Compose to manage complex application setups with multiple interconnected services.