Docker Compose File

Learn the properties you can add in the docker-compose.yml file.

Docker Compose

Docker Compose is a utility for launching and managing multiple containers. It is more powerful and easier than using a series of docker run commands.

The configuration is usually defined in a docker-compose.yml (YAML) file. This lesson provides a summary of the commands that will be used most often in your Docker journey.

YML is a standard data format using new lines, tabs, colons, and dashes to indicate sections and data.

All configuration files must specify:

  1. Docker Compose version compatibility.
  2. The services (containers) to launch.
  3. The networks (if used).
  4. The volumes (if used).
version: '3'

services:

  #container
  mycontainer:
    #...definition...


networks:

volumes:

The following sections describe common settings used to configure service containers for Docker Compose v3 and above.

Use or build image

Specify a starting repository image, e.g., for the latest MySQL:

  mycontainer:
    image: mysql

A new image can be built by specifying the relative path context, the name of the dockerfile in that location, and any associated build args passed to Dockerfile ARG instructions:

  mycontainer:
    build:
      context: ./
      dockerfile: Dockerfile
      args:
        - arg1=val1
        - arg2=val2
        - arg3=val3

Set the container_name

Set the container name. This can be used for inter-container communications across the same Docker network:

  mycontainer:
    container_name: mycontainer

Container depends_on another

Express a dependency between services to ensure one or more other containers have started before launching this one:

  mycontainer:
    depends_on:
      - containerA
      - containerB

Set environment variables

Define any number of individual environment variables:

  mycontainer:
    environment:
      - MYVAR1=value1
      - MYVAR2=value2
      - MYVAR3=value3

Sets of environment variables can be defined in a .env file, e.g.

#example values
MYVAR1=value1
MYVAR2=value2
MYVAR3=value3

All values can be imported using env_file::

  mycontainer:
    env_file: .env

Multiple files can also be specified:

  mycontainer:
    env_file:
      - ./one.env
      - ./two.env
      - ./three.env

Attach to Docker networks

Join one or more Docker networks (created on first use):

  mycontainer:
    networks:
      - mynetwork

It is also possible to set aliases (alternative hostnames) and IP addresses for the container on the network:

  mycontainer:
    networks:
      mynetwork:
        aliases:
          - myname1
          - myname2
        ipv4_address: 172.16.238.20
        ipv6_address: 2001:3984:3989::20

The networks (and optional configurations) must be referenced after the services: definition at the bottom of docker-compose.yml:

networks:
  mynetwork:

Get hands-on with 1400+ tech skills courses.