Quick tip: Reduce your Docker Image size when using the League Flysystem s3 adapter
If you're deploying your PHP applications as Docker images and you're interacting with S3 as your filesystem with Flysystem, you'll know that your Docker image won't be small. Flysystem is a fantastic library to interact with the filesystem and adding support for interacting with an S3 bucket is very easy, but it comes with the downside of having to include the massive AWS PHP SDK.
The current AWS PHP SDK includes all classes for every AWS service, even if you're never planning on using anything else besides S3. The author of Flysystem (Frank de Jonge) has already marked this as an issue, as the entire AWS PHP SDK is 29mb. You can find that discussion here: Reducing package size.
This massive SDK is difficult to explain when you only need a tiny sliver of the functionality, so let's fix that!
Remove any unused dependencies
As a response to this, the AWS team has proposed a possible solution, which requires very little from you as a developer, but saves you 28mb!
The AWS team has created a callback that you can add to your
composer.json and removes all the services you don't plan on using: Removing Unused Services.
These are all the changes you'll need to make to your
composer.json and it'll instantly make your Docker image size smaller without breaking any of the great functionality or
pre-autoload-dump hook allows you to add a hook to the composer process, which in this case reads the
composer.json file and determines which services you'd like to preserve. It'll remove all other services from the SDK. There are a few services which will always be included, no matter if you use them or not:
The AWS team has marked these namespaces as "unsafe to delete", so they'll always be included in the dependencies.
The configuration in the
extra key contains a list of the namespaces you'd like to preserve.
As I'm only using the S3 namespace, this is the only service I'm listing.
Technically, I don't need to do this, as this namespace will never be removed by this Composer hook, but I like to be explicit about my dependencies.
So if you're trying to make your Docker image smaller and you're using Flysystem with the S3 adapter, be sure to implement this in your project! It'll save you many precious megabytes!Posted on: January 22nd, 2023
I help you achieve great SEO, higher conversions, and help you grow your business