Search code examples
dockerdocker-composeenvironment

Dev, Staging, Production in single server using docker


let's say I have a project. I want to make this project with different environments (dev, stag, prod) using Docker. So I will have three project containers with different environments. I have tried docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build but when I run another environment, it just only replaces the container. how to achieve this? note: each docker-compose.{env}.yml have .env.{env_name} file self.


Solution

  • Compose has the notion of a project name. This is used to identify all of the Docker resources that belong to a specific Compose setup. It defaults to the basename of the current directory; in your setup, this means all three environments have the same project name and their containers will replace each other's.

    You can use the docker-compose -p option to override the project name for a single docker-compose invocation. Like the -f options you have, you need to provide this option on every Compose invocation (or set the $COMPOSE_PROJECT_NAME environment variable).

    # Run the same images in all environments
    # (requires a fixed `image:` name for each thing that is `build:`ed)
    docker-compose build
    
    # Start the three environments
    docker-compose \
      -p dev                    \  # alternate project name
      -f docker-compose.yml     \  # base Compose file
      -f docker-compose.dev.yml \  # per-environment overrides
      up -d
    
    docker-compose -p staging -f docker-compose.yml -f docker-compose.staging.yaml up -d
    docker-compose -p prod -f docker-compose.yml -f docker-compose.prod.yaml up -d