Connecting Containers to a Custom Network
Now that you have created a custom Docker network, let's explore how to connect containers to it.
Connecting Containers During Creation
When you start a new container, you can specify the network it should be connected to using the --network
option. Here's an example:
docker run -d --name my-app --network my-custom-network nginx
This command starts a new Nginx container and connects it to the my-custom-network
custom network.
Connecting Existing Containers
You can also connect existing containers to a custom network using the docker network connect
command. Here's an example:
docker run -d --name my-db mysql
docker network connect my-custom-network my-db
This command first starts a new MySQL container, and then connects the my-db
container to the my-custom-network
custom network.
Verifying Container Connectivity
To verify that the containers are connected to the custom network, you can use the docker network inspect
command:
docker network inspect my-custom-network
The output will show the list of containers connected to the network, as well as their IP addresses within the custom network.
You can also test the connectivity between the containers by using the container names or IP addresses within the custom network. For example, you can ping
one container from another:
docker exec my-app ping my-db
This command will ping the my-db
container from the my-app
container, using the container name as the hostname.
By connecting containers to a custom Docker network, you can improve the isolation and security of your application, as well as simplify the management of network-related tasks.