Docker Community Forums

Share and learn in the Docker community.

Docker custom networks or network_mode = host which one should I select?

Hi, I have a question regarding using the network_host mode.
I have a 3 to 4 services in a docker_compose which I want to communicate with each other. Initially, I was using a custom network for interconnectivity of the services for this I had to specify the host url with each port, but then I found the network_mode host which I think is more easy for me with less code change.
My question is what is the best practice to have a custom network? Or we can use the network_mode host for services to communicate with each other?

A custom network is more portable and easier to use as port conflicts will not happen. Though, on host mode it is more likely that port conflicts will happen, it is enought that a single port is already used on the host itself or one of the other containers to fail the start of every other container requiring the same port.

In a custom network, a container needs to addresses the other containers using ther service name AND the port inside the container. I am not sure what you mean by ‘I had to specify the host url with each port’?

Question instead of an answer: Why do you need a custom network at all? docker-compose will manage the connection between the services automatically.

Actually I am running spring boot services and a redis, so in order for the services to connect with redis or with each other I have to specify the host machine url inside the config files of all services , for example ( is the host. So instead of specifying the url I just want to use localhost since everything is running on the same docker host. In order to achieve this I am using network_mode host so I can use localhost to connect the services.

So my question is using network_mode host is a good practice or not?

AFAIK, best practice is referring containers using container name (entered either in “docker run” command or in docker-compose.yml) as hostname. This allows to abstract from actual container deployment location (using orchestrators like kubernetes there can be multiple nodes, not just localhost). Custom network allows better encapsulation of the stack, in order to avoid port collisions, and is in general good practice.