Modify the IP address of the docker network card

After the Docker container is started, a network card is allocated on the host by default, which corresponds to a network namespace, and an IP address is randomly allocated under this network namespace.
If you want to modify the IP address of the Docker container, there are several methods:

  1. Modify the Docker network of the Docker host You can modify the file
    on the Docker host and add the following content:/etc/docker/daemon.json
{
    
    
  "bip": "192.168.1.5/24",  
}

This will modify the subnet to which the Docker container is assigned an IP 192.168.1.0/24, and the default gateway to be set to 192.168.1.1.
It will take effect after restarting Docker, and the containers created thereafter will be assigned IPs in this subnet.
2. When starting the container, specify the IP
using --ipparameters to specify the IP address of the container:

docker run -it --ip 192.168.1.10 ubuntu:18.04

This will force 192.168.1.10this IP to be assigned to newly started containers.
3. Modify the IP after starting the container
You can directly modify the network configuration in the container to change the IP address after starting the container.
First, locate the network namespace of the container. can use:

docker inspect 容器id|name    # 查看"NetworkSettings"下的"SandboxKey"值 

Then use ip netns execthe command to enter the network namespace:

sudo ip netns exec 沙盒KEY /bin/bash

Just modify the network configuration under this namespace. For example:

ip addr add 192.168.1.15/24 dev eth0
ip link set eth0 up 

This will set the IP of the eth0 network card to 192.168.1.15.
After exiting, the IP of the container has been modified.
It should be noted that if the container has written the old IP into the configuration of other containers or the host (for example /etc/resolv.conf), then the configuration in those places needs to be modified accordingly, otherwise network abnormalities may occur.
The above are several common methods to modify the IP address of the Docker container. Select the applicable solution according to the actual scenario.

Guess you like

Origin blog.csdn.net/qq_44534541/article/details/130528330