Laravel Dockerization: Integrating S3Mock

Laravel Dockerization: Integrating S3Mock

Introduction

When developing a Laravel application that interacts with AWS S3 or other object storage services, it's crucial to have a testable bucket environment. This is especially important for features that local storage doesn't support, such as generating temporary URLs. Fortunately, there is a Docker image called S3Mock that simulates the AWS S3 API, which we'll explore in this tutorial.

What is S3Mock

The S3Mock is a library that provides a local server that mimics the behavior of the AWS S3 API. This allows developers to perform integration tests without having to actually connect to AWS. It is also available as a docker image, which we will be using in this tutorial.

Installing the Flysystem Composer Package

First, install the package Laravel uses for S3 integration via Composer:

Adding the Docker Service

Next, you need to add the following service to the docker-compose.yml file of your docker setup:

Configuring the Environment File

Ensure that the new service is functioning within your Docker setup, then set the storage-related environment variables in the .env file:

Verify that the bucket name you specify as AWS_BUCKET is listed under initialBuckets in the docker-compose.yml file. It's also important to set AWS_USE_PATH_STYLE_ENDPOINT to true to mandate the library's use of this endpoint.

Note: Make sure that the S3Mock service is connected to the same network as your Laravel application so the container name ld_s3 is recognized by the application as a domain.

Configuring Hosts

As you might have figured out already, the URLs for the bucket objects will start with http://ld_s3:9090. To make these URLs accessible outside the Docker environment, you will need to modify your hosts file by adding the following line:

In Ubuntu and other Unix-like systems, the hosts file is located at /etc/hosts.

Testing the Bucket

Your service is now ready to handle requests. Let's implement two methods: one to store a random PDF from the public directory into the bucket, and another to list the items in it:

S3Mock stores uploaded files in /s3mockroot/ within the container.

By default, S3Mock deletes the files stored in the bucket upon shutdown. To retain these files, set retainFilesOnExit to true:

References