Skip to content
v2.274.0

NetworkLoadBalancer L2 construct ​

Define a new network load balancer.

Example ​

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
  enablePrefixForIpv6SourceNat: true,
});

const listener = lb.addListener('Listener', {
  port: 1229,
  protocol: elbv2.Protocol.UDP,
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK,
    enable_prefix_for_ipv6_source_nat=True
)

listener = lb.add_listener("Listener",
    port=1229,
    protocol=elbv2.Protocol.UDP
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .enablePrefixForIpv6SourceNat(true)
        .build();

NetworkListener listener = lb.addListener("Listener", BaseNetworkListenerProps.builder()
        .port(1229)
        .protocol(Protocol.UDP)
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    IpAddressType = IpAddressType.DUAL_STACK,
    EnablePrefixForIpv6SourceNat = true
});

var listener = lb.AddListener("Listener", new BaseNetworkListenerProps {
    Port = 1229,
    Protocol = Protocol.UDP
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
	EnablePrefixForIpv6SourceNat: jsii.Boolean(true),
})

listener := lb.AddListener(jsii.String("Listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(1229),
	Protocol: elbv2.Protocol_UDP,
})

Initializer ​

ts
new NetworkLoadBalancer(scope: Construct, id: string, props: NetworkLoadBalancerProps)
python
NetworkLoadBalancer(scope: Construct, id: str, props: NetworkLoadBalancerProps)
java
new NetworkLoadBalancer(Construct scope, String id, NetworkLoadBalancerProps props)
csharp
new NetworkLoadBalancer(Construct scope, string id, NetworkLoadBalancerProps props)
go
NewNetworkLoadBalancer(Scope Construct, Id *string, Props NetworkLoadBalancerProps)

Construct Props ​

clientRoutingPolicyoptionalClientRoutingPolicyclient_routing_policyoptionalClientRoutingPolicyclientRoutingPolicyoptionalClientRoutingPolicyClientRoutingPolicyoptionalClientRoutingPolicyClientRoutingPolicyoptionalClientRoutingPolicy#
The AZ affinity routing policy.

Default: AZ affinity is disabled.

crossZoneEnabledoptionalbooleancross_zone_enabledoptionalboolcrossZoneEnabledoptionalBooleanCrossZoneEnabledoptionalboolCrossZoneEnabledoptional*bool#
Indicates whether cross-zone load balancing is enabled.

Default: false for Network Load Balancers and true for Application Load Balancers. This can not be false for Application Load Balancers.

deletionProtectionoptionalbooleandeletion_protectionoptionalbooldeletionProtectionoptionalBooleanDeletionProtectionoptionalboolDeletionProtectionoptional*bool= false#
Indicates whether deletion protection is enabled.
denyAllIgwTrafficoptionalbooleandeny_all_igw_trafficoptionalbooldenyAllIgwTrafficoptionalBooleanDenyAllIgwTrafficoptionalboolDenyAllIgwTrafficoptional*bool#
Indicates whether the load balancer blocks traffic through the Internet Gateway (IGW).

Default: false for internet-facing load balancers and true for internal load balancers

disableSecurityGroupsoptionalbooleandisable_security_groupsoptionalbooldisableSecurityGroupsoptionalBooleanDisableSecurityGroupsoptionalboolDisableSecurityGroupsoptional*bool= false#
Create a Network Load Balancer without security groups.
notes

When true, creates an NLB that cannot have security groups attached. This is useful when you need to create a traditional NLB without security group associations.

This property only takes effect when the feature flag @aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault is enabled.

enablePrefixForIpv6SourceNatoptionalbooleanenable_prefix_for_ipv6_source_natoptionalboolenablePrefixForIpv6SourceNatoptionalBooleanEnablePrefixForIpv6SourceNatoptionalboolEnablePrefixForIpv6SourceNatoptional*bool#
Indicates whether to use an IPv6 prefix from each subnet for source NAT.

Default: undefined - NLB default behavior is false

The IP address type must be IpAddressType.DUALSTACK.

enforceSecurityGroupInboundRulesOnPrivateLinkTrafficoptionalbooleanenforce_security_group_inbound_rules_on_private_link_trafficoptionalboolenforceSecurityGroupInboundRulesOnPrivateLinkTrafficoptionalBooleanEnforceSecurityGroupInboundRulesOnPrivateLinkTrafficoptionalboolEnforceSecurityGroupInboundRulesOnPrivateLinkTrafficoptional*bool= true#
Indicates whether to evaluate inbound security group rules for traffic sent to a Network Load Balancer through AWS PrivateLink.
internetFacingoptionalbooleaninternet_facingoptionalboolinternetFacingoptionalBooleanInternetFacingoptionalboolInternetFacingoptional*bool= false#
Whether the load balancer has an internet-routable address.
ipAddressTypeoptionalIpAddressTypeip_address_typeoptionalIpAddressTypeipAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressType= IpAddressType.IPV4#
The type of IP addresses to use.

If you want to add a UDP or TCP_UDP listener to the load balancer, you must choose IPv4.

loadBalancerNameoptionalstringload_balancer_nameoptionalstrloadBalancerNameoptionalStringLoadBalancerNameoptionalstringLoadBalancerNameoptional*string#
Name of the load balancer.

Default: Automatically generated name.

minimumCapacityUnitoptionalnumberminimum_capacity_unitoptionalint | floatminimumCapacityUnitoptionalNumberMinimumCapacityUnitoptionaldoubleMinimumCapacityUnitoptional*float64#
The minimum capacity (LCU) for a load balancer.

Default: undefined - ELB default is 0 LCU

securityGroupsoptionalISecurityGroup[]security_groupsoptionaltyping.List[ISecurityGroup]securityGroupsoptionalList<ISecurityGroup>SecurityGroupsoptionalISecurityGroup[]SecurityGroupsoptional*[]ISecurityGroup#
Security groups to associate with this load balancer.

Default: No security groups associated with the load balancer.

subnetMappingsoptionalSubnetMapping[]subnet_mappingsoptionaltyping.List[SubnetMapping]subnetMappingsoptionalList<SubnetMapping>SubnetMappingsoptionalSubnetMapping[]SubnetMappingsoptional*[]SubnetMapping#
Subnet information for the load balancer.

Default: undefined - The VPC default strategy for subnets is used

vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpcrequired#
The VPC network to place the load balancer in.
vpcSubnetsoptionalSubnetSelectionvpc_subnetsoptionalSubnetSelectionvpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelection#
Which subnets place the load balancer in.

Default: the Vpc default strategy.

zonalShiftoptionalbooleanzonal_shiftoptionalboolzonalShiftoptionalBooleanZonalShiftoptionalboolZonalShiftoptional*bool= false#
Indicates whether zonal shift is enabled.

Properties ​

connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
The network connections associated with this resource.
enforceSecurityGroupInboundRulesOnPrivateLinkTrafficmay be undefinedstringenforce_security_group_inbound_rules_on_private_link_trafficmay be undefinedstrenforceSecurityGroupInboundRulesOnPrivateLinkTrafficmay be undefinedStringEnforceSecurityGroupInboundRulesOnPrivateLinkTrafficmay be undefinedstringEnforceSecurityGroupInboundRulesOnPrivateLinkTrafficmay be undefined*string#
Indicates whether to evaluate inbound security group rules for traffic sent to a Network Load Balancer through AWS PrivateLink.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

ipAddressTypemay be undefinedIpAddressTypeip_address_typemay be undefinedIpAddressTypeipAddressTypemay be undefinedIpAddressTypeIpAddressTypemay be undefinedIpAddressTypeIpAddressTypemay be undefinedIpAddressType#
The type of IP addresses to use.
loadBalancerArnstringload_balancer_arnstrloadBalancerArnStringLoadBalancerArnstringLoadBalancerArn*stringrequired#
The ARN of this load balancer.

Example value: arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-internal-load-balancer/50dc6c495c0c9188

loadBalancerCanonicalHostedZoneIdstringload_balancer_canonical_hosted_zone_idstrloadBalancerCanonicalHostedZoneIdStringLoadBalancerCanonicalHostedZoneIdstringLoadBalancerCanonicalHostedZoneId*stringrequired#
The canonical hosted zone ID of this load balancer.

Example value: Z2P70J7EXAMPLE

loadBalancerDnsNamestringload_balancer_dns_namestrloadBalancerDnsNameStringLoadBalancerDnsNamestringLoadBalancerDnsName*stringrequired#
The DNS name of this load balancer.

Example value: my-load-balancer-424835706.us-west-2.elb.amazonaws.com

loadBalancerFullNamestringload_balancer_full_namestrloadBalancerFullNameStringLoadBalancerFullNamestringLoadBalancerFullName*stringrequired#
The full name of this load balancer.

Example value: app/my-load-balancer/50dc6c495c0c9188

loadBalancerNamestringload_balancer_namestrloadBalancerNameStringLoadBalancerNamestringLoadBalancerName*stringrequired#
The name of this load balancer.

Example value: my-load-balancer

loadBalancerRefLoadBalancerReferenceload_balancer_refLoadBalancerReferenceloadBalancerRefLoadBalancerReferenceLoadBalancerRefLoadBalancerReferenceLoadBalancerRefLoadBalancerReferencerequired#
A reference to this load balancer.
loadBalancerSecurityGroupsstring[]load_balancer_security_groupstyping.List[str]loadBalancerSecurityGroupsList<String>LoadBalancerSecurityGroupsstring[]LoadBalancerSecurityGroups*[]*stringrequired#
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
securityGroupsmay be undefinedstring[]security_groupsmay be undefinedtyping.List[str]securityGroupsmay be undefinedList<String>SecurityGroupsmay be undefinedstring[]SecurityGroupsmay be undefined*[]*string#
After the implementation of `IConnectable` (see https://github.com/aws/aws-cdk/pull/28494), the default value for `securityGroups` is set by the `ec2.Connections` constructor to an empty array. To keep backward compatibility (`securityGroups` is `undefined` if the related property is not specified) a getter has been added.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
vpcmay be undefinedIVpcvpcmay be undefinedIVpcvpcmay be undefinedIVpcVpcmay be undefinedIVpcVpcmay be undefinedIVpc#
The VPC this load balancer has been created in.

This property is always defined (not null or undefined) for sub-classes of BaseLoadBalancer.

Methods ​

addListener(id: string, props: BaseNetworkListenerProps): NetworkListenerdef add_listener(self, id: str, props: BaseNetworkListenerProps) -> NetworkListenerpublic NetworkListener addListener(String id, BaseNetworkListenerProps props)public NetworkListener AddListener(string id, BaseNetworkListenerProps props)func AddListener(Id *string, Props BaseNetworkListenerProps) NetworkListener#
Add a listener to this load balancer.
returns

Returns: The newly created listener

addSecurityGroup(securityGroup: ISecurityGroup): voiddef add_security_group(self, security_group: ISecurityGroup) -> Nonepublic void addSecurityGroup(ISecurityGroup securityGroup)public void AddSecurityGroup(ISecurityGroup securityGroup)func AddSecurityGroup(SecurityGroup ISecurityGroup)#
Add a security group to this load balancer.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromLookup(scope: Construct, id: string, options: NetworkLoadBalancerLookupOptions): INetworkLoadBalancer@staticmethod def from_lookup(scope: Construct, id: str, options: NetworkLoadBalancerLookupOptions) -> INetworkLoadBalancerpublic static INetworkLoadBalancer fromLookup(Construct scope, String id, NetworkLoadBalancerLookupOptions options)public static INetworkLoadBalancer FromLookup(Construct scope, string id, NetworkLoadBalancerLookupOptions options)func FromLookup(Scope Construct, Id *string, Options NetworkLoadBalancerLookupOptions) INetworkLoadBalancerstatic#
Looks up the network load balancer.
fromNetworkLoadBalancerAttributes(scope: Construct, id: string, attrs: NetworkLoadBalancerAttributes): INetworkLoadBalancer@staticmethod def from_network_load_balancer_attributes(scope: Construct, id: str, attrs: NetworkLoadBalancerAttributes) -> INetworkLoadBalancerpublic static INetworkLoadBalancer fromNetworkLoadBalancerAttributes(Construct scope, String id, NetworkLoadBalancerAttributes attrs)public static INetworkLoadBalancer FromNetworkLoadBalancerAttributes(Construct scope, string id, NetworkLoadBalancerAttributes attrs)func FromNetworkLoadBalancerAttributes(Scope Construct, Id *string, Attrs NetworkLoadBalancerAttributes) INetworkLoadBalancerstatic#
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
logAccessLogs(bucket: IBucket, prefix?: string): voiddef log_access_logs(self, bucket: IBucket, prefix: typing.Optional[str] = None) -> Nonepublic void logAccessLogs(IBucket bucket, String prefix)public void LogAccessLogs(IBucket bucket, string? prefix = null)func LogAccessLogs(Bucket IBucket, Prefix *string)#
Enable access logging for this load balancer.

A region must be specified on the stack containing the load balancer; you cannot enable logging on environment-agnostic stacks. See https://docs.aws.amazon.com/cdk/latest/guide/environments.html

metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.custom`` instead
metricActiveFlowCount(props?: MetricOptions): Metricdef metric_active_flow_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricActiveFlowCount(MetricOptions props)public Metric MetricActiveFlowCount(MetricOptions? props = null)func MetricActiveFlowCount(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.activeFlowCount`` instead

This metric includes connections in the SYN_SENT and ESTABLISHED states. TCP connections are not terminated at the load balancer, so a client opening a TCP connection to a target counts as a single flow.

metricConsumedLCUs(props?: MetricOptions): Metricdef metric_consumed_lc_us(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricConsumedLCUs(MetricOptions props)public Metric MetricConsumedLCUs(MetricOptions? props = null)func MetricConsumedLCUs(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.activeFlowCount`` instead
metricNewFlowCount(props?: MetricOptions): Metricdef metric_new_flow_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricNewFlowCount(MetricOptions props)public Metric MetricNewFlowCount(MetricOptions? props = null)func MetricNewFlowCount(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.newFlowCount`` instead
metricProcessedBytes(props?: MetricOptions): Metricdef metric_processed_bytes(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricProcessedBytes(MetricOptions props)public Metric MetricProcessedBytes(MetricOptions? props = null)func MetricProcessedBytes(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.processedBytes`` instead
metricTcpClientResetCount(props?: MetricOptions): Metricdef metric_tcp_client_reset_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricTcpClientResetCount(MetricOptions props)public Metric MetricTcpClientResetCount(MetricOptions? props = null)func MetricTcpClientResetCount(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.tcpClientResetCount`` instead

These resets are generated by the client and forwarded by the load balancer.

metricTcpElbResetCount(props?: MetricOptions): Metricdef metric_tcp_elb_reset_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricTcpElbResetCount(MetricOptions props)public Metric MetricTcpElbResetCount(MetricOptions? props = null)func MetricTcpElbResetCount(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.tcpElbResetCount`` instead
metricTcpTargetResetCount(props?: MetricOptions): Metricdef metric_tcp_target_reset_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricTcpTargetResetCount(MetricOptions props)public Metric MetricTcpTargetResetCount(MetricOptions? props = null)func MetricTcpTargetResetCount(Props MetricOptions) Metricdeprecated#
Use ``NetworkLoadBalancer.metrics.tcpTargetResetCount`` instead

These resets are generated by the target and forwarded by the load balancer.

removeAttribute(key: string): voiddef remove_attribute(self, key: str) -> Nonepublic void removeAttribute(String key)public void RemoveAttribute(string key)func RemoveAttribute(Key *string)#
Remove an attribute from the load balancer.
setAttribute(key: string, value?: string): voiddef set_attribute(self, key: str, value: typing.Optional[str] = None) -> Nonepublic void setAttribute(String key, String value)public void SetAttribute(string key, string? value = null)func SetAttribute(Key *string, Value *string)#
Set a non-standard attribute on the load balancer.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.