Is there a way to add a hostname to an EXISTING do

2020-03-06 18:29发布

I have some containers that communicate via their IP from the network docker.

I can use the option -h or --hostname when running a new container but I want to set the hostname for existing container.

Is it possible?

3条回答
小情绪 Triste *
2楼-- · 2020-03-06 18:52

The hostname is immutable once the container is created (although technically you can modify /etc/hostname).

As suggested in another answer, you cannot change the hostname by stopping or restarting the container. There are not Docker engine client parameters for the start command that affect hostname. That wouldn't make sense anyway as starting a container simply launches the ENTRYPOINT process in a container filesystem that has already been created (i.e. /etc/hostname has already been written).

It is possible to synchronize the container hostname with the host by using the --uts=host parameter when the container is created. This shares the UTS namespace. I would not recommend --net=host unless you also want to share the host network devices (i.e. bypass the Docker bridge).

查看更多
Viruses.
3楼-- · 2020-03-06 18:56

One way is to create network and add different container in this network. When adding container in the network, you can use the --alias option of docker network. Like this:

  • Create a network:

    docker network create <my-network-name> 
    
  • Add containers in the network:

    docker network connect --alias <hostname-container-1> <my-network-name> <container-1>
    docker network connect --alias <hostname-container-2> <my-network-name> <container-2>
    docker network connect --alias <hostname-container-3> <my-network-name> <container-3>
    
  • Enjoy.

So each container can see other container by the alias (the alias is used as hostname).

查看更多
等我变得足够好
4楼-- · 2020-03-06 19:04

Generally, you would need to stop/restart a container, in order to run it again with -h (--hostname) (unless you used --net=host)

If you cannot stop the container, you can try and (in an attached bash session) edit its /etc/hostname.

查看更多
登录 后发表回答