我创建了一个侦听端口 5000 的容器化代理服务器(例如工作服务器)。我使用
--network=host
选项运行容器,以便它可以访问主机上的端口,而无需 -p
标志。服务器有一个终点get-buttons
。端点执行 shell 脚本,然后将请求转发到具有相同端点的主机的端口 6000。我用过nodejs的http-proxy
。代码如下:
const express = require('express');
const httpProxy = require('http-proxy');
const { exec, execSync } = require('child_process');
const app = express();
const proxy = httpProxy.createProxyServer({});
app.get('/start-analysis', (req, res) => {
// Execute a shell script
exec(`sh hello_world.sh ${req.query.abc}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error starting engine: ${error}`);
res.status(500).send('Error executing shell script');
return;
}
console.log('Shell script executed successfully');
proxy.web(req, res, { target: 'http://localhost:6000/get-buttons' }, function (error) {
console.log("Proxy Error ", error)
});
});
});
app.listen(5000, () => {
console.log('Worker server is running on port 5000');
});
我每次都会收到以下错误
Error: socket hang up
at connResetException (internal/errors.js:639:14)
at Socket.socketOnEnd (_http_client.js:499:23)
at Socket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1333:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
code: 'ECONNRESET
可能会注意到,如果我从容器内部运行
curl localhost:6000/get-buttons
,它会给我一个响应。我很困惑,如果curl命令有效,为什么nodejs代理给我一个socker挂起错误。
http-proxy 不会替换您正在调用的路径,只会替换主机(但也替换路径)。
:6000
上的服务器正在接收 /get-buttons/start-analysis 的请求。
重现:
nc -ltp 6000
启动新的 netcat 侦听器nc
的输出:GET /get-buttons/start-analysis HTTP/1.1
accept: */*
user-agent: curl/7.81.0
host: localhost:5000
connection: close
您可以在
proxy.web
之前添加一行来更新req.url
,并将目标更改为以下内容以获得所需的结果:
req.url = 'http://localhost:5000/get-buttons';
proxy.web(req, res, { target: 'http://localhost:6000'}
上面的代码在目标上产生以下结果:
:: nc -ltp 6000
GET /get-buttons HTTP/1.1
accept: */*
user-agent: curl/7.81.0
host: localhost:5000
connection: close