After you finally containerise your NodeJS app, you’re eager to see if it works. You run it, but then this happens:

“Error: connect ECONNREFUSED”

Your application fails to connect to the database. But why? Connecting to the database from localhost works without a hitch. Also, the app used to work fine before without containers.

You looked for help in the official Docker docs, and even with those instructions, you can’t get two containers to talk to each other.

Networking is a complicated topic. Add containers to the mix, and it becomes a real headache. You could read several books and spend days trying to understand the fundamentals of networking.

It would be much nicer to fix this seemingly trivial problem and get on with your day to work on features that matter.

In this article, you’ll read four possible reasons why your containers might fail to communicate with each other and a fix for each of them. These quick troubleshooting steps could save you wasted hours on debugging connectivity issues.

Do the containers share a network?

Containers can only communicate with each other if they share a network. Containers that don’t share a network cannot communicate with one another¹. That’s one of the isolation features provided by Docker.

A container can belong to more than one network, and a network can have multiple containers inside.

To find out if two containers share a network, first list all the networks of one of the containers. It doesn’t matter which one you pick. If container A can talk to container B, then by default in Docker networks, container B can also talk to container A.

## List all networks a container belongs to
docker inspect -f '{{range $key, $value := .NetworkSettings.Networks}}{{$key}} {{end}}' [container]

You should see a space-delimited output of all the networks the container is attached to. Then, for each of these networks, list all containers inside that network.

## List all containers belonging to a network by name
docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' [network]

If you don’t find the container you’re trying to connect to in any of the networks, then the containers don’t share a network. You can attach an already running container to a network with the following command:

## Attach a running container to a network
docker network connect [network] [container]

You can also specify a network when you start a container with the --network (or --net) flag as follows:

#docker #containers #docker containers #nodejs

4 Reasons Why Your Docker Containers Can't Talk to Each Other
4.15 GEEK