I am stumped by "EndpointConnectionError"

I executed Lambda that sends a txt file to S3 storage. I got an “EndpointConnectionError” after this operation. As a supplement, I have attached the lambda, docker-compose.yml and executed commands below. The space after the http is there for restrictions regarding submissions.
----------Error----------

{
    "errorMessage": "Could not connect to the endpoint URL:\"http : //localhost:4566/test-bucket/2023-07-20-04-10-19.txt\"",
    "errorType": "EndpointConnectionError",
    "stackTrace": [
        "  File \"/var/task/lambda.py\", line 16, in lambda_handler\n    s3.Bucket(bucket).put_object(Key=key,Body=file_contents)\n",
        "  File \"/var/runtime/boto3/resources/factory.py\", line 580, in do_action\n    response = action(self, *args, **kwargs)\n",
        "  File \"/var/runtime/boto3/resources/action.py\", line 88, in __call__\n    response = getattr(parent.meta.client, operation_name)(*args, **params)\n",
        "  File \"/var/runtime/botocore/client.py\", line 530, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
        "  File \"/var/runtime/botocore/client.py\", line 947, in _make_api_call\n    http, parsed_response = self._make_request(\n",
        "  File \"/var/runtime/botocore/client.py\", line 970, in _make_request\n    return self._endpoint.make_request(operation_model, request_dict)\n",
        "  File \"/var/runtime/botocore/endpoint.py\", line 119, in make_request\n    return self._send_request(request_dict, operation_model)\n",
        "  File \"/var/runtime/botocore/endpoint.py\", line 202, in _send_request\n    while self._needs_retry(\n",
        "  File \"/var/runtime/botocore/endpoint.py\", line 354, in _needs_retry\n    responses = self._event_emitter.emit(\n",
        "  File \"/var/runtime/botocore/hooks.py\", line 412, in emit\n    return self._emitter.emit(aliased_event_name, **kwargs)\n",
        "  File \"/var/runtime/botocore/hooks.py\", line 256, in emit\n    return self._emit(event_name, kwargs)\n",
        "  File \"/var/runtime/botocore/hooks.py\", line 239, in _emit\n    response = handler(**kwargs)\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 207, in __call__\n    if self._checker(**checker_kwargs):\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 284, in __call__\n    should_retry = self._should_retry(\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 320, in _should_retry\n    return self._checker(attempt_number, response, caught_exception)\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 363, in __call__\n    checker_response = checker(\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 247, in __call__\n    return self._check_caught_exception(\n",
        "  File \"/var/runtime/botocore/retryhandler.py\", line 416, in _check_caught_exception\n    raise caught_exception\n",
        "  File \"/var/runtime/botocore/endpoint.py\", line 281, in _do_get_response\n    http_response = self._send(request)\n",
        "  File \"/var/runtime/botocore/endpoint.py\", line 377, in _send\n    return self.http_session.send(request)\n",
        "  File \"/var/runtime/botocore/httpsession.py\", line 517, in send\n    raise EndpointConnectionError(endpoint_url=request.url, error=e)\n"
    ]
}

----------Lambda----------

import boto3
from boto3.session import Session
from datetime import datetime


def lambda_handler(event,context):
    bucket = 'test-bucket'
    key = datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.txt'
    file_contents = 'Lambda Save File'

    s3 = boto3.resource(
            service_name='s3',
            endpoint_url='http://localhost:4566'
         )

    s3.Bucket(bucket).put_object(Key=key,Body=file_contents)
    return 'create file' + key


def main():
    client = boto3.client('lambda','us-east-1')
    result = client.list_functions()
    print(result)


if __name__ == "__main__":
    main()

----------docker-compose.yml----------

version: "3.8"

services:
  localstack:
    container_name: localstack_main
    image: localstack/localstack
    ports:
      - "127.0.0.1:4566:4566"
      - "127.0.0.1:4510-4559:4510-4559"
    environment:
      - S3_DIR=test_dir/
      - DEBUG=1
      - DOCKER_HOST=unix :///var/run/docker.sock
    volumes:
      - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

----------executed commands----------

  1. aws configure --profile localstack
    Access Key: dummy
    Secret Key: dummy
    region: us-east-1
    output format: json
  2. docker-compose up -d
  3. aws --endpoint-url=http ://localhost:4566 --profile localstack s3api create-bucket --bucket test-bucket
  4. zip lambda.zip lambda.py
  5. aws --endpoint-url=http ://localhost:4566 lambda create-function --function-name test --runtime python3.8 --handler lambda.lambda_handler --role arn:aws:iam::000000000000:role/r1 --zip-file fileb://lambda.zip --timeout 90 --region us-east-1 --profile localstack
  6. aws lambda --endpoint-url=http ://localhost:4566 invoke --function-name test --profile localstack result.log

Hello!
Please do not use localhost in the endpoint url in your lambda. The lambda runs in a different container than LocalStack, so localhost will not point to LocalStack. Please set the endpoint url to f'http://{os.environ.get("LOCALSTACK_HOSTNAME"):{os.environ.get("EDGE_PORT")}', that should work, then.

Thanks @dfangl !!!
This problem is solved !!!
You’re a superhero.