乐闻世界logo
搜索文章和话题

How do you create a custom Docker network?

1个答案

1

Creating custom networks in Docker allows containers to communicate in a more flexible and secure manner. I will detail the steps to create custom Docker networks and provide a practical example to demonstrate how to use such networks in real-world environments.

Step 1: Install Docker

First, verify that Docker is installed on your machine. You can check its installation and version by running the following command:

bash
docker --version

If not installed, visit the Docker official website to download and install the Docker version suitable for your operating system.

Step 2: Create a Custom Network

The command to create a custom network is straightforward. Use docker network create with the name you specify. For instance, to create a network named my-custom-network, run:

bash
docker network create my-custom-network

You can also specify the network type. Docker supports various network drivers, such as bridge, overlay, and macvlan, with bridge being the default. To specify the network type, use the --driver option. For example:

bash
docker network create --driver bridge my-custom-network

Step 3: Connect Containers to the Network

After creating the network, you can connect containers to it when running them using the --network option. For example, to run a container using the nginx image and connect it to my-custom-network, use the following command:

bash
docker run -d --name my-nginx-container --network my-custom-network nginx

Step 4: Verify the Network

After creating and connecting containers, you can verify the network configuration meets your expectations. Use the following command to inspect the network details:

bash
docker network inspect my-custom-network

This command displays detailed information about the network, including which containers are using it.

Practical Example

Assume we need to deploy a web application and a database in a local development environment, and we want these services to communicate securely while preventing external networks from directly accessing the database. We can create a custom network and connect both services to it.

  1. Create the network:
    bash

docker network create --driver bridge dev-network

shell
2. Run the MySQL database container: ```bash docker run -d --name my-mysql-db --network dev-network -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql:5.7
  1. Run the web application container, using WordPress as an example:
    bash

docker run -d --name my-wordpress-app --network dev-network -e WORDPRESS_DB_HOST=my-mysql-db -e WORDPRESS_DB_PASSWORD=my-secret-pw wordpress

shell
In this way, `wordpress` can securely access the `mysql` database via the `dev-network`, but both services are invisible to external networks. Through this process, I demonstrate how to create and use custom Docker networks, which are crucial for ensuring the security and flexible configuration of containerized applications.
2024年8月9日 14:10 回复

你的答案