A bucket is the fundamental container for objects in Object Storage Service (OSS). It offers unlimited storage and scales elastically.
Basic configuration
These are the core settings for a bucket and cannot be changed after creation.
-
Bucket Name: Must be globally unique. We recommend using department or business identifiers when naming buckets to simplify identification and management. For example:
hr-documents. -
Region: Determines where your data is physically stored. Choose a region based on the following priorities:
-
Compliance: Choose a region that meets your regulatory requirements.
-
Performance: To reduce network latency, choose the region closest to your target users. If you access data from other Alibaba Cloud products, such as ECS, select the same region to use free internal network traffic and minimize latency.
-
Feature availability: Refer to the Release Notes to verify that the region supports your required features.
-
Cost optimization: After meeting the other requirements, choose a region with more favorable pricing.
NoteYou can no longer create buckets in the China (Zhangjiakou) region. However, existing buckets in this region are unaffected. If you have a resource plan for this region, you can still use it to offset charges for these buckets.
-
If you specify only a bucket name and region when creating a bucket, it defaults to the following settings: standard storage, Zone-Redundant Storage (ZRS), private, and Block Public Access enabled.
Console
-
In the OSS console, go to the Buckets page and click Create Bucket.
-
In the Create Bucket panel, set Bucket Name and Region, and then click Create.
Ossutil
Use the ossutil command-line tool to create a bucket. For installation instructions, see Install ossutil.
-
Configure the required bucket region.
ossutil config -
Press Enter to skip the initial prompts until the region prompt appears:
Please enter Region [cn-hangzhou]:Enter the target region ID, such as
cn-beijing, and press Enter, or press Enter to accept the default regioncn-hangzhou. Region IDs are listed in the OSS Regions and Endpoints topic. -
Create a bucket named examplebucket.
ossutil mb oss://examplebucket -
Verify that the bucket was created successfully.
ossutil ls
For more information about this command, see mb (create a bucket).
SDK
The following samples show how to create a bucket with common SDKs. For code samples for other SDKs, see Introduction to Alibaba Cloud SDKs.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class Demo {
public static void main(String[] args) throws Exception {
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name.
String bucketName = "examplebucket";
// Specify the resource group ID. If you do not specify a resource group ID, the bucket belongs to the default resource group.
//String rsId = "rg-aek27tc****";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer in use, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a bucket and enable the hierarchical namespace feature.
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
// To specify the storage class, ACL, and data redundancy type when you create the bucket, see the following code.
// This example shows how to set the storage class of the bucket to Standard.
createBucketRequest.setStorageClass(StorageClass.Standard);
// The default data redundancy type is LRS, which is DataRedundancyType.LRS.
createBucketRequest.setDataRedundancyType(DataRedundancyType.LRS);
// Set the ACL of the bucket to public-read. The default ACL is private.
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
// When you create a bucket in a region that supports resource groups, you can configure a resource group for the bucket.
//createBucketRequest.setResourceGroupId(rsId);
ossClient.createBucket(createBucketRequest);
// Create the bucket.
ossClient.createBucket(createBucketRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}import argparse
import alibabacloud_oss_v2 as oss
# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put bucket sample")
# Specify the required command line parameter --region, which specifies the region in which the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the required command line parameter --bucket, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the optional command line parameter --endpoint, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
args = parser.parse_args() # Parse command line parameters.
# Load access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located.
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Execute the request to create a bucket and set its storage class to Standard.
result = client.put_bucket(oss.PutBucketRequest(
bucket=args.bucket,
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='Standard'
)
))
# Output the HTTP status code in the response and the request ID used to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
if __name__ == "__main__":
main() # Entry point of the script. The main function is invoked when the file is run directly.package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string
bucketName string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
flag.Parse()
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load default config. Credentials are read from environment variables.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
request := &oss.PutBucketRequest{
Bucket: oss.Ptr(bucketName),
}
// Create the bucket.
result, err := client.PutBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket %v", err)
}
log.Printf("put bucket result:%#v\n", result)
}<?php
// Automaticically load objects and dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region parameter is required. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket is required.
];
// Generate a list of long options for parsing command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));
// Parse command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters have been configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
exit(1);
}
}
// Retrieve the values of the command line parameters.
$region = $options["region"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the bucket.
// Load the credential information (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a request to initiate bucket creation.
$request = new Oss\Models\PutBucketRequest($bucket);
// Call the putBucket method.
$result = $client->putBucket($request);
// Output the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP status code.
'request id:' . $result->requestId // Unique ID of the request.
);
using Aliyun.OSS;
using Aliyun.OSS.Common;
// The endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Ensure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set before running.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// The bucket name.
var bucketName = "examplebucket";
// The region ID where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Specify v4 signatures.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Create the bucket.
try
{
var request = new CreateBucketRequest(bucketName);
// By default, the bucket ACL is private. To set the ACL to public-read, use the following code.
request.ACL = CannedAccessControlList.PublicRead;
// Set the data redundancy type to Zone-Redundant Storage (ZRS).
request.DataRedundancyType = DataRedundancyType.ZRS;
client.CreateBucket(request);
Console.WriteLine("Create bucket succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Create bucket failed. {0}", ex.Message);
}const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourBucketName',
});
async function putBucket() {
try {
const options = {
// Storage class: Standard (default), Archive
storageClass: 'Standard',
// ACL: private (default), public-read, public-read-write
acl: 'private',
// Data redundancy type: LRS (locally redundant storage, default), ZRS (zone-redundant storage)
dataRedundancyType: 'LRS',
};
const result = await client.putBucket('examplebucket', options);
console.log(result);
} catch (err) {
console.log(err);
}
}
putBucket();require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Specify the endpoint for the region where your bucket is located. For example, for the China (Hangzhou) region, use https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Ensure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set before running.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name, for example, examplebucket.
client.create_bucket('examplebucket')// Construct a request to create a bucket.
// Specify the bucket name.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("examplebucket");
// Specify the access control list (ACL) of the bucket.
// createBucketRequest.setBucketACL(CannedAccessControlList.Private);
// Specify the storage class of the bucket.
// createBucketRequest.setBucketStorageClass(StorageClass.Standard);
// Create the bucket asynchronously.
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
@Override
public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
Log.d("asyncCreateBucket", "Success");
}
@Override
public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
// Request exception.
if (clientException != null) {
// Client-side exceptions, such as network errors.
clientException.printStackTrace();
}
if (serviceException != null) {
// Server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, for example, examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Specify the name, storage class, and ACL for the new bucket. */
CreateBucketRequest request(BucketName, StorageClass::IA, CannedAccessControlList::PublicReadWrite);
/* Set the data redundancy type to zone-redundant storage. */
request.setDataRedundancyType(DataRedundancyType::ZRS);
/* Create the bucket. */
auto outcome = client.CreateBucket(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "CreateBucket fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}// Construct a request to create a bucket.
OSSCreateBucketRequest * create = [OSSCreateBucketRequest new];
// Set the bucket name to examplebucket.
create.bucketName = @"examplebucket";
// Set the access control list (ACL) of the bucket to private.
create.xOssACL = @"private";
// Set the storage class of the bucket to Infrequent Access (IA).
create.storageClass = OSSBucketStorageClassIA;
OSSTask * createTask = [client createBucket:create];
[createTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"create bucket success!");
} else {
NSLog(@"create bucket failed, error: %@", task.error);
}
return nil;
}];
// Block the current thread to wait for the task to complete.
// [createTask waitUntilFinished]; #include "oss_api.h"
#include "aos_http_io.h"
/* The endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* The bucket name, for example, examplebucket. */
const char *bucket_name = "examplebucket";
/* The region ID that corresponds to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize an aos_string_t from a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Ensure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set before running. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// You must also configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method at the program entry point to initialize global resources, such as network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* A memory pool for memory management, equivalent to apr_pool_t. The implementation code is in the APR library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that no other memory pools are inherited. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. These options contain global configuration information such as endpoint, access_key_id, acces_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory from the memory pool to options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize client options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
oss_acl_e oss_acl = OSS_ACL_PRIVATE;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* data to the aos_string_t bucket. */
aos_str_set(&bucket, bucket_name);
/* Create the bucket. */
resp_status = oss_create_bucket(oss_client_options, &bucket, oss_acl, &resp_headers);
/* Check whether the request was successful. */
if (aos_status_is_ok(resp_status)) {
printf("create bucket succeeded\n");
} else {
printf("create bucket failed\n");
}
/* Release the memory pool, which releases the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}API
To create a bucket with the PutBucket API, specify the bucket name and region in the Host request header.
Storage class
OSS provides five storage classes: Standard, Infrequent Access (IA), Archive, Cold Archive, and Deep Cold Archive. The default storage class is Standard. These classes offer progressively lower storage costs in exchange for stricter access restrictions, making them suitable for data with different access frequencies.
Objects inherit the storage class of the bucket by default. Although you cannot change the storage class of a bucket after it is created, you can use lifecycle rules to automatically transition objects to different storage classes to optimize costs.
-
Standard
Suitable for active data where a single file is accessed more than once a month. It supports real-time access. Use Standard if you are unsure about the data access frequency. You can later use lifecycle rules to automatically transition objects to a lower-cost storage class.
-
Infrequent Access (IA)
Suitable for warm data where a single file is accessed once a month or less, such as backup files and operation logs. It supports real-time access but has a minimum storage duration of 30 days. If you delete an object before 30 days have passed, you are still charged for 30 days of storage. This storage class is not suitable for temporary or test data.
-
Archive
Suitable for cold data where a single file is accessed less than once every 90 days. It supports real-time access through Archive Direct Read. Alternatively, you can restore the object before reading it. Restoration takes about 1 minute. This storage class has a minimum storage duration of 60 days.
Restore: The process of making an object in an archive storage class temporarily available for reading.
-
Cold Archive
Suitable for data where a single file is accessed less than once a year. You must restore the data before you can read it. Restoration takes 1 to 12 hours. This class has lower costs and a minimum storage duration of 180 days.
-
Deep Cold Archive
As the lowest-cost option, it is suitable for data where a single file is accessed less than once a year. Restoration takes 12 or 48 hours. It has a minimum storage duration of 180 days. Creating a bucket with this storage class is not recommended. We recommend that you use lifecycle rules to automatically transition data to this class.
Console
When you create a bucket, configure the storage class based on your requirements.
ossutil
The following command creates a bucket named examplebucket with the Infrequent Access (IA) storage class.
ossutil mb oss://examplebucket --storage-class IA
For more information about this command, see mb (create a bucket).
OSS SDK
The following code samples show how to create a bucket using common SDKs. For code samples for other SDKs, see SDK introduction.
Java
To set the storage class, configure the CreateBucketRequest object.
// Create a request and specify the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setStorageClass(StorageClass.IA); // Specify the storage class here.
// Available options: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
For a complete example, see Create a bucket (Java SDK V1).
Python
When you call the client.put_bucket method, specify the storage class by using the create_bucket_configuration parameter.
// Create a request and specify the storage class.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='IA' # Specify the storage class here.
)
)
# Available options: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
For a complete example, see Create a bucket (Python SDK V2).
Go
To set the storage class, configure the CreateBucketConfiguration field when you create a PutBucketRequest object.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
StorageClass: oss.StorageClassIA, // Specify the storage class here.
},
}
// Available options: oss.StorageClassStandard, oss.StorageClassIA, oss.StorageClassArchive, etc.
For a complete example, see Create a bucket (Go SDK V2).
PHP
To set the storage class, pass a CreateBucketConfiguration object to the constructor when you create a PutBucketRequest object.
// Create a request and specify the storage class.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA', // Specify the storage class here.
)
);
/*
* Available storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
*/
For a complete example, see Create a bucket (PHP SDK V2).
C#
To set the storage class, create a CreateBucketRequest object and configure its properties.
// Create a request and specify the storage class.
var request = new CreateBucketRequest("your-bucket-name");
request.StorageClass = StorageClass.IA; // Specify the storage class here.
// Available storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
For a complete example, see Create a bucket (C# SDK V1).
Node.js
To set the storage class, create an options object and pass it to the putBucket method.
// Create an options object and specify the storage class.
const options = {
storageClass: 'IA', // Specify the storage class here.
};
// Available storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
For a complete example, see Create a bucket (Node.js SDK).
Android
To set the storage class or access permissions, create and configure a CreateBucketRequest object.
// Create a request and specify the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketStorageClass(StorageClass.IA); // Specify the storage class here.
// Available storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
For a complete example, see Create a bucket (Android SDK).
iOS
To set the storage class, create an OSSCreateBucketRequest object and configure its properties.
// Create a request and specify the storage class.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.storageClass = OSSBucketStorageClassIA; // Specify the storage class here.
// Available storage classes: OSSBucketStorageClassStandard, OSSBucketStorageClassIA, etc.
For a complete example, see Create a bucket (iOS SDK).
API
When you call PutBucket, specify the storage class of the bucket in the StorageClass request element.
Storage redundancy type
The storage redundancy type determines the disaster recovery capabilities for your data, which affects its durability and availability. The default type is zone-redundant storage (ZRS). You can upgrade from locally redundant storage (LRS) to ZRS, but you cannot downgrade.
-
Zone-redundant storage (ZRS) - Recommended for production environments
This option stores your data across multiple zones (AZs) in the same region. This design provides higher data durability and service availability, ensuring continuous access even if an entire zone fails.
-
Locally redundant storage (LRS) - Suitable for non-critical or test data
This option stores your data redundantly within a single zone at a lower cost. It withstands hardware failures but cannot guarantee data access if an entire zone becomes unavailable.
Console
When you create a bucket, you can select its storage redundancy type in the Basic Information section.
ossutil
The following command creates a bucket named examplebucket with the LRS redundancy type.
ossutil mb oss://examplebucket --redundancy-type LRS
For more details, see mb (create a bucket).
OSS SDK
Java
To set the storage redundancy type, configure the CreateBucketRequest object as follows.
// Create a bucket request and set the redundancy type.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS); // Specify the storage redundancy type here.
// Available options: DataRedundancyType.ZRS, DataRedundancyType.LRS
For a complete example, see Create a bucket (Java SDK V1).
Python
When you call the client.put_bucket method, specify the storage redundancy type with the create_bucket_configuration parameter.
# Create a request object and set the storage redundancy type.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
data_redundancy_type='ZRS' # Specify the storage redundancy type here.
)
)
# Available options: 'ZRS', 'LRS'
For a complete example, see Create a bucket (Python SDK V2).
Go
To set the storage redundancy type, configure the CreateBucketConfiguration field when you create a PutBucketRequest object.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
DataRedundancyType: oss.DataRedundancyZRS, // Specify the storage redundancy type here.
},
}
// Available options: oss.DataRedundancyZRS, oss.DataRedundancyLRS
For a complete example, see Create a bucket (Go SDK V2).
PHP
To set the storage redundancy type, pass a CreateBucketConfiguration object to the constructor when you create a PutBucketRequest object.
// Create a request object and set the storage redundancy type.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
null, // storageClass
'ZRS' // Specify the storage redundancy type here.
)
);
/*
* Available storage redundancy types: 'ZRS', 'LRS'
*/
For a complete example, see Create a bucket (PHP SDK V2).
C#
To set the storage redundancy type, create a CreateBucketRequest object and configure its properties as follows.
// Create a request object and set the storage redundancy type.
var request = new CreateBucketRequest("your-bucket-name");
request.DataRedundancyType = DataRedundancyType.ZRS; // Specify the storage redundancy type here.
// Available storage redundancy types: DataRedundancyType.ZRS, DataRedundancyType.LRS
For a complete example, see Create a bucket (C# SDK V1).
Node.js
To set the storage redundancy type, create an options object and pass it to the putBucket method.
// Create an options object and set the storage redundancy type.
const options = {
dataRedundancyType: 'LRS', // Specify the storage redundancy type here.
};
// Available storage redundancy types: 'ZRS', 'LRS'
For a complete example, see Create a bucket (Node.js SDK).
API
When you call PutBucket, specify the bucket's storage redundancy type in the DataRedundancyType request element.
Access control list (ACL)
The access control list (ACL) controls a bucket's anonymous access policy. The default permission is private, which you can change after the bucket is created. By default, objects inherit the bucket's access permissions. You can also set permissions for individual objects.
-
private - Strongly recommended
This is the default and most secure setting. Only the bucket owner and users granted permissions through a RAM policy or bucket policy can access the bucket. To grant access to other users, see Permission and Access Control Overview.
-
public-read - Use with caution
No authentication is required. Anyone, including anonymous visitors, can read objects but cannot write to them.
-
This setting makes your data public, which can result in unexpected outbound traffic fees. This setting is suitable for scenarios that require public sharing, such as hosting static website assets.
-
If you must enable public-read, configure hotlink protection to allow access only from specific sources, such as your website domain, to prevent unauthorized hotlinking.
-
-
public-read-write - Strongly discouraged
Anyone can read, write, and even delete objects in the bucket. This poses an extremely high security risk and can lead to substantial fees. Use this setting only for special scenarios, such as public resource repositories, and never for general purposes.
OSS console
For security reasons, the OSS console enables Block Public Access by default and supports creating only private buckets.
To change the ACL to Public Read or Public Read/Write, follow these steps:
-
Click the name of the target bucket.
-
In the left navigation pane, choose Permission Control > Block Public Access and disable the policy.
-
Navigate to the ACL tab and click Set.
-
Follow the on-screen instructions to change the bucket ACL to Public Read or Public Read/Write.
Ossutil
This command creates a bucket named examplebucket and sets its ACL to private.
ossutil mb oss://examplebucket --acl=private
For more information about this command, see mb (create bucket).
OSS SDK
Java
Set access permissions by configuring the CreateBucketRequest object as follows.
// Prepare a request object that contains the access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setCannedACL(CannedAccessControlList.Private); // Specify the bucket ACL here.
// Optional values: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
For a complete example, see Create a bucket (Java SDK V1).
Python
Specify access permissions in the client.put_bucket method with thecreate_bucket_configuration parameter.
# Prepare a request object that contains the access permissions.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
access_control_policy='private' # Specify the access permissions here.
)
)
# Optional values: 'private', 'public-read','public-read-write'
For a complete example, see Create a bucket (Python SDK V2).
Go
To set the access permissions, configure theAcl field when you create a PutBucketRequest.
// Prepare a request object that contains configurations such as access permissions.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
Acl: oss.BucketACLPrivate, // Specify the access permissions here.
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
},
}
// Optional values: oss.BucketACLPrivate, oss.BucketACLPublicRead, oss.BucketACLPublicReadWrite
For a complete example, see Create a bucket (Go SDK V2).
PHP
To set access permissions, pass the value for Acl as the second parameter when creating a PutBucketRequest object.
// Prepare a request object that contains configurations such as access permissions.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
'private', // Specify the access permissions here (second parameter).
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA', // Specify the storage class here.
'ZRS' // Specify the redundancy type here.
)
);
/*
* Optional values: 'private', 'public-read', 'public-read-write'
*/
For a complete example, see Create a bucket (PHP SDK V2).
C#
To set access permissions, create and configure aCreateBucketRequest object as follows.
// Prepare a request object that contains the access permission configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.ACL = CannedAccessControlList.Private; // Specify the access permissions here.
// Optional values: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
For a complete example, see Create a bucket (C# SDK V1).
Node.js
To set the access permissions, create anoptions object and pass it to the putBucket method.
// Prepare an options object that contains the access permissions.
const options = {
acl: 'private', // Specify the access permissions here.
};
// Optional values: 'private', 'public-read','public-read-write'
For a complete example, see Create a bucket (Node.js SDK).
Android
To set the access permissions, create and configure aCreateBucketRequest object as follows.
// Prepare a request object that contains configurations such as access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketACL(CannedAccessControlList.Private); // Specify the access permissions here.
// Optional values: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
For a complete example, see Create a bucket (Android SDK).
iOS
To set the access permissions, create anOSSCreateBucketRequest object and configure its properties as follows.
// Prepare a request object that contains configurations such as access permissions.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.xOssACL = @"private"; // Specify the access permissions here.
// Optional values: @"private", @"public-read", @"public-read-write", etc.
For a complete example, see Create a bucket (iOS SDK).
API
When you call the PutBucket operation, specify the bucket ACL in the x-oss-acl request header.
Block public access
This global security setting prevents accidental public data exposure from incorrect ACL or bucket policy configurations.
When enabled, you can create only private buckets. You cannot set public-read or public-read-write ACLs, or apply bucket policies that grant public access. By default, OSS enables Block Public Access when you create a bucket. If your business requires public access, you can manually disable this feature after the bucket is created. However, for security reasons, we recommend keeping this feature enabled.
Optional features
You can configure these features during or after bucket creation.
-
Versioning
Versioning protects your data from accidental deletion or overwrites. When you upload an object with the same name as an existing one, OSS automatically creates a new version instead of overwriting the original. You can restore a previous version with a single click to recover from accidental operations. For more information, see versioning.
-
Server-side encryption
Server-side encryption automatically encrypts data at rest. OSS encrypts data when written and decrypts it when read. We recommend that you enable at least the "Fully managed by OSS" option. For more information, see server-side encryption.
-
Resource group
Resource groups are ideal for multi-team collaboration. You can group buckets by department or project to enable independent access control and cost accounting. For more information, see Use resource groups.
-
Real-time log query
When enabled, you can quickly query and analyze access logs in the console to troubleshoot unusual access, perform user behavior analysis, and identify who accessed which objects and when. For more information, see real-time log query.
-
Scheduled backup
Scheduled backup automates data backups. For more information, see Configure scheduled backup for a bucket.
-
OSS-HDFS
Ideal for data lake scenarios, OSS-HDFS allows big data frameworks like Spark to directly analyze OSS data without migration. For more information, see What is the OSS-HDFS service?.
-
Bucket tagging
Bucket tagging facilitates batch management and cost analysis. You can classify buckets by using key-value tags, such as
department:research. For more information, see Manage bucket tags.
Billing
Creating a bucket is free. You are charged based on usage after you store data in the bucket. To avoid unnecessary fees, consider the following when you configure your bucket:
-
Match resource plans with storage redundancy types
The type of your resource plan must exactly match the storage redundancy type of your bucket. For example, an LRS resource plan cannot be used to offset the costs of a ZRS bucket, and vice versa. Make sure to confirm your selection during creation. -
Special billing for non-Standard storage classes
Although the Infrequent Access, Archive, Cold Archive, and Deep Cold Archive storage classes have lower storage costs, they have a minimum storage duration and incur data retrieval fees.-
Early deletion or modification: If an object is deleted or modified before its minimum storage duration expires, OSS still charges storage fees for the remaining duration.
-
Data reads: Except for the Standard storage class, accessing data in any other storage class incurs additional data retrieval fees.
-
-
Risks of public access
If you set the ACL to public-read or public-read-write, you expose your data to the Internet. This can attract malicious traffic, resulting in unexpectedly high traffic fees.