DEV Community

Cover image for Extension in Docker compose
Hamza Waheed
Hamza Waheed

Posted on

Extension in Docker compose

To write an extension in a compose.yml file for Docker, you can use the x- prefix to define reusable fragments of configuration. Here's an example demonstrating how to use extensions in compose.yml:

  • Define the Extension: Use the **x- **prefix to define reusable configurations.
  • Reference the Extension: Use << to include the extension in your service definitions.

Example compose.yml with Extensions

version: '3.8'

# Define extensions
x-common-environment: &common-environment
  environment:
    - NODE_ENV=production
    - LOG_LEVEL=info

x-common-volumes: &common-volumes
  volumes:
    - data:/data

services:
  web:
    image: my-web-app:latest
    <<: *common-environment  # Include common environment variables
    <<: *common-volumes      # Include common volumes
    ports:
      - "80:80"

  worker:
    image: my-worker-app:latest
    <<: *common-environment  # Include common environment variables
    <<: *common-volumes      # Include common volumes
    environment:
      - WORKER_TYPE=background

volumes:
  data:

Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Extensions with x- Prefix: Define common configurations with x- prefix.
  • Reference Extensions: Use <<: *extension-name to include them in services.
  • Reuse Configurations: Simplifies and DRYs up the compose.yml.

This method helps maintain a clean and maintainable compose.yml file by avoiding repetition.

Top comments (0)