我对 AWS 和 docker 还很陌生。
在我的本地开发环境中,我想从应用服务器上传文件并将文件放置在localstack s3中。但是,当我尝试从应用服务器访问localstack s3时,出现以下错误。
AggregateError [ECONNREFUSED]:
at internalConnectMultiple (node:net:1139:18)
at afterConnectMultiple (node:net:1712:7) {
code: 'ECONNREFUSED',
'$metadata': { attempts: 3, totalRetryDelay: 105 },
[errors]: [
Error: connect ECONNREFUSED ::1:4566
at createConnectionError (node:net:1675:14)
at afterConnectMultiple (node:net:1705:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 4566
},
Error: connect ECONNREFUSED 127.0.0.1:4566
at createConnectionError (node:net:1675:14)
at afterConnectMultiple (node:net:1705:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 4566
}
]
}
docker-compose 配置如下。我参考了这个链接。
version: '3'
services:
test-app:
build:
dockerfile: Dockerfile
context: .
args:
- VARIANT=22-bookworm
container_name: test-app
stdin_open: true
dns:
# Set the DNS server to be the LocalStack container
- 10.0.2.20
networks:
- ls
localstack:
container_name: localstack
image: localstack/localstack
ports:
- "4566:4566"
- "4510-4559:4510-4559"
environment:
- SERVICES=s3
networks:
ls:
# Set the container IP address in the 10.0.2.0/24 subnet
ipv4_address: 10.0.2.20
networks:
ls:
ipam:
config:
# Specify the subnet range for IP address allocation
- subnet: 10.0.2.0/24
该应用程序在 NestJS 上运行,并且 S3Client 已初始化并注入以下代码片段:
import { S3Client } from '@aws-sdk/client-s3';
import type { Provider } from '@nestjs/common';
export const S3_CLIENT_TOKEN = 'S3Client';
export const s3ClientProvider: Provider = {
provide: S3_CLIENT_TOKEN,
useValue: new S3Client({
endpoint: 'https://localhost.localstack.cloud:4566',
region: 'ap-northeast-1',
credentials: {
accessKeyId: '',
secretAccessKey: '',
},
}),
};
控制器使用以下代码片段:
@Post()
async uploadFile(
@AuthorizedUser() _user: User,
@UploadedFile() file: Express.Multer.File,
): Promise<void> {
const command = new PutObjectCommand({
Bucket: 'test',
Key: file.filename,
Body: await readFile(file.path),
});
const response = await this.s3Client.send(command);
return;
}
有人能帮我解决这个问题吗?提前谢谢了 :)
我期望出现购物篮不存在错误而不是网络错误,或者文件上传成功。
我尝试了此链接中的步骤,但没有得到我预期的结果。
与 Docker 中的其他地方一样,特殊 IP 地址 127.0.0.1 指的是“当前容器”,而不是你的其他容器。官方 AWS S3 使用一种通过主机名区分不同存储桶的方案,而外部
localhost.localstack.cloud
服务的主要功能是允许 DNS 解析在你使用该系统时仍然有效。在 Docker 中,要连接到 localstack S3,您需要
所以你的配置块应该是这样的
这样,您就可以删除 Compose 文件中的很多设置。您无需手动设置容器 DNS;无需覆盖 Compose 生成的容器名称;
localstack
只要两个容器位于同一网络(包括default
Compose 自动创建的网络),主机名就可以正常工作;等等。您可以将 Compose 文件精简为