IT 3300 : Virtualization

Docker Compose

Intro

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.

Sample file

    version: "3.9"  # optional since v1.27.0
    services:
      web:
        build: .
        ports:
          - "5000:5000"
        volumes:
          - .:/code
          - logvolume01:/var/log
        links:
          - redis
      redis:
        image: redis
    volumes:
      logvolume01: {}

More

  • The file should be named docker-compose.yml
  • First make sure to create your Dockerfile
  • run docker compose up (old way was docker-compose up)

Advantages

  • Using a project name, DC can isolate environments from each other
  • Preserve volume data when containers are created
  • Recreate only containers that have changed
  • Can use variables to make things more dynamic

Use cases

  • Dev environment - can quickly interact with all your services
  • Automated testing - easily create the environment for testing

Networking

If you make a configuration change to a service and run docker-compose up to update it, the old container is removed and the new one joins the network under a different IP address but the same name. Running containers can look up that name and connect to the new address, but the old address stops working.

More networking

  • Containers in the same network can access each others ports directly
  • Can also look up the hostname of other containers on the same network

Example

    version: "3"
    services:
      web:
        build: .
        ports:
          - "8000:8000"
        links:
          - "db:database"
      db:
        image: postgres
        ports:
          - "8001:5432"

Example explained

  • Web machine can refer to hostname db and access port 5432 of that machine directly (default port for postgres)
  • Placed in the same network.
  • The links section, also makes db available as database.

Demo

Try the project here

Misc

  • Other commands with docker-compose
    • logs -> shows container logs
    • ps -> shows running containers
    • restart
    • rm -> deletes containers
    • stop