Dynamically get a running container name created by docker-compose

While an accepted answer was provided, the answer itself is not really related to the title of this question:

Dynamically get a running container name created by docker-compose

To dynamically retrieve the name of a container run by docker-compose you can execute the following command:

$(docker inspect -f '{{.Name}}' $(docker-compose ps -q web) | cut -c2-)

Just use docker-compose exec. It will execute in the already-running container instead of starting a new one.

docker-compose exec web python manage.py test

You can assign a name to a container using container_name option on docker-compose.yml file.

container_name: container_name

Then, you can easily run commands in that container using.

docker exec container_name python manage.py test.

For more information about docker-compose options, visit the official documentation.

https://docs.docker.com/compose/compose-file/