Is there a way to add a hostname to an EXISTING docker container?

瘦欲@ 提交于 2019-12-01 01:19:18
Youssouf Maiga

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).

VonC

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.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!