无法在Dockerfile上公开NodeJS多进程服务器的某些端口

jdzmm42g  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(91)

我的目标是创建一个基于NODE镜像的Docker镜像。图像应该包含几个NodeJs服务器,运行在不同的端口上,并将其端点暴露在外部。
Dockerfile:

FROM node:14
WORKDIR /app
RUN mkdir webapp2
RUN mkdir webapp2/be
RUN mkdir webapp2/fe

RUN npm install -g http-server && \
npm install -g newman webpack babel figlet

RUN npm install -g express react vue angular typescript
    
# Copy the application code
COPY /pages/* .
COPY index.html .
COPY welcome.js 
COPY webapp2/be/* ./webapp2/be/

EXPOSE 8080 8090 8091 8092 8093 8094 8095

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

脚本welcome.js负责运行2个服务器:http服务器在后台提供标准html页面和web应用程序webpage 2。

const http = require('http');
const { exec } = require('child_process');

function startProcess(command) {
  const process = exec(command);

  process.stdout.on('data', data => {
    console.log(data.toString());
  });

  process.on('error', err => {
    console.error(`Error starting process with command '${command}':`, err);
  });

  return process;
}

const webapp2Process = startProcess('node webapp2/be/controller.js > /var/webapp2.log 2>&1 &');
const serverProcess = startProcess('http-server');

// Gracefully stop the processes on program termination
process.on('SIGINT', () => {
  const processes = [serverProcess, , webapp2Process];

  processes.forEach(app => app.kill());
  process.exit();
});

正如您所看到的,webapp 2 Process在后台运行(由于终止&),http-server直接运行。
webapp 2代码:

const http = require('http');
const { info } = require('./logic.js');

const server = http.createServer((req, res) => {
    
    if (req.method === 'GET' && req.url === '/') {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain');
            res.end(info());
    } 
});

server.listen(8091, 'localhost', () => {
  console.log('Server running at http://localhost:8091/');
});

当前状态:通过主机系统中的浏览器可以轻松访问网页Webapp 2无法通过主机系统中的浏览器访问-> http://localhost:8091/返回404
但是,当我连接到Linux终端,并尝试curl http://localhost:8091时,webapp 2返回信息。
我试着把server.listen(8091,'localhost',()=> {改为server.listen(8091,'0.0.0.0',()=> {
但没有效果。

mitkmikd

mitkmikd1#

仅仅暴露是不够的,你还应该在docker run命令中Maphost:container端口,例如:(图像名称为jsgame

docker run -p 8080:8080 -p 8090:8090 -p 8091:8091 -p 8092:8092 -p 8093:8093 -p 8094:8094 -p 8095:8095 jsgame

为了使事情更简单,可以使用docker compose
另外,您还需要更改服务器,使其不包含'localhost',如下所示:

server.listen(8091, () => {
    console.log('Server running at http://localhost:8091/');
});

否则你会得到ERR_EMPTY_RESPONSE(我不是dockerMaven,所以不完全确定为什么需要这个)

相关问题