Search code examples
dockerdocker-composedocker-in-docker

How to get the name of the Docker network in a Docker-compose stack from within the containers?


I have a Docker Compose stack application. One function of the application is that it has a .NET Core backend running as a container in the stack which is able to spawn new temporary containers running data processing tasks. These containers need to exist in the same network as the stack in order to be able to access the database. The .NET Core backend container contains the necessary docker tooling and can execute docker commands using the docker-in-docker approach.

I need to know how, from within a container in the stack, to figure out the name of the network that the stack is using. It's sufficient to simply know the name of the network the container itself is running under. However I cannot and also do not want to depend on any hard-coded values. An alternative is simply to be able to unquestionably know the name of the container I am running inside, so I can use docker inspect to pull the network name.

Docker-compose does seem to use relatively predictable names (e.g. myapp_backend_1 for the backend container. myapp_default for the network) but as far as I know these names are NOT guaranteed so I cannot depend on hard-coding such names into the application.

Summary:

  • Need to be able to, from within a Docker container, retrieve the name of the network that Docker container is attached to.
  • Alternatively, need to be able to determine the name of a container from within that container so that I can use docker inspect to retrieve the network name.

Solution

  • You can get all the details about container from within the container, make use of docker remote apis.

    I have already answered this here.

    Please check and let me know if it helped.