0

My simplified docker compose file

services:
  myapp:
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - mynetwork
    ports:
      - 3000:3000
networks:
  mynetwork:

I run these two commands to up my containers

docker swarm init
docker stack deploy -c docker-compose.yml app

Now within the app I use dockerode to create dynamic containers. I have some code inside the dynamically created containers which performs an API call to myapp container. But when that call is triggered using the url http://myapp:3000 it fails, as it does not have any context about the network. So I tried adding the network created by docker compose. But that also fails.

Code for creating dynamic container and trying to attach it to the same network

const Docker = require("dockerode");

const docker = new Docker({
  socketPath: "/var/run/docker.sock",
});

let network = docker.getNetwork("mynetwork");

let container = await docker.createContainer({
  Image: '1234567890',
  NetworkMode: "mynetwork",
});

await network.connect({
  Container: container.id,
});

container.start();

After this I get this error

Error: (HTTP code 500) server error - Could not attach to network mynetwork: rpc error: code = NotFound desc = network mynetwork not found 
    at /app/node_modules/docker-modem/lib/modem.js:343:17
    at getCause (/app/node_modules/docker-modem/lib/modem.js:373:7)
    at Modem.buildPayload (/app/node_modules/docker-modem/lib/modem.js:342:5)
    at IncomingMessage.<anonymous> (/app/node_modules/docker-modem/lib/modem.js:310:16)
    at IncomingMessage.emit (node:events:523:35)
    at endReadableNT (node:internal/streams/readable:1367:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  reason: 'server error',
  statusCode: 500,
  json: {
    message: 'Could not attach to network mynetwork: rpc error: code = NotFound desc = network mynetwork not found'
  }
}

What is the right way to attach the dynamically created container to my network ?

LoneRanger
  • 665
  • 13
  • 31
  • 1
    Compose generally names things following its [project name](https://docs.docker.com/compose/environment-variables/envvars/#compose_project_name), so the network might be named something like `myapp_mynetwork`; `docker volume ls` will tell you for sure, but the project name is something that can be changed when you run `docker-compose` commands. – David Maze May 14 '23 at 20:55
  • Thanks for the reply, that was the issue. – LoneRanger May 15 '23 at 14:16

1 Answers1

1

The network isn't called mynetwork. Docker compose adds a 'project name' in front of it. By default, the project name is the directory name where the docker-compose.yml file is.

If your directory name is 'mydirectory', then the network name will be mydirectory_mynetwork.

Use docker network ls to find out what the name is and use that name in your node program.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35