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

前端 未结 4 674
無奈伤痛
無奈伤痛 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:02

    I used a dockerode library for this.

    Solution:

    const Docker = require( 'dockerode' );
    const os = require( 'os' );
    
    const docker = new Docker( { socketPath: '/tmp/docker.sock' } );
    const container = docker.getContainer( os.hostname() );
    
    container.inspect( function( error, data ) {
        if ( error ) {
            return null;
        }
    
        const mappedPort = data.NetworkSettings.Ports[ '80/tcp' ][ 0 ].HostPort
    } );
    

提交回复
热议问题