Docker is a platform for developing, shipping, and running container applications. Containers are lightweight, portable, and self-sufficient units that can run applications and their dependencies in isolated environments. When we create a container, it is automatically assigned an ID. This unique identifier enables easy management and tracking of individual containers, simplifying starting, stopping, or deleting them as needed.
To retrieve the IDs of Docker containers associated with a specific service, we can use the Docker CLI (Command Line Interface).
Docker CLI (Command Line Interface) empowers users to efficiently manage Docker containers and images. It offers a streamlined way to create, deploy, and manage applications using Docker containers. With commands for building, running, and networking containers, Docker CLI simplifies the process of containerization, enabling seamless development and deployment workflows across diverse environments.
Following is the command to find the ID of the container for a specific service.
docker ps --filter "name=<service-name>" --format "{{.ID}}"
In the provided command, replace <service_name>
with the actual name of the service for which you want to find the container ID. This command will return the ID of the running container.
In the widget below, we have initiated two different services product-service
and website
. Now, we will find the ID of the container with the help of Docker CLI.
Note: We have already implemented the above-mentioned command in the following widget. Click the “Run” button in the widget below to execute the code.
version: '3' services: product-service: build: ./product volumes: - ./product:/usr/src/app ports: - 5001:80 website: image: php:apache volumes: - ./website:/var/www/html ports: - 5000:80 depends_on: - product-service
Line 1: Specifying the version of the docker-compose file format.
Line 3: We use service
keyword to specify our services. We have initiated two different services named as product-service
and website
.
The products-service
service:
Line 5: Specifying the path to the build context, which in our case, is ./products.
Lines 6–7: Mounting a volume.
Lines 8–9: Mapping ports in the host:container
format.
The website
service:
Line 12: Docker Compose ensures that the “website” service is based on a PHP image with Apache server php:apache
available at Docker Hub
Lines 13–14: Mounting a volume.
Lines 15–16: Mapping ports in the host:container
format.
Lines 17–18: Expressing a dependency between website
and product-service
. We would encourage you to read about the depends on keyword in the Docker Compose documentation.
Free Resources