简体   繁体   中英

How to change the subnet and the IP address of a docker container?

I have a docker container created with docker-compose running on a host.

The docker container obtained has its own network:

docker exec -it containername /bin/bash

root@4913fd78f383:/# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
155: eth0@if156: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:14:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.20.0.2/16 brd 172.20.255.255 scope global eth0
       valid_lft forever preferred_lft forever

So, the container occupies the IP 172.20.0.2/16 in the host.

My problem is that in this way my host can't connect on the real 172.20.xy hosts in the network where the host is connected.

So, the container (with its own ip) hide other real addresses.

I need to change the IP address of the existing container, possibly without deleting/recreating it.

I have created my container with docker compose, so I use these commands to run/stop the container:

docker start containername
docker stop containername

Thanks in advance.

In general you have two options:

  1. Using docker. Create a network with a custom subnet then from docker-compose join that network. for more details

  2. Using docker-compose. Define the network settings. for more details

In your case specifically you have to do the following:

  1. Create a network using docker cli.
    docker network create -d bridge --subnet 172.25.0.0/16 my_custom_network
  1. Make the container join the network
    docker network connect my_custom_network my_running_container
  1. Remove the container from the old network

You can get the name of the old network using docker inspect my_running_container

    docker network disconnect old_network my_running_container
  1. Delete unwanted network that docker-compose have created.
    docker network rm old_network
  1. Reconfigure docker-compose.yml to use the new network in order to keep the same settings if someone used docker-compose up again.

For more details about the above options check Work with Networks

Note that you can also configure the default docker0 as explained in here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM