无法使用AWS lambda连接到elasticsearch服务



我在端口:4566上使用localstack使用下面的图像

version: "2.1"
services:
localstack:
image: "localstack/localstack"
container_name: "localstack"
ports:
- "4566-4620:4566-4620"
- "127.0.0.1:8055:8080"
environment:
- SERVICES=s3,es,dynamodb,apigateway,lambda,sns,sqs,sloudformation
- DEBUG=1
- EDGE_PORT=4566
- DATA_DIR=/var/lib/localstack/data
- DOCKER_HOST=unix:///var/run/docker.sock
- HOST_TMP_FOLDER=${TMPDIR}
- LAMBDA_EXECUTOR=docker
- DYNAMODB_SHARE_DB=1
- DISABLE_CORS_CHECKS=1
- AWS_DDB_ENDPOINT=http://localhost:4566
volumes:
- "${TMPDIR:-/var/lib/localstack}:/var/lib/localstack"
- "/var/run/docker.sock:/var/run/docker.sock"
networks:
- "local"
elasticsearch:
container_name: tqd-elasticsearch
image: docker.elastic.co/elasticsearch/elasticsearch:7.0.1
# volumes:
#   - esdata:/usr/share/elasticsearch/data
environment:
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- discovery.type=single-node
depends_on:
- "localstack"
logging:
driver: none
ports:
- 9300:9300
- 9200:9200
networks:
- "local"
networks:
local:
driver: "bridge"

问题:从lambda
调用elasticsearch时没有得到任何响应这是我的lambda代码

module.exports.createIndex = async () => {


const elasticClient = new Client({
node: "http://localhost:9200"
});
console.log("before the client call")
console.log(getIndices().then(res => { console.log(res) }).catch(err => {
console.log(err)
}))
console.log("after the client call")


const getIndices = async () =>
{
return await elasticClient.indices.create({
index:"index-from-lambda"
})
}

return {
statusCode: 201,
body: JSON.stringify({
msg:"index created successfully"
})
}
}
logs on my docker image,
before the client call
Promise { <pending> }
console.log("after the client call")

在此之后,即使我转到bash并验证该索引是否已创建,它返回空索引集,即没有创建索引
但是,同样的代码工作得很好,即在port 9200上创建索引,同时从httpserver@port 3000和独立的javascript文件调用独立服务器代码

const express = require('express')
const app = express();
const { Client } = require('@elastic/elasticsearch');
const elasticClient = new Client({
node: "http://localhost:9200"
});
app.listen(3000, () => {
console.log('listening to the port 3000')
})
const getIndices = async () =>
{
return await elasticClient.cat.indices()
}
console.log(getIndices().then(res => { console.log(res) }).catch(err => {
console.log(err)
}))

这是一个独立的js脚本

const { Client } = require('@elastic/elasticsearch');
const elasticClient = new Client({
node: "http://localhost:9200"
});
const getIndices = async () =>
{
return await elasticClient.cat.indices()
}
console.log(getIndices().then(res => { console.log(res) }).catch(err => {
console.log(err)
}))

这是网络错误或docker镜像错误吗?

这个问题已经列出来了,问题在于端点。所以localhost实际上是指向docker容器,而不是主机。如果您在主机上运行express服务器,请使用host.docker.internal作为主机名,它将从您的docker容器中寻址主机。同样的事情与Elasticsearch图像。现在代码变成了

elasticClient = new Client({
node:"http://host.docker.internal:9200"
})

其余部分保持不变。

最新更新