简体   繁体   中英

docker-compose: start service from same docker-compose file using env vars to alter container name

We are using docker in a team of developers. We have on project all devs work on. Since we do not want to have one docker-compose.yml for each developer we use environment variables to pass the username to docker-compose. Inside docker-compose we have something like this services: myservice: image: myimage container_name: ${user}_myservice

This used to work very well for us but has stopped working lately. Assume there are two users. The first user runs docker-compose up myservice launching ${user1}_myservice. When the second user issues the same command, the second user will kill the container running under ${user1}_myservice and start ${user2}_myservice.

Somehow it seems that docker services are now linked directly and not only through the container_name variable as before.

We recently upgraded docker to Docker version 17.09.0-ce, build afdb6d4 . I attribute the change to the "new" docker version. I have tried downgrading docker-compose to previous versions and it seems this is not related to docker-compose.

UPDATE

Inspired by the answer below we found the following workaround:

We set the env variable COMPOSE_PROJECT_NAME to be the username on login of the user on the host. Then we extend the service name in our docker-compose.yml files to be <proj>_<service> , thereby avoiding any conflicts between identical service names across projects.

Rather than mucking about with variables in docker-compose.yml , it's probably easier just to make use of the --project-name ( -p ) option to docker-compose .

Normally, docker-compose derives the project name from the name of the directory that contains your docker-compose.yaml file. So if two people try to start an application from a directory named myapp , they will end up with a conflict because both instances will attempt to use the same name.

However, if they were to run instead:

docker-compose --project-name ${USER}_myapp ...

Then docker-compose for each user would use different project names (like alice_myapp and bob_myapp ) and there would be no conflict.

If people get tired of using the -p option, they could create a .env like this:

COMPOSE_PROJECT_NAME=alice_myapp

And this would have the same effect as specifying -p alice_myapp on the command line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM