简体   繁体   English

在运行带端口转发的容器时,没有从node.js代码获取docker容器的IP地址

[英]Not getting the IP address of the docker container from node.js code when run the container with port forwarding

I write a basic node.js code to get the IP of the Host. 我写了一个基本的node.js代码来获取Host的IP。 code looks like this: 代码看起来像这样:

var express = require('express');
var os = require('os');
var app = express();
var interfaces = os.networkInterfaces();


app.get('/',function(req,res){
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}
  res.send("IP address of container  :  " + addresses);
});

app.listen(3000);

When I run this code on my local machine I will the correct IP 当我在本地机器上运行此代码时,我将使用正确的IP

But when I containerize my application using Docker file : 但是当我使用Docker文件封装我的应用程序时:

FROM centos:7

MAINTAINER Vaibhav Jain <vaibhavjain882@gmail.com>

RUN yum -y install curl

RUN curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -

RUN yum -y install nodejs

RUN mkdir "/ecsTest"
WORKDIR /ecsTest

ADD node_modules node_modules
ADD app.js package.json ./

CMD ["node","app.js"]

and run the container with port forwarding I am not getting the IP 并使用端口转发运行容器我没有获得IP

command used for running the container: 用于运行容器的命令:

docker run -d -p 3000:3000 image_name docker run -d -p 3000:3000 image_name

appreciate the any lead. 感谢任何领导。 Thanks 谢谢

Finally I find the solution for that. 最后,我找到了解决方案。 I tried IP npm module and use its function address() and it works fine for me. 我尝试了IP npm模块并使用它的函数address(),它对我来说很好。

You need to expose port 3000 in your Dockerfile: 您需要在Dockerfile中公开端口3000:

EXPOSE  3000
CMD ["node","app.js"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM