Todos os produtos
Search
Central de documentação

NAT Gateway:CreateNatGateway

Última atualização: Jun 29, 2026

Cria um gateway NAT público aprimorado ou um gateway NAT de VPC.

Descrição da operação

Antes de chamar esta operação, observe o seguinte:

  • Ao criar um gateway NAT pela primeira vez, uma função vinculada ao serviço chamada AliyunServiceRoleForNatgw é criada automaticamente. Uma política de permissão chamada AliyunServiceRolePolicyForNatgw é anexada a essa função para permitir que o gateway NAT acesse outros recursos da nuvem. Para obter mais informações, consulte Funções vinculadas ao serviço.

  • Após a criação de um gateway NAT público aprimorado, o sistema adiciona automaticamente uma entrada de rota à tabela de rotas da VPC para rotear o tráfego para o gateway NAT. Essa entrada define o bloco CIDR de destino como 0.0.0.0/0 e o próximo salto como o gateway NAT.

  • A operação CreateNatGateway é assíncrona. Após o envio de uma solicitação, o sistema retorna o ID da instância do gateway NAT (público ou de VPC) enquanto a tarefa de criação é executada em segundo plano. Chame a operação DescribeNatGateways para consultar o status do gateway NAT.

    • O status Creating indica que o gateway NAT está sendo criado. Você pode realizar apenas operações de consulta.

    • O status Available indica que o gateway NAT foi criado.

A criação de um gateway NAT leva de 1 a 3 minutos.

Experimente agora

Experimente esta API no OpenAPI Explorer, sem necessidade de assinatura manual. Chamadas bem-sucedidas geram automaticamente código SDK correspondente aos seus parâmetros. Faça o download com segurança de credenciais integrada para uso local.

Testar

Autorização RAM

A tabela abaixo descreve a autorização necessária para chamar esta API. Você pode defini-la em uma política do Resource Access Management (RAM). As colunas da tabela estão detalhadas abaixo:

  • Ação: As ações que podem ser usadas no elemento Action das instruções de política de permissão do RAM para conceder permissões para executar a operação.

  • API: A API que você pode chamar para executar a ação.

  • Nível de acesso: O nível de acesso predefinido concedido para cada API. Valores válidos: create, list, get, update e delete.

  • Tipo de recurso: O tipo de recurso que suporta autorização para executar a ação. Indica se a ação suporta permissão em nível de recurso. O recurso especificado deve ser compatível com a ação. Caso contrário, a política será ineficaz.

    • Para APIs com permissões em nível de recurso, os tipos de recursos obrigatórios são marcados com um asterisco (*). Especifique o Nome de Recurso Alibaba Cloud (ARN) correspondente no elemento Resource da política.

    • Para APIs sem permissões em nível de recurso, é exibido como Todos os Recursos. Use um asterisco (*) no elemento Resource da política.

  • Chave de condição: As chaves de condição definidas pelo serviço. A chave permite controle granular, aplicando-se somente a ações ou a ações associadas a recursos específicos. Além das chaves de condição específicas do serviço, o Alibaba Cloud fornece um conjunto de chaves de condição comuns aplicáveis a todos os serviços compatíveis com RAM.

  • Ação dependente: As ações dependentes necessárias para executar a ação. Para concluir a ação, o usuário RAM ou a função RAM deve ter permissões para executar todas as ações dependentes.

Ação

Nível de acesso

Tipo de recurso

Chave de condição

Ação dependente

vpc:CreateNatGateway

create

*NatGateway

acs:vpc:{#regionId}:{#accountId}:natgateway/*

Nenhuma Nenhuma

Parâmetros da solicitação

Parâmetro

Tipo

Obrigatório

Descrição

Exemplo

RegionId

string

Sim

O ID da região na qual o gateway NAT será criado.

Chame a operação DescribeRegions para obter o ID da região.

cn-hangzhou

VpcId

string

Sim

O ID da nuvem privada virtual (VPC) na qual você deseja criar o gateway NAT.

vpc-bp1di7uewzmtvfuq8****

Name

string

Não

O nome do gateway NAT.

Deve ter de 2 a 128 caracteres, começar com uma letra ou um caractere chinês e pode conter dígitos, sublinhados (_) e hifens (-).

Se você não especificar este parâmetro, o sistema especificará automaticamente um nome para o gateway NAT.

fortest

Description

string

Não

A descrição do gateway NAT.

A descrição deve ter de 2 a 256 caracteres. Não pode começar com http:// ou https://.

testnat

ClientToken

string

Não

O token de cliente usado para garantir a idempotência da solicitação.

Você pode criar o token, mas deve garantir que ele seja exclusivo entre diferentes solicitações.

Nota

Se você não especificar este parâmetro, o sistema usará automaticamente o ID da solicitação como o token de cliente. O ID da solicitação pode ser diferente para cada solicitação.

5A2CFF0E-5718-45B5-9D4D-70B3FF3898

Spec

string

Não

Os gateways NAT públicos baseados em assinatura não estão mais disponíveis para compra. Este parâmetro foi descontinuado.

无效参数

InstanceChargeType

string

Não

O método de cobrança do gateway NAT. Defina o valor como:

PostPaid (padrão): pós-pago.

Para obter mais informações, consulte Cobrança de gateways NAT públicos e Cobrança de gateways NAT de VPC.

PostPaid

PricingCycle

string

Não

Os gateways NAT públicos baseados em assinatura não estão mais disponíveis para compra. Este parâmetro não é mais utilizado.

无效参数

Duration

string

Não

Os gateways NAT públicos baseados em assinatura não estão mais disponíveis para compra. Este parâmetro foi descontinuado.

无效参数

AutoPay

boolean

Não

Os gateways NAT públicos baseados em assinatura não estão mais disponíveis para compra. Este parâmetro foi descontinuado.

无效参数

VSwitchId

string

Não

O ID do vSwitch ao qual o gateway NAT pertence.

Ao criar um gateway NAT, você deve especificar um vSwitch ao qual o gateway NAT pertence. O sistema então atribui um endereço IP privado ao gateway NAT a partir do vSwitch.

  • Para criar um gateway NAT em um vSwitch existente, certifique-se de que a zona à qual o vSwitch pertence suporte gateways NAT e que o vSwitch tenha endereços IP ociosos.

  • Se você não criou um vSwitch, crie um vSwitch em uma zona que suporte gateways NAT e, em seguida, especifique o vSwitch.

Nota

Chame a operação ListEnhancedNatGatewayAvailableZones para consultar as zonas disponíveis e DescribeVSwitches para consultar o número de endereços IP ociosos em um vSwitch.

vsw-bp1e3se98n9fq8hle****

NatType

string

Não

O tipo de gateway NAT. Defina o valor como Enhanced, que especifica um gateway NAT aprimorado.

Enhanced

InternetChargeType

string

Não

O método de cobrança do gateway NAT. Defina o valor como PayByLcu, que indica que o gateway NAT é um gateway NAT pós-pago e é medido em LCUs.

PayByLcu

NetworkType

string

Não

O tipo do gateway NAT a ser criado. Valores válidos:

  • internet: um gateway NAT público

  • intranet: um gateway NAT de VPC

internet

SecurityProtectionEnabled deprecated

boolean

Não

Especifica se o recurso de firewall deve ser ativado. Valores válidos:

  • false (padrão): desativa o recurso de firewall.

    Importante

    Este parâmetro foi descontinuado.

false

IcmpReplyEnabled

boolean

Não

Especifica se a resposta ICMP deve ser ativada. Valores válidos:

  • true (padrão): ativa a resposta ICMP.

  • false: desativa a resposta ICMP.

true

PrivateLinkEnabled

boolean

Não

Especifica se o PrivateLink deve ser ativado. Valores válidos:

  • true: ativa o PrivateLink.

  • false (padrão): desativa o PrivateLink.

false

EipBindMode

string

Não

O modo no qual o EIP é associado ao gateway NAT. Valores válidos:

  • MULTI_BINDED (padrão): o modo multi-EIP para ENI.

  • NAT: o modo EIP para gateway NAT. Este modo é compatível com gateways IPv4.

    Nota

    Se o EIP for associado ao gateway NAT no modo EIP para gateway NAT, o EIP ocupará um endereço IP privado do vSwitch ao qual o gateway NAT pertence. Certifique-se de que o vSwitch tenha endereços IP privados suficientes. Caso contrário, a associação do EIP falhará. No modo EIP para gateway NAT, um gateway NAT pode ser associado a até 50 EIPs.

MULTI_BINDED

Tag

array<object>

Não

As tags.

MULTI_BINDED

object

Não

Key

string

Não

A chave da tag. Você pode especificar até 20 chaves de tag. A chave da tag não pode ser uma string vazia. A chave da tag deve ter de 1 a 128 caracteres e não pode começar com aliyun ou acs:. A chave da tag não pode conter http:// ou https://.

TestKey

Value

string

Não

O valor da tag. Você pode especificar até 20 valores de tag. O valor da tag pode ser uma string vazia. O valor da tag deve ter de 0 a 128 caracteres e não pode começar com aliyun ou acs:. Não pode conter http:// ou https://.

TestValue

AccessMode

object

Não

O modo de acesso do gateway NAT de VPC para acesso reverso ao endpoint.

MULTI_BINDED

ModeValue

string

Não

O modo de acesso. Valores válidos:

  • route

  • tunnel

Nota

Este parâmetro é válido apenas quando PrivateLinkEnabled está definido como true.

route

TunnelType

string

Não

O tipo de túnel. Valor válido:

  • geneve: Geneve.

Nota

Este parâmetro é válido apenas quando o modo de acesso é tunnel.

geneve

NatIp

string

Não

O endereço IP privado do gateway NAT. Use um endereço IP ocioso do bloco CIDR do vSwitch ao qual o gateway NAT pertence. Se este parâmetro for deixado vazio, um endereço IP será atribuído aleatoriamente.

192.168.0.2

Ipv4Prefix

string

Não

O prefixo do endereço IP. Os endereços IP do NAT são criados a partir do prefixo. Use um bloco CIDR reservado que não esteja alocado no vSwitch ao qual o gateway NAT pertence.

192.168.0.0/28

AvailabilityMode

string

Não

Elementos de resposta

Elemento

Tipo

Descrição

Exemplo

object

O corpo da resposta.

NatGatewayId

string

O ID da instância do gateway NAT.

ngw-112za33e4****

RequestId

string

O ID da solicitação.

2315DEB7-5E92-423A-91F7-4C1EC9AD97C3

ForwardTableIds

object

ForwardTableId

array

A lista DNAT.

string

O ID de uma tabela de encaminhamento DNAT.

ftb-11tc6xgmv****

SnatTableIds

object

SnatTableId

array

A lista SNAT.

string

O ID de uma tabela SNAT.

stb-SnatTableIds****

FullNatTableIds

object

FullNatTableId

array

A lista FULLNAT.

string

O ID de uma tabela FULLNAT.

fulltb-gw88z7hhlv43rmb26****

Exemplos

Resposta de sucesso

JSON formato

{
  "NatGatewayId": "ngw-112za33e4****",
  "RequestId": "2315DEB7-5E92-423A-91F7-4C1EC9AD97C3",
  "ForwardTableIds": {
    "ForwardTableId": [
      "ftb-11tc6xgmv****"
    ]
  },
  "SnatTableIds": {
    "SnatTableId": [
      "stb-SnatTableIds****"
    ]
  },
  "FullNatTableIds": {
    "FullNatTableId": [
      "fulltb-gw88z7hhlv43rmb26****"
    ]
  }
}

Códigos de erro

Código de status HTTP

Código de erro

Mensagem de erro

Descrição

400 Forbidden.NatPayBySpec Pay-by-specification NAT is no longer supported. Newly purchased pay-as-you-go NAT gateways only support the pay-by-CU metering method. Pay-by-specification NAT gateways are no longer available for purchase. Set InternetChargeType to PayByLcu.
400 DependencyViolation.FullNatEntry The specified resource of %s depends on %s, so the operation cannot be completed.
400 UnsupportedFeature.InternetChargeType The feature of InternetChargeType is not supported.
400 InvalidVPCStatus vpc incorrect status.
400 InvalidNatGatewayName.MalFormed NatGateway name is not valid.
400 InvalidNatGatewayDescription.MalFormed NatGateway description is not valid.
400 MissingParameter.BandwidthPackage only support one BandwidthPackage be created with NatGateway.
400 OperationDenied The user cannot allow to create natgw, please call PD to authorize
400 RouterEntryConflict.Duplicated A route entry already exists, which CIDR is '0.0.0.0/0'
400 MissingParameter Miss mandatory parameter.
400 QuotaExceeded.BandwidthPackageIps The specified ipCount exceeded quota. The number of IP addresses has reached the upper limit. Request a quota increase on the Quota Management page.
400 AllocateIpFailed Alloc bandwidthPackage ips failed, maybe no available ip.
400 InvalidParameter.Name.Malformed The specified Name is not valid.
400 InvalidParameter.Description.Malformed The specified Description is not valid.
400 ZONE_NO_AVAILABLE_IP The Zone have no available ip.
400 ParameterIllegal ipCount,bandwidth parameter invalid
400 InvalidParameter.BandwidthPackage.n.ISP.ValueNotSupport The specified ISP of BandwidthPackage is not valid.
400 InvalidNatGatewayId.NotFound The NatGatewayId not exist.
400 VpcStatusError The Vpc is creating .
400 InvalidParameter.Spec.ValueNotSupported The specified Spec is not valid.
400 TaskConflict The operation is too frequent, TaskConflict. The system is unavailable. Try again later.
400 COMMODITY.INVALID_COMPONENT The instance component is invalid. The instance component is invalid.
400 CreateNatGateway.RouteConflict.DynamicRoute Route conflict exists in routing table.
400 OperationUnsupported.MultiNatGateway More than one natGateway per vpc is unsupported.
400 Forbidden.CheckEntryRuleQuota Route entry quota rule check error.
400 OperationFailed.UnpaidBillsExist The account has unpaid bills. Please pay your overdue bill first. This account has unpaid orders.
400 IncorrectStatus.RouteEntry Specified routeEntry status error.
400 OperationFailed.RiskControl Risk control check failed. The error message returned because your payment method has security risks. Click the link for verification in your email or console message and submit your order after verification.
400 OperationFailed.TokenVerfiy Token verify failed.
400 IllegalParam.Name The specified Name is invalid, shorter than 2 characters.
400 OperationFailed.EnhancedQuotaExceed Enhanced nat gateway per vpc quota is exceeded
400 NoPermission.CreateServiceLinkedRole You are not authorized to create service linked role
400 OperationFailed.EnhancedInventoryNotEnough Operation failed because inventory is not enough.
400 OperationFailed.VswNotBelongToVpc Operation failed because the specified VSwitch is not bound to the same VPC with NAT gateway. The vSwitch and NAT gateway do not belong to the same VPC.
400 OperationFailed.EnhancedUserIsUnAuthorized Operation failed because the user is not authorized to create an enhanced NAT gateway. Operation failed because the user is not authorized to create an enhanced NAT gateway.
400 OperationUnsupported.PrePaidPyByLcu The operation failed because the subscription NAT gateway does not support the pay-by-LCU billing method. The operation failed because the subscription NAT gateway does not support the pay-by-LCU billing method.
400 OperationFailed.NormalInventoryNotEnough Standard NAT gateways are no longer offered. You can create enhanced NAT gateways and set the correct natType.
400 OperationFailed.VSwitchNoAvailableIp Operation failed because the specified vswitch does not have availabe ip.
400 UnsupportedFeature.IcmpReplyEnabled The feature of IcmpReplyEnabled is not supported. The value of IcmpReplyEnabled cannot be modified.
400 UnsupportedFeature.SecurityProtectionEnabled The feature of SecurityProtectionEnabled is not supported.
400 OperationFailed.RegionConvert Operation failed because do not find region info.
400 UnsupportedFeature.VpcNat The feature of VpcNat is not supported.
400 InvalidVSWITCHID.NotFound The specified resource of %s is not found.
400 Forbidden.OperateShareResource Operate share resource is forbidden.
400 IncorrectStatus.VSWITCH The status of VSWITCH is incorrect.
400 OperationFailed.VpcNatGatewayInventoryNotEnough The operation is failed because of inventory is not enough.
400 OperationFailed.VpcNatGatewayCheckInventory The operation is failed because of check inventory result is unexpected
400 ExclusiveParam.%sAnd%s The param of %s and %s are mutually exclusive. You cannot specify %s and %s at the same time.
400 SecurityGroupType.NotSupported The specified security group type is not supported. The security group is already hosted and cannot be used.
400 SecurityGroup.NotExist The specified security group is not exist. The security group does not exist in this VPC.
400 OperationFailed.ContainForbiddenLabel There is a label that prohibits ordering, please contact your distributor for processing. There is a label that prohibits ordering, please contact your distributor for processing.
400 OperationDenied.PrePaidInstance The operation is not allowed because prepaid instance is no longer supported. Prepaid instance is no longer supported.
400 UnsupportedFeature.Geneve The feature of Geneve is not supported. The feature of Geneve is not supported.
400 OperationFailed.NoAvailableResource The Zone have no available resource. No resources are available in the region.
400 ExclusiveParam.AccessModeValueAndAccessTunnelType The specified param AccessModeValue and AccessTunnelType are mutually exclusive. The specified input AccessMode.ModeValue and AccessMode.TunnelType conflict
400 ExclusiveParam.PrivateLinkModeAndAccessMode The specified param PrivateLinkMode and AccessMode are mutually exclusive. The specified input PrivateLinkMode conflicts with the AccessMode.
400 ExclusiveParam.PrivateLinkEnabledAndAccessMode The specified paramPrivateLinkEnabled and AccessMode are mutually exclusive. The specified input PrivateLinkEnabled conflicts with the AccessMode.
400 UnsupportedFeature.AccessModeValue The feature of AccessMode.ModeValue(%s) is not supported. This operation is not supported for the VPC NAT AccessMode.ModeValue attribute
400 IllegalParam.AccessTunnelType The request parameter AccessMode.TunnelType is illegal. The request parameter AccessMode.TunnelType is illegal.
400 IllegalParam.AccessModeValue The request parameter AccessMode.ModeValue is illegal. The request parameter AccessMode.ModeValue is illegal.
400 OperationFailed.VSwitchStatusError The vSwitch is creating . The vSwitch is being created.
400 UnsupportedFeature.PrivateLinkMode The feature of %s is not supported. The feature of reverse access is not supported.
400 OperationFailed.EcsNetworkInterfaceQuotaNotSatisfy ECS network interface quota is not satisfy. The ECS ENI quota does not meet the requirements.
400 OperationFailed.NoNameAuthentication You have not passed the real name authentication and do not meet the purchase conditions. Please log in to the user center for real-name authentication. You have not passed the real name authentication and do not meet the purchase conditions. Please log in to the user center for real-name authentication.
400 Mismatch.NatIpAndNatIpCidr The %s and %s are mismatched. The specified %s and %s do not match.
400 Mismatch.Ipv4PrefixAndNatIpCidr The %s and %s are mismatched.
400 ResourceAlreadyExist.NatIp The specified resource of NatIp has already exist. Configured NatIp already exists
400 Mismatch.Ipv4PrefixAndCidrReservations The %s and %s are mismatched. The reserved network segments of the Ipv4Prefix and VSwitch do not match.
400 ResourceAlreadyAssociated.Ipv4Prefix %s is already associated. Ipv4Prefix have been allocated.
400 ResourceNotEnough.Ipv4Prefix The resource of %s is not enough. Insufficient Ipv4Prefix resources.
400 ResourceNotFound.Ipv4Prefix The resource of s% is not found. The resource Ipv4Prefix does not exist.
400 ResourceAlreadyAssociated.NatIp The resource of %s was already associated. NatIp resources have been allocated.
400 ResourceNotEnough.NatIp The specified resource of NatIp is not enough. Insufficient IP addresses in the specified CIDR block.
400 ResourceNotFound.NatIp The specified resource of %s is not found. The specified NatIp parameter is not found.
400 IllegalParam.Ipv4Prefix The param of %s is illegal, must be /28 network segment. The parameter Ipv4Prefix is invalid and must be/28 network segment.
400 IllegalParam.NatIp The param of %s is illegal. The parameter NatIp is illegal.
400 OperationUnsupported.EnhancedRegion Region not support. The current region is temporarily not supported.
400 IncorrectStatus.RouteTableStatus The route table status is invaild. Please try again later. The routing table status does not support this operation. Please try again later.
400 OperationUnsupported.User The current user does not support this operation. The current user does not support this operation.
400 OperationUnsupported.EnhancedCURegion Operation failed because of this region not unsupported. Operation failed due to unsupported pay-as-you-go region
400 OrderError.NoAvailablePaymentMethod Order payment parameter is not available. Order error. The payment type parameter is not available.
400 OrderError.BasicInfoUncompleted Order basic parameter is not completed. Order error, basic parameter information incomplete.
400 OperationUnsupported.Region Operation unsupport this region parameter. This operation does not support the region parameter
400 InvalidParameter.SingleZone Operation failed because current user not support create single zone nat. current user is not allowed to create a single az nat
500 OrderError.NatGateway The Account failed to create order.
500 OperationFailed.AccessTunnelId AccessTunnelId param do operation failed. VPC NAT failed to generate tunnel ID. Try again later
500 OperationFailed.EnhancedCheckInventory The NAT gateway in the current zone is not in service, or the resource inventory is insufficient. The NAT gateway in the current zone is not in service, or the resource inventory is insufficient.
404 InvalidRegionId.NotFound The specified RegionId does not exist in our records.
404 InvalidVpcId.NotFound Specified value of VpcId is not found in our record. The VPC does not exist. Check whether the specified VPC is valid.
404 InvalidZoneId.NotFound Specified value of ZoneId is not exists.
404 VPC_ONLY_CAN_CREATE_ONE_NAT_GATEWAY NatGateway in one vpc support only one.
404 OperationFailed.CrateEntryTimeOut Operation failed because create custom routeEntry timeout.
404 Forbidden.CreateSpecialSpecNatGateway You are not authorized to create special spec nat gateway.
404 UnsupportedZoneForFwNat The zone is unsupported for FW NAT.

Consulte Códigos de Erro para uma lista completa.

Notas de versão

Consulte Notas de Versão para uma lista completa.