EN VI

How can I conditionally run a container depending on environment in docker-compose.yml?

2024-03-12 14:00:06
How can I conditionally run a container depending on environment in docker-compose.yml

In ASP.NET Core world, we have appsettings.{environment}.json, do we have similar thing in docker's world?

My scenario is, I have a docker-compose.yml file that starts a couple of container services. But during the integration tests, I want to start an additional container service just for integration tests. I know I can't use .env file to specify environment to be used in the docker-compose.yml file. But I don't want the specified container service to be created and started in non-integration environment, which means I don't want to start the container and overwrite the setting based on passing environemnt from .env file, I want docker-compose.yml completed ignores the container service for non-integration environments.

so is it something like docker-compose-{environment}.yml like appsettings.{environment}.json that can be merged?

Solution:

Docker Compose Profiles are used to address this.

Using an example from the linked documentation, you assign your debug container to a specific profile: compose.yaml

services:
  backend:
    image: backend

  db:
    image: mysql

  tests:
    image: tests
    depends_on:
      - db
    profiles:
      - debug

With a compose.yaml structured like this, you can either start the default services by omitting the target profile, or specific services by specifying the profile name.

# Only start backend and db
$ docker compose up -d

# Starts backend and db and tests
$ docker compose up -d --profile debug
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login