Use Eureka despite having random external port of docker containers

懵懂的女人 提交于 2019-12-02 22:42:21

I have found a solution myself, which is maybe not the best solution, but it fits for me...

When you start docker with "--net=host" (host networking), then you use the hosts network stack directly. Then I just use 0 as port for spring-boot and spring randomizes the port for me and as it's using the hosts networking stack there is no translation to a different port (and IP).

There are some drawbacks though:

  • When you use host networking you can't use the link-feature for these containers as link source or target.
  • Using the hosts network stack leads to less encapsulation of the instance, which maybe a problem depending on your project.

I hope it helps

A lot of time has passed and I think I should elaborate this a little bit further:

  1. If you use docker to host your spring application, just don't use a random port! Use a fixed port because every container gets his own IP anyway so every service can use the same port. This makes life a lot easier.

  2. If you have a public facing service then you would use a fixed port anyway.

  3. For local starts via maven or for example the command line have a dedicated profile that uses randomized ports so you don't have conflicts (but be aware that there are or have been a few bugs surrounding random ports and service registration)

  4. if for whatever reason you want to or need to use host networking you can use randomized ports of course, but most of the time you shouldn't!

You can set up a directory for each docker instance and share it between the host and the instance and then write the port and IP address to a file in that directory.

$ instanceName=$(generate random instance name)
$ dirName=/var/lib/docker/metadata/$instanceName
$ mkdir -p $dirName
$ docker run -name $instanceName -v ${dirName}:/mnt/metadata ...
$ echo $(get port number and host IP) > ${dirName}/external-address

Then you just read /mnt/metadata/external-address from your application and use that information with Eureka.

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