Using Docker Compose with Profiles


Docker TIL

Docker Compose provides a way to name and group optional services with the profiles directive. Using profiles a docker-compose.yml file can be a little more useful and versatile.

A Use Case of Profiles

It is useful when you have a couple of containers that are occasionally needed but usually not. Let’s say we are creating a REST API service with Docker Compose. We also have its frontend user interface with React.js or Vue.js. For E2E testing, there’s also a selenium service.

services:
  db:
    image: db-image

  api:
    image: web-api-image

  frontend:
    image: frontend-image

  selenium:
    image: selenium/standalone-chrome-debug

However, since we mainly make changes only for the API implementation, we usually don’t need the frontend and selenium services. To avoid consuming extra resources and troubles, we don’t want extra containers running. By specifying the profiles, these unneeded containers can be disabled by default.

services:
  db:
    image: db-image

  api:
    image: web-api-image

  frontend:
    image: frontend-image
    profiles: ['frontend'] # added this one

  selenium:
    image: selenium/standalone-chrome-debug
    profiles: ['frontend'] # and this one as well

The services that do not have profiles attributes (db and api) will always be enabled. The following command will invoke only db and api.

docker compose up # will invoke only the db and api

In other words, the services that have profiles (in this example, frontend and selenium) will not be enabled by default. When you need these services, you can enable them by specifying the profile name.

docker compose --profile=frontend up # will invoke db, api, frontend, and selenium

You can specify the profiles by passing them as command-line options. You can also specify by setting the environment variable COMPOSE_PROFILES as well.

Other solutions

  • You can specify which service to invoke by command-line args for docker compose up.
  • You can create additional YAML files like docker-compose.frondend.yml and make Docker Compose read it by setting COMPOSE_FILE=docker-compose.yml:docker-compose.frontend.yml.

See Also