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

How can I set a static IP address in a Docker container?

1个答案

1

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:

bash
docker 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:

bash
docker 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:

  1. Create the network:
bash
docker network create --driver bridge --subnet 172.25.0.0/16 web_network
  1. Run the web server container and specify the IP:
bash
docker run -d --name my_web_server --network web_network --ip 172.25.0.10 nginx
  1. Verify the configuration: Use docker inspect my_web_server to 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.

2024年8月5日 10:06 回复

你的答案