You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker部署Localstack后,Terraform无法创建API Gateway资源

问题:Localstack + Terraform 创建API Gateway REST API时无法连接到4567端口端点

通过docker-compose启动Localstack,尝试用Terraform创建aws_api_gateway_rest_api资源,但无法连接到Localstack的restapis端点http://localhost:4567/restapis。S3等其他服务可正常访问,求排查问题。


docker-compose.yml 代码

version: '3'
services:

  localstack:
    image: localstack/localstack
    ports:
      - 4566:4566
      - 4567:4567
      - 4569:4569
      - 4572:4572
      - 4574:4574
      - 4575:4575
      - 4576:4576
      - 4593:4593
      - 4510-4559:4510-4559
    environment:
      - SERVICES=restapis,s3,lambda,dynamodb,sns,sqs,apigateway,iam

main.tf 代码

provider "aws" {
  region = "ap-southeast-2"

  endpoints {
    s3      = "http://localhost:4572"
    lambda  = "http://localhost:4574"
    dynamodb = "http://localhost:4569"
    sns     = "http://localhost:4575"
    sqs     = "http://localhost:4576"
    apigateway = "http://localhost:4567"
    iam     = "http://localhost:4593"
  }
}

resource "aws_api_gateway_rest_api" "example_api" {
  name = "example_api"
}

执行命令

terraform init
terraform plan
terraform apply

错误信息

Error: creating API Gateway REST API (example_api): RequestError: send request failed
│ caused by: Post "http://localhost:4567/restapis": read tcp 127.0.0.1:46738->127.0.0.1:4567: read: connection reset by peer

问题排查与解决

1. 核心问题:Localstack端口版本差异

Localstack从v0.11.x版本开始,已经统一使用4566端口作为所有服务的唯一入口,不再维护各个服务的独立端口(比如4567、4572这类旧端口)。你当前配置的apigateway端点用了废弃的4567端口,导致连接失败。

2. 修正步骤

  • 更新docker-compose.yml:无需映射大量独立端口,只保留4566即可;同时SERVICES里的restapis可以删除,因为apigateway已经包含该功能:

    version: '3'
    services:
      localstack:
        image: localstack/localstack
        ports:
          - 4566:4566
        environment:
          - SERVICES=s3,lambda,dynamodb,sns,sqs,apigateway,iam
    
  • 修改main.tf的AWS Provider配置:所有服务的端点统一指向4566端口,同时添加跳过凭证校验的参数,适配Localstack本地环境:

    provider "aws" {
      region = "ap-southeast-2"
      skip_credentials_validation = true
      skip_requesting_account_id = true
    
      endpoints {
        apigateway = "http://localhost:4566"
        s3         = "http://localhost:4566"
        lambda     = "http://localhost:4566"
        dynamodb   = "http://localhost:4566"
        sns        = "http://localhost:4566"
        sqs        = "http://localhost:4566"
        iam        = "http://localhost:4566"
      }
    }
    
    resource "aws_api_gateway_rest_api" "example_api" {
      name = "example_api"
    }
    

3. 验证操作

重启Localstack容器后,重新执行terraform init和terraform apply,即可正常创建API Gateway REST API资源。

内容的提问来源于stack exchange,提问作者Mitlandir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:37:45