How should we communicate with docker containers when I am trying to make multiple containers?

86 views Asked by At

Below steps I want to do using dockerode.

  1. Create container on request
  2. Compile code inside container
  3. Extract output from container
  4. Finally delete container

I have api/run endpoint(next.js) inside docker container. To this endpoint I want send code as input and want to capture output from that container

Below is my code where, I am creating new container and when that container starts. I want to make axios post request to the api/run endpoint running inside container to send input. After process I want to capture the output or the response from request made.

I was trying to use IPaddress where container is running. But I found that we can't access container using IP.

Then what is the way to do this?

 const data = await request.json();
    const { language, program, inputs } = data;
    const docker = new Docker();
    const containerId = v4();
    // 1. I am trying to spin new container using dockerode on each request
    const container = await docker.createContainer({
      Image: "project-name",
      name: containerId,
    });
    await container.start();
    const containerInfo = await container.inspect();
    const ipAddress = containerInfo.NetworkSettings.IPAddress;
    const containerUrl = `http://${ipAdress}/api/run`;
    // 2 .Send code as input to that container's api/run endpoint (Where compiler logic is)

    const response = await axios.post(containerUrl, data);
    // 3. Then stop and remove after getting output
    await container.stop();
    await container.remove();
0

There are 0 answers