Setting a static IP address in Docker typically requires configuration during network creation. The specific steps are as follows:
Step 1: Create a Custom Network
First, create a custom Docker network. This is because Docker's default network modes (e.g., bridge) do not support directly assigning static IP addresses. Use the docker network create command to establish a custom bridge network:
bashdocker network create --driver bridge --subnet 172.25.0.0/16 my_custom_network
Here, --subnet defines the network's subnet. Customize this range based on your specific requirements.
Step 2: Run Container and Specify IP
With the custom network in place, specify it when running the container and set a static IP address. Use the --network option of the docker run command to select the network, and the --ip option to assign the container's IP address:
bashdocker run -it --name my_static_ip_container --network my_custom_network --ip 172.25.0.5 ubuntu /bin/bash
Here, the value after --ip is the static IP address you want to assign. Ensure this IP is within your custom subnet and not in use by other devices.
Example
Suppose you need to deploy a web server container requiring a fixed IP address. Follow these steps:
- Create the network:
bashdocker network create --driver bridge --subnet 172.25.0.0/16 web_network
- Run the web server container and specify the IP:
bashdocker run -d --name my_web_server --network web_network --ip 172.25.0.10 nginx
- Verify the configuration:
Use
docker inspect my_web_serverto check the container's network settings and confirm the IP address is configured as expected.
By following these steps, you can control Docker container IP addresses to align with network design and service needs. This is particularly valuable in production environments where containers require fixed communication addresses.