'Starting two services with the same compose file (different in image's name and container's name) cause others stop
In my project, I have one docker-compose.yml as follows:
version: '3.9'
services:
my-service:
build:
dockerfile: ./Dockerfile
context: ./
image: "my-service:${IMAGE_VERSION}"
container_name: my-service-$IMAGE_VERSION
restart: always
...
Then, I have two environment files,
.env.devfor development:
...
IMAGE_VERSION=dev
...
.env.prodfor production:
...
IMAGE_VERSION=latest
...
I have no .env file.
Every time I want to develop, I run docker-compose --env-file .env.dev up --build. And when I want to deploy, I run docker-compose --env-file .env.prod up --build.
Although the Docker image's name and container's name are different in each process, I cannot run both services simultaneously (in the same host machine). For example, when I deploy with .env.prod env, it always recreates the dev containers, making my-service-dev stop. (The log: FatalError: 'Termination signal' is detected by the operating system.)
Successfully built 119ce748c6f5
Successfully tagged my-service:latest
Recreating my-service-dev ... done ==> THIS LINE!
Attaching to my-service-latest
Which Docker mechanism causes such consequence? How can I avoid it? Or do I have to create two different compose files?
Solution 1:[1]
That's normal behavior, because the project name is determined by default from your folder name. And it is the same in both cases, same like the internal service-name. If you check it by docker inspect you will get:
"Config": {
"Labels": {
"com.docker.compose.project": "folder_name",
"com.docker.compose.service": "service_name",
}
}
If you're working with .env-Files, just add
.env.dev:
COMPOSE_PROJECT_NAME=your_app_dev
.env.prod:
COMPOSE_PROJECT_NAME=your_app_prod
and you can spin up both, because you change the project name.
If the have to use the same network, add:
services:
your_service:
networks:
- test_network
networks:
test_network:
name: test_network
name is important because compose prefixes with project name else.
Both containers will have their service name as network alias, and it is the same. So make sure to not use service_name if you want to DNS-resolve one of them. Maybe there are other problems in using the same alias, but don't know.. there is no problem in starting so far..
If they don't have to interact just keep compose doing its default thing and dev/prod are joining two separate networks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
