In Docker, different network modes can be used for communication between containers. If the default bridge network mode is used, each container will be assigned a dynamic IP address. However, the IP address of Docker containers can be configured in the following ways:
Custom bridge network mode: Create a custom bridge network and specify the subnet, gateway, and IP range. For example, when creating a custom network, the following command can be used to specify the subnet as "172.10.0.0/16", the gateway as "172.10.2.1", and assign the IP address "172.10.2.2" to the container:
docker network create --subnet=172.10.0.0/16 --gateway=172.10.2.1 --ip-range=172.10.2.0/24 my_network
Then, when running the container, use the --net parameter to specify the network to be used, as shown below:
docker run -it --net my_network --ip 172.10.2.2 my_image
Using host network mode: Using the --net host parameter allows the container to share the network stack with the host, thus directly using the host IP address. For example:
docker run -it --net host my_image
Setting a static IP address inside the container: Inside the container, a static IP address can be manually set. For example, after the container is started, the following command can be used to set the IP address:
ifconfig eth0 172.10.2.2 netmask 255.255.255.0 up
These are common methods for setting the IP address of Docker containers. Please choose the appropriate method according to your needs.