How to get the IP address of the docker host from inside a docker container

后端 未结 24 1948
鱼传尺愫
鱼传尺愫 2020-11-22 06:41

As the title says. I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.

24条回答
  •  时光说笑
    2020-11-22 07:21

    This is a minimalistic implementation in Node.js for who is running the host on AWS EC2 instances, using the afore mentioned EC2 Metadata instance

    const cp = require('child_process');
    const ec2 = function (callback) {
        const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
        // we make it silent and timeout to 1 sec
        const args = [URL, '-s', '--max-time', '1'];
        const opts = {};
        cp.execFile('curl', args, opts, (error, stdout) => {
            if (error) return callback(new Error('ec2 ip error'));
            else return callback(null, stdout);
        })
            .on('error', (error) => callback(new Error('ec2 ip error')));
    }//ec2
    

    and used as

    ec2(function(err, ip) {
            if(err) console.log(err)
            else console.log(ip);
        })
    

提交回复
热议问题