CodeO CodeO -4 years ago 319
Node.js Question

Docker (compose) and socket io - how to link containers

I am currently working on a project where I remake an existing project to be used in docker containers.
I have 3 different containers:


  • a nodejs server that opens a socket.io connection on port 3001 and serves a webpage (that also connects to that socket.io server) on port 3000

  • a MySQL database that is needed for the nodejs backend

  • a small application that sends data via socket.io to the server



Now I am trying to link these containers but I am not sure if I understood the docker network just right. Am I right in assuming that in a docker-compose.yml file:


  • ports: exposes ports to the host computer (and also to all other/all linked containers?)

  • links: sets the start order and allows one container to user anothers exposed ports, hostname = containername

  • expose: exposes ports to all linked containers only (not the host, not unlinked containers)



So I have to always link and expose? Does this always work in both directions (socket.io messages can be send back too)?

So would something like this be right (version 3 format):

nodeserver:
ports:
-3000:3000
expose:
-3001
links:
-database
...

database:
(image mysql...)

application:
links:
-nodeserver
...


Could the application and the webpage now both reach the socket.io server as nodeserver:3000 ?

I tried some of this already but haven't gotten it fully work so I wanted to make sure to understand everything first.
Thanks for your help!

Answer Source

If I understood your deploy architecture, the application need access nodeserver via socket.io on port 3001, so you add a link with nodeserver to application, it's correct.

But the nodeserver serve a webpage that also connects to socket.io on port 3001, so the browser cannot connects nodeserver on port 3001.

So you just need to change nodeserver as below:

nodeserver:
ports:
    - "3000:3000"
    - "3001:3001"
links:
    -database
...

links:

Link to containers in another service. Either specify both the service name and a link alias (SERVICE:ALIAS), or just the service name.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

ports:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

expose:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

See more details: https://docs.docker.com/compose/compose-file

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download