Create a zone-redundant storage bucket

Updated at:
Copy as MD

OSS zone-redundant storage (ZRS) provides 99.9999999999% (12 nines) data durability. In multi-zone regions, OSS distributes redundant copies across availability zones in the same region, ensuring continuous data access during zone failures for data center-level disaster recovery.

Notes

  • Supported regions, data durability, and service availability are listed in Storage redundancy.

  • ZRS incurs higher storage costs than locally redundant storage. For more information, see Object Storage Service pricing.

  • After you enable ZRS for a bucket, you cannot disable it.

Procedure

Use the OSS console

  1. Log on to the OSS console.

  2. In the left navigation pane, click Buckets and then click Create Bucket.

  3. In the Create Bucket panel, set Redundancy Type to ZRS (Recommended) and configure the other parameters.

    Other parameters are described in Create a bucket.

Use Alibaba Cloud SDKs

The following examples create a ZRS bucket using popular SDKs. Additional SDKs are listed in 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();
            }
        }
    }
}
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")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
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 arguments.

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    cfg.region = args.region
    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the configured information.
    client = oss.Client(cfg)

    # Send a request to create a bucket. The storage class is Standard.
    result = client.put_bucket(oss.PutBucketRequest(
        bucket=args.bucket,
        create_bucket_configuration=oss.CreateBucketConfiguration(
            storage_class='Standard',
           data_redundancy_type='ZRS'
        )
    ))
    # Print the status code and request ID to verify whether the request succeeded.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id}'
    )


if __name__ == "__main__":
    main()  # The entry point of the script. The main function is called when the file is run directly.
using Aliyun.OSS;
using Aliyun.OSS.Common;

// 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.
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 bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, if the bucket is 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 as needed.
var conf = new ClientConfiguration();

// Use Signature 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) to public-read. The default ACL is private.
        request.ACL = CannedAccessControlList.PublicRead;
        // Set the data disaster recovery type to zone-redundant storage.
        request.DataRedundancyType = DataRedundancyType.ZRS;
        client.CreateBucket(request);
        Console.WriteLine("Create bucket succeeded");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create bucket failed. {0}", ex.Message);
    }
#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;
}
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(&region, "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 whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether 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 a 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 (Zone-Redundant Storage).
		},
	}

	// Send the request to create the bucket.
	result, err := client.PutBucket(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to create bucket: %v", err) // Handle the error and stop the program.
	}

	// Print the result of creating the bucket.
	log.Printf("put bucket result: %#v\n", result)
}

Use ossutil

To create a ZRS bucket with ossutil, run the put-bucket command.

Use a REST API

For custom requirements, call the REST API directly. Manual signature calculation is required. PutBucket.