Object Storage Service (OSS) zone-redundant storage (ZRS) provides 99.9999999999% (12 nines) of data durability. In regions that support multiple zones, OSS uses a multi-zone data redundancy mechanism to store data redundantly across three or more zones within the same region. This cross-zone data distribution ensures that data remains accessible and provides data center-level disaster recovery if a zone fails. This topic describes how to create a ZRS bucket.
Notes
ZRS buckets in the China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Hong Kong), Japan (Tokyo), Singapore, Indonesia (Jakarta), Malaysia (Kuala Lumpur), and Germany (Frankfurt) regions use a multi-zone data redundancy mechanism.
ZRS costs more than locally redundant storage (LRS). For more information, see OSS Pricing.
You cannot disable ZRS after you enable it.
Supported storage classes
ZRS in OSS supports the Standard, Infrequent Access (IA), and Archive Storage storage classes. The following table compares these three storage classes.
Storage class | Region | Data durability | Service availability | Minimum billable size | Minimum storage duration | Data retrieval fees | Data access | Image processing |
Standard | China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Hong Kong), Japan (Tokyo), Singapore, Indonesia (Jakarta), Malaysia (Kuala Lumpur), Germany (Frankfurt) | 99.9999999999% (12 nines) | 99.995% | None | None | None | Real-time access with millisecond latency | Support |
Infrequent Access | China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Hong Kong), Japan (Tokyo), Singapore, Indonesia (Jakarta), Malaysia (Kuala Lumpur), Germany (Frankfurt) | 99.50% | 64 KB | 30 days | Charged based on the amount of data retrieved, in GB | Real-time access with millisecond latency | ||
Archive Storage | 64 KB | 60 days | Charged based on the amount of restored or directly read data, in GB | Data must be restored before you can read it. Restoration takes about one minute. If you enable direct read, you can access data in real time with millisecond latency. |
Procedure
Use the OSS console
Log on to the OSS console.
In the navigation pane on the left, click Buckets. Then, click Create Bucket.
In the Create Bucket panel, set Redundancy Type to ZRS (Recommended) and configure the other parameters.
For more information about the parameters, see Create a bucket.
Use an Alibaba Cloud SDK
The following code provides examples of how to enable ZRS when you create a bucket using common SDKs. For examples that use other SDKs, see 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 {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 the 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 name of the bucket.
String bucketName = "examplebucket";
// Specify the ID of the resource group. If you do not specify a resource group ID, the bucket belongs to the default resource group.
//String rsId = "rg-aek27tc****";
// 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
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 for the bucket.
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
// The following code provides an example on how to specify the storage class, access control list (ACL), and redundancy type when you create the bucket.
// In this example, the storage class of the bucket is Standard.
createBucketRequest.setStorageClass(StorageClass.Standard);
// The default redundancy type of the bucket 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 a 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();
}
}
}
}<?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.
);
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',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourBucketName',
});
// Create the bucket.
async function putBucket() {
try {
const options = {
storageClass: 'Standard', // By default, the storage class of a bucket is Standard. To set the storage class of the bucket to Archive, set storageClass to Archive.
acl: 'private', // By default, the access control list (ACL) of a bucket is private. To set the ACL of the bucket to public read, set acl to public-read.
dataRedundancyType: 'LRS' // By default, the redundancy type of a bucket is locally redundant storage (LRS). To set the redundancy type of the bucket to zone-redundant storage (ZRS), set dataRedundancyType to ZRS.
}
// Specify the name of the bucket.
const result = await client.putBucket('examplebucket', options);
console.log(result);
} catch (err) {
console.log(err);
}
}
putBucket(); 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.using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// 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 cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Create a bucket.
try
{
var request = new CreateBucketRequest(bucketName);
// Set the access control list (ACL) of the bucket to PublicRead. The default value is private.
request.ACL = CannedAccessControlList.PublicRead;
// Set the redundancy type of the bucket 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);
}// Construct a request to create a bucket.
// Specify the name of the bucket.
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) {
// Handle request exceptions.
if (clientException != null) {
// Handle client exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});// 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;
}];
// Implement synchronous blocking to wait for the task to complete.
// [createTask waitUntilFinished]; #include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* 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 cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Specify the name, storage class, and access control list (ACL) of the bucket. */
CreateBucketRequest request(BucketName, StorageClass::IA, CannedAccessControlList::PublicReadWrite);
/* Set the redundancy type of the bucket to zone-redundant storage (ZRS). */
//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 resources, such as network resources. */
ShutdownSdk();
return 0;
}#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* 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 cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
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"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME to access OSS. The value of 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure 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 in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value specifies that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the 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 char* data to a bucket of the aos_string_t type. */
aos_str_set(&bucket, bucket_name);
/* Create the bucket. */
resp_status = oss_create_bucket(oss_client_options, &bucket, oss_acl, &resp_headers);
/* Determine whether the bucket is created. */
if (aos_status_is_ok(resp_status)) {
printf("create bucket succeeded\n");
} else {
printf("create bucket failed\n");
}
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
client.create_bucket('examplebucket')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"
)
// Define command-line arguments.
var (
region string // The region where the bucket is located.
bucketName string // The name of the bucket.
)
// Initialize command-line argument parsing.
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() {
// Parse command-line arguments.
flag.Parse()
// Check if the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Configure the OSS client.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). // Use environment variables to provide access credentials.
WithRegion(region) // Set the region.
// Create an OSS client instance.
client := oss.NewClient(cfg)
// Build the request to create a bucket.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr(bucketName), // Set the bucket name.
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
DataRedundancyType: oss.DataRedundancyZRS, // Set the data redundancy type to ZRS.
},
}
// Send the request to create the bucket.
result, err := client.PutBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket: %v", err) // Handle the error and terminate the program.
}
// Print the result of the bucket creation.
log.Printf("put bucket result: %#v\n", result)
}
Use ossutil
To create a ZRS bucket using ossutil, see put-bucket.
Use the REST API
If your program has high customization requirements, you can directly send REST API requests. This requires you to manually calculate the signature in your code. For more information, see PutBucket.