Skip to main content

aws-localstack-s3-example-1

Description

aws-localstack-s3-example-1.png

S3 (Simple Storage Service) is an object storage service that provides a highly scalable and durable solution for storing and retrieving data. In S3, a bucket represents a directory, while an object corresponds to a file. Each object or file within S3 encompasses essential attributes such as a unique key denoting its name, the actual content it holds, a version ID for versioning support, and accompanying metadata. S3 can store unlimited objects, allowing you to store, retrieve, and manage your data in a highly adaptable and reliable manner.

Install LocalStack

local-compose.yaml
version: "3.8"

services:
localstack:
container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}"
image: localstack/localstack
ports:
- "127.0.0.1:4566:4566" # LocalStack Gateway
- "127.0.0.1:4510-4559:4510-4559" # external services port range
environment:
# LocalStack configuration: https://docs.localstack.cloud/references/configuration/
- DEBUG=${DEBUG:-0}
volumes:
- "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
- "/var/run/docker.sock:/var/run/docker.sock"
docker compose -f local-compose.yaml up

Create an S3 bucket

Run the following command to create an S3 bucket named sample-bucket:

awslocal s3api create-bucket --bucket sample-bucket

Output:

{
"Location": "/sample-bucket"
}

See: http://localhost:4566/sample-bucket

<ListBucketResult>
<IsTruncated>false</IsTruncated>
<Marker/>
<Name>sample-bucket</Name>
<Prefix/>
<MaxKeys>1000</MaxKeys>
</ListBucketResult>

You can list your S3 buckets using the ListBuckets:

awslocal s3api list-buckets

Output:

{
"Buckets": [
{
"Name": "sample-bucket",
"CreationDate": "2024-09-01T07:42:05+00:00"
}
],
"Owner": {
"DisplayName": "webfile",
"ID": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a"
}
}

Managing S3 objects

To upload a file to your S3 bucket, you can use the PutObject API. Download a random image from the internet and save it as image.jpg. Run the following command to upload the file to your S3 bucket:

awslocal s3api put-object \
--bucket sample-bucket \
--key image.jpg \
--body /media/{...}/image.jpg

Output:

{
"ETag": "\"deb86dad6d431665472eb815bcf1908a\"",
"ServerSideEncryption": "AES256"
}

You can list the objects:

awslocal s3api list-objects \
--bucket sample-bucket

Output:

{
"Contents": [
{
"Key": "image.jpg",
"LastModified": "2024-03-04T09:10:52+00:00",
"ETag": "\"deb86dad6d431665472eb815bcf1908a\"",
"Size": 107995,
"StorageClass": "STANDARD",
"Owner": {
"DisplayName": "webfile",
"ID": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a"
}
}
],
"RequestCharged": null
}

See: https://docs.localstack.cloud/user-guide/aws/s3/