Search code examples
phpdockeramazon-s3docker-composelocalstack

Localstack S3 is not accessible from php


I'm trying to work with localstack in my docker container.I created demo-bucket for s3.I can view the file I uploaded from the terminal, but I cannot access s3 from the code. Where am I making a mistake? I share my codes below. Thanks. My yml file looks like this:

version: "3.7" 

services:

php:
  image: php:7.4-fpm
  volumes:
    - ~/image.minyay.com/src:/var/www/html
    - ~/image.minyay.com/docker/php.ini:/usr/local/etc/php/php.ini
web:
  image: nginx:1.17
  ports:
   - 80:80
  volumes:
    - ~/image.minyay.com/src:/var/www/html
    - ~/image.minyay.com/docker/site.conf:/etc/nginx/conf.d/site.conf
  depends_on:
    - php

localstack:
      image: localstack/localstack:0.11.0
      container_name: localstack
      ports:
        - "4563-4599:4563-4599"
        - '8055:8080'
      environment:
        - SERVICES=s3
        - DOCKER_HOST=unix:///var/run/docker.sock
        - DATA_DIR=/tmp/localstack/data
      volumes:
        - /tmp/localstack:/tmp/localstack
        - /var/run/docker.sock:/var/run/docker.sock
        - ./aws:/docker-entrypoint-initaws.d

And my php code looks like this:

  public function get_big_folder_in_s3($file_path){

        try {
            
           $pages = $this->s3->getPaginator('ListObjects', [
                'Bucket' => $this->bucket,
                'Prefix' => $file_path, //DESTINATION
            ]);

            foreach ($pages as $page) {
                foreach ($page['Contents'] as $object) {
                  //  echo $object['Key'] . PHP_EOL;
                    $result[] = $object['Key'];
                }
            }

            return $result;
            
        } catch (S3Exception $e) {

            return false;
            
        }
    }

My s3 client creation:

        $this->s3 = S3Client::factory([
            'credentials' => false,
            'version' => 'latest',
            'region'  => 'eu-central-1',
            'endpoint' => 'http://localhost:4572',
            'force_path_style'  => true,
        ]);

Solution

  • you didn't share you client initialization, but localstack usually requires passing an endpoint, thus I guess in PHP I guess it should look something similar to:

    $s3 = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => 'us-west-2',
        'endpoint' => 'http://localstack:4566',
    ]);