0
0
DockerHow-ToBeginner · 3 min read

How to Use Profiles in Docker Compose for Selective Service Startup

Use profiles in your docker-compose.yml to group services and start only those groups with docker compose --profile <name> up. Define profiles under each service to control which services run together.
📐

Syntax

The profiles key is added under each service in docker-compose.yml. It takes a list of profile names. When you run docker compose --profile <profile-name> up, only services with that profile or no profile run.

Parts explained:

  • services: Defines containers.
  • profiles: List of profile names for the service.
  • docker compose --profile: CLI option to activate profiles.
yaml
services:
  web:
    image: nginx
    profiles:
      - frontend
  db:
    image: postgres
    profiles:
      - backend
  cache:
    image: redis
    # no profile means always runs
💻

Example

This example shows a Compose file with three services: web in the frontend profile, db in the backend profile, and cache without a profile (always runs). Running docker compose --profile frontend up starts web and cache only.

yaml
version: '3.9'
services:
  web:
    image: nginx:alpine
    profiles:
      - frontend
  db:
    image: postgres:alpine
    environment:
      POSTGRES_PASSWORD: example
    profiles:
      - backend
  cache:
    image: redis:alpine
    # no profile means always active
Output
Starting network "default" with the default driver Creating cache ... done Creating web ... done
⚠️

Common Pitfalls

1. Forgetting to specify --profile: If you don't use --profile, only services without profiles run.

2. Services with multiple profiles: A service can have multiple profiles; it runs if any are active.

3. Profiles do not isolate networks or volumes: Profiles only control which services start, not resource isolation.

yaml
services:
  app:
    image: myapp
    profiles:
      - frontend
      - backend

# Running without --profile
# Only services without profiles start

# Correct usage:
docker compose --profile frontend up
📊

Quick Reference

Command or KeyDescription
profilesList of profile names assigned to a service in docker-compose.yml
docker compose --profile upStart services with the specified profile and those without any profile
No profilesServices without profiles always start unless filtered by other options
Multiple profilesA service with multiple profiles starts if any profile is active

Key Takeaways

Define profiles under services in docker-compose.yml to group them logically.
Use 'docker compose --profile up' to start only services in that profile plus unprofiled services.
Services without profiles always start unless you specify profiles to filter.
A service can belong to multiple profiles and will start if any profile is active.
Profiles control service startup but do not affect networks or volumes.