How to get docker mapped ports from node.js application?

前端 未结 4 719
無奈伤痛
無奈伤痛 2021-02-06 05:44

I would like to get mapped port from inside node.js application.

ex.

docker-compose:

my-app:
    build:
        context: ./my-app
           


        
4条回答
  •  执念已碎
    2021-02-06 06:15

    What about using shelljs?

    const shelljs = require('shelljs');
    
    const output = shelljs.exec('docker ps --format {{.Ports}}', {silent: true}).stdout.trim();
    
    console.log(output); // 80/tcp
                         // 19999/tcp
                         // 9000/tcp
                         // 8080/tcp, 50000/tcp
    

    The output is a string, now let's map the response.

    const shelljs = require('shelljs');
    
    const output = shelljs.exec('docker ps --format {{.Ports}}', {silent: true}).stdout.trim();
    
    const ports = output.split('\n').map(portList => portList.split(',').map(port => Number(port.split('/')[0].trim())));
    
    

    This way ports return an array of arrays containing the ports:

    [ [ 80 ], [ 19999 ], [ 9000 ], [ 8080, 50000 ] ]
    

    In your case, you want the number between : and ->. So you can do this:

    const shelljs = require('shelljs');
    
    const output = shelljs
      .exec('docker ps --format {{.Ports}}', { silent: true })
      .stdout.trim();
    
    const aoa = output.split('\n').map(portList => portList.split(','));
    
    console.log(aoa); // [ [ '9000/tcp', ' 0.0.0.0:9000->123/tcp ' ], [ ' 80/tcp' ] ]
    
    let ports = [];
    
    aoa.forEach(arr => {
      arr.forEach(p => {
        // match strings which contains :PORT-> pattern;
        const match = p.match(/:(\d+)->/);
        if (match) {
          ports.push(Number(match[1]));
        }
      });
    });
    
    console.log(ports); // [ 9000 ]
    

    Finally, you need to install docker inside your container and connect docker socks as explained here.

    Update 29/06/2019:

    As said by @Tarun Lalwani, if sharing docker socks is a problem, you may create an app which shares the network with your main app and has a GET method that returns ports.

提交回复
热议问题