List networks to identify unused ones
In this step, we will learn how to list Docker networks and identify those that are not currently being used by any containers. This is useful for cleaning up your Docker environment and freeing up resources.
We already used the docker network ls
command in the previous step to list all networks. Let's run it again to see the current state.
docker network ls
The output shows the network ID, name, driver, and scope for each network. Notice that the my-network-1
and my-network-2
networks we created are listed.
To identify unused networks, we can use the docker network prune
command with the --dry-run
flag. This flag allows us to see which networks would be removed without actually removing them.
docker network prune --dry-run
The output of this command will list the networks that are not attached to any running containers and would be pruned. Since we haven't attached any containers to my-network-1
or my-network-2
, they should appear in the output of the dry run.
Let's run a simple container attached to my-network-1
to see how it affects the output of docker network prune --dry-run
. We will use the hello-world
image, which is very small. First, pull the image:
docker pull hello-world
Now, run a container using this image and attach it to my-network-1
. The -d
flag runs the container in detached mode (in the background).
docker run -d --network my-network-1 hello-world
You will see a container ID as output.
Now, let's run the docker network prune --dry-run
command again.
docker network prune --dry-run
This time, my-network-1
should not appear in the list of networks to be pruned because it is being used by the running hello-world
container. my-network-2
, which is not being used, should still be listed.
To stop and remove the hello-world
container, first find its ID using docker ps
.
docker ps
Then, stop the container using docker stop <container_id>
and remove it using docker rm <container_id>
. Replace <container_id>
with the actual ID from the docker ps
output.
docker stop <container_id>
docker rm <container_id>
Now, if you run docker network prune --dry-run
again, both my-network-1
and my-network-2
should be listed as networks to be pruned, as they are no longer in use.