dockerode icon indicating copy to clipboard operation
dockerode copied to clipboard

How to run multiple containers of the same image and expose different ports

Open HamzaBinSarfraz opened this issue 5 years ago • 2 comments

HamzaBinSarfraz avatar Dec 14 '20 18:12 HamzaBinSarfraz

This library is not developed for such purposes, of you ise docker-compose try this: docker-compose up --scale =

e.g. docker-compose up --scale wordpress=3

nahinakbar avatar Dec 17 '20 11:12 nahinakbar

Checking in on this to respond to @HamzaBinSarfraz (you've possibly come to the same conclusion/solution I did): this behavior is possible. I chose to implement a method that is possibly a bad idea, but seemed required based on my need to limit orchestration overhead. Here's the run command I've been using:

// Helper functions

let pid = 1000;

const port = () => {
  while(true) {
    pid++;
    if(!ports.hasOwnProperty(pid)) {
      break;
    }
  }
  return pid;
}

// Docker setup
const Docker = require("dockerode");
      ishmael = new Docker({socketPath: '/var/run/docker.sock'});

ishmael.run(image, [], undefined, {
  "Hostname": "",
  "Env": [...],
  "ExposedPorts": {"8000/tcp":{}},
  "HostConfig": {
    "Binds": [`/home/${user}:/home/${user}`],
    "PortBindings": {
      "8000/tcp": [{"HostPort": pid.toString()}]
    }
  }
}, (err, data, container) => {
  // Error handing for container init
}).on('container', (container) => {
  // Stuff to do when container is up and running
});

I'm not sure if this is exactly what you're looking for -- one note: it takes a bit for the container to acquire an address, which can cause a bit of confusion as to whether or not your container has spun up and is exposing ports correctly.

dluman avatar May 27 '22 00:05 dluman

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Open a new issue if needed.

stale[bot] avatar Nov 28 '23 02:11 stale[bot]