AWS Database Blog

Best practices for creating a VPC for Amazon RDS for Db2

You can create an Amazon Relational Database Service (Amazon RDS) for Db2 instance by using the AWS Management Console, AWS Command Line Interface (AWS CLI), AWS CloudFormation, Terraform by Hashicorp, AWS Lambda functions, or other methods. One of the prerequisites for creating an RDS for Db2 instance is to configure the virtual private cloud (VPC) appropriately. This post shows how to create a VPC with best practices for any Amazon RDS database in general and Amazon RDS for Db2 in particular through a one-click automated deployment.

This post shows the VPC best practices for Amazon RDS for Db2. The same VPC can be used for other engines such as RDS for Oracle, RDS for SQL Server, RDS for MySQL, RDS for PostgreSQL, and RDS for MariaDB.

What is Amazon RDS for Db2?

Amazon RDS for Db2 is the latest addition to the Amazon RDS family of database engines. This service offers a fully managed solution on scalable hardware, designed to deliver optimal performance within minutes. It features an optional Multi-AZ deployment, which synchronously replicates data to a cold standby DB instance in a different Availability Zone in the same AWS Region, providing high availability and reliability. AWS takes care of provisioning, patching, backups, and monitoring of the RDS for Db2 instances, significantly reducing operational overhead. This allows database administrators to focus on enhancing application performance instead of handling routine maintenance tasks.

What is an Amazon VPC?

With Amazon Virtual Private Cloud (Amazon VPC), you can create a VPC in AWS, which is a logically isolated network dedicated to your AWS account. It allows you to define a virtual network that mimics a traditional on-premises network but with the scalability, flexibility, and security of AWS. When you create a VPC, you define an IP address range (CIDR block), subnets, route tables, and other networking components that determine how AWS resources—for example, Amazon Elastic Compute Cloud (Amazon EC2) instances—can communicate with each other and the internet.

VPCs are crucial for controlling how network traffic flows into and out of AWS resources. A VPC provides the following core features:

  • Complete network isolation – You can launch your resources like Amazon RDS for Db2, Amazon EC2, and more inside your VPC and fully control the incoming and outgoing traffic by configuring security groups and network access control lists (ACLs).
  • Security – Security is a fundamental aspect of VPC. AWS provides security groups and network ACLs that allow you to control traffic at the instance and subnet level, respectively.

A VPC includes the following components:

  • Subnets – You can divide the VPC into subnets, which represent isolated network segments within the VPC. Subnets can be public (accessible from the internet) or private (internal only).
  • Route tables – You can set up route tables to control the routing of traffic within the VPC, and between other VPCs and the internet.
  • Gateways and interface endpoints – You can configure internet gateways, NAT gateways, and VPC endpoints to manage how traffic flows between your VPC and external networks—for example, the internet or AWS services like Amazon Simple Storage Service (Amazon S3).

Importance of Amazon VPC in Amazon RDS for Db2

An Amazon VPC provides the foundational network infrastructure for your AWS environment. Whether you’re running a simple web application, an RDS database, or a complex multi-tier architecture, an Amazon VPC is essential for several reasons:

  • Network isolation – By default, resources in an Amazon VPC are isolated from the internet and other Amazon VPCs. This makes sure your resources are only accessible with explicit permissions.
  • Fine-grained control – You have full control over the IP address ranges, subnets, route tables, and network configurations. This allows you to build network architectures tailored to your application’s requirements, including multi-tiered environments and secure zones.
  • Security – Amazon VPCs enable you to control who and what can access your resources. With security groups, network ACLs, and VPC flow logs, you can enforce strict security policies and monitor network traffic for auditing purposes.
  • Elasticity – Amazon VPCs allow for flexible and scalable networking infrastructure. You can add subnets, add gateways, and modify route tables as your network grows, allowing your applications to scale without re-architecting the network.

How to use Amazon VPCs to isolate Amazon RDS for Db2

Amazon VPCs are designed to isolate resources and control access within AWS. In this section, we discuss several ways in which a VPC can be used to isolate resources effectively.

Public and private subnets

A public subnet is a subnet that has a route to an internet gateway, making its resources accessible from the internet. These subnets are ideal for hosting public-facing services like web servers.

A private subnet is a subnet that doesn’t have a route to the internet gateway, which keeps its resources internal. Typically, private subnets are used for resources that should not be accessible from the internet, such as RDS for Db2 databases, internal APIs, and backend services.

By using a combination of public and private subnets, you can make sure that critical components of your infrastructure (like databases) are protected from direct exposure to the internet.

Isolating Amazon RDS for Db2

You can isolate different parts of your application in different subnets. For example:

  • Db2 clients and web servers hosted in public subnets (for internet access)
  • Application servers in private subnets (only accessible from the web servers)
  • Databases in another private subnet (only accessible from the application servers)

The following diagram shows a sample architecture of Amazon RDS for Db2 with application servers.

This multi-tier architecture makes sure that different components are isolated from each other, reducing the attack surface and limiting the potential impact of a security breach.

Security groups and network ACLs

Security groups act as virtual firewalls at the instance level, controlling both inbound and outbound traffic. You can specify which IP addresses, ports, and protocols are allowed to communicate with your resources.

Network ACLs provide additional security at the subnet level. Whereas security groups are stateful (they automatically allow return traffic), network ACLs are stateless and allow you to define more granular rules for controlling traffic between subnets.

Using a combination of security groups and network ACLs, you can create tight security controls that limit traffic to only what’s necessary for your application.

Amazon VPC peering for isolation across projects

Amazon VPC peering allows you to connect two VPCs privately using the AWS network, without the need for a VPN or gateway. This is useful if you want to allow communication between VPCs but still keep them isolated from the public internet.

For example, you could have one VPC for development and another for production. By using VPC peering, developers can access production services as needed, while keeping the two environments logically isolated.

Amazon VPC endpoints

Amazon VPC endpoints enable private connections between your Amazon VPC and services like Amazon S3 and Amazon RDS for Db2, without traversing the public internet. This makes sure that traffic between your Amazon VPC and these services remains secure and isolated from potential threats.

Amazon VPC endpoints are ideal for private subnets that need access to AWS services (like Amazon S3) without going through a NAT gateway or internet gateway.

Best practices for Amazon VPC design

When designing a VPC, there are several best practices to follow to achieve security, scalability, and performance:

  • Use multiple Availability Zones – Spread your subnets across multiple Availability Zones to increase availability and fault tolerance. By having resources in different Availability Zones, your infrastructure can continue operating even if one Availability Zone becomes unavailable.
  • Separate public and private subnets – Always separate your public-facing resources (such as web servers) from private resources (such as databases or backend servers). This adds an extra layer of security by preventing direct internet access to sensitive resources.
  • Use private subnets for sensitive data – Place sensitive data stores, such as RDS databases, in private subnets to make sure they’re not exposed to the internet. Access should only be allowed from other subnets in your VPC through strict security group rules.
  • Minimize the use of NAT gateways – NAT gateways can become bottlenecks and incur additional costs. Use VPC endpoints where possible (for example, for accessing Amazon S3 or Amazon RDS for Db2), which can route traffic directly from your VPC to AWS services without using a NAT gateway.
  • Limit the scope of security groups – Use least privilege principles when configuring security groups. Only allow the minimum amount of traffic necessary to operate your resources. For example, restrict traffic to specific IP ranges, ports, and protocols.
  • Follow best practices for Amazon RDS for Db2 – While deploying Amazon RDS for Db2, consider the following best practices:
    • Make sure the database is using private subnets and the endpoint URLs aren’t exposed to public access.
    • Use data at rest encryption either by using default keys or by using your AWS Key Management Service (AWS KMS) keys.
    • Use data in transit encryption for Amazon RDS for Db2.
  • Use VPC peering or AWS Transit Gateway for inter-VPC communication – If you need to interconnect multiple VPCs (for example, for different environments like development, testing, and production), use VPC peering or AWS Transit Gateway to securely connect them while keeping them logically isolated.
  • Monitor and log traffic – Enable VPC flow logs to capture information about the traffic coming in and out of your Amazon VPC. This is essential for monitoring, auditing, and debugging network-related issues.
  • Use a well-planned IP addressing scheme – Plan your IP address ranges (CIDR blocks) carefully to avoid overlap, especially if you plan to connect multiple VPCs or integrate with on-premises networks using a VPN or AWS Direct Connect.

Best practices for creating an Amazon VPC for use by Amazon RDS for Db2

The following architectural diagram depicts multiple VPCs in an AWS account.

This architecture uses the following configuration and best practices:

  • Create two private subnets and one public subnet for each Availability Zone in a Region.
  • Use private subnets for Amazon RDS for Db2 and for the Db2 client connecting to Amazon RDS for Db2.
  • Create an Amazon S3 endpoint gateway and associate it to the private subnets so that the traffic from Amazon RDS for Db2 or client uses an AWS internal network.
  • If you need to access the internet from Db2 clients, create a NAT gateway and associate it with the appropriate private subnet route.
  • To SSH to a Db2 client hosted on Amazon EC2, use AWS Systems Manager to connect using the aws ssm start_session <instance ID> command to bypass any need of opening an SSH port. Carefully review your security policy before opening an SSH port through a security group.
  • If an EC2 instance is used as a web server, only open port 80 and 443 through the security group.

Prerequisites

The following tools and libraries are required:

Deploy an Amazon VPC

You can deploy an Amazon VPC for Amazon RDS for Db2 by using a single command from any Linux or MacOS system. You can let a Lambda function choose the next available CIDR range automatically or you can override it by using a valid value in an environment variable CIDR. The Lambda function will still check the validity of the overridden CIDR_IP network address range. If it’s in use, it will pick the next available CIDR_IP network address range automatically.

$ export CIDR="" # Keep blank to pick up next available CIDR
# Example CIDR="10.12.0.0/16" to override with your value
$ export PROFILE=<your AWS profile Name>
$ export REGION=<your region name>
$ source <(curl -Ls https://tinyurl.com/deployvpc)

If you’re using Windows, you can manually deploy the CloudFormation template by using the AWS CloudFormation console.

Optionally, if you want to go through the driver script and CloudFormation stack script, complete the following steps:

  1. Use the shell script that runs the CloudFormation template:
    $ curl -Ls https://tinyurl.com/deployvpc -o deploy.sh

    The preceding command will download the deploy.sh bash shell script, which deploys the CloudFormation template create-vpc-lambda.yml.

  2. You can download the CloudFormation template, which will deploy the Lambda function and appropriate IAM role, and run a custom resource to run the Lambda function to create an Amazon VPC with relevant resources such as subnets, route tables, and endpoints:
    $ curl -Ls https://aws-blogs-artifacts-public.s3.us-east-1.amazonaws.com/artifacts/DBBLOG-4481/create-vpc-lambda.yml -o create-vpc-lambda.yml

The preceding two steps are put together as a single step in the following script to deploy an Amazon VPC in a Region of your choice:

$ source <(curl -Ls https://tinyurl.com/deployvpc)

After creating the Amazon VPC, you can view the resource map of the VPC on the Amazon VPC console. Choose Your VPCs in the navigation pane and choose the VPC that was created. The resource map tab shows the graphical view of the subnets, routing tables, and gateways. Choose the table pri_route_table to see the outlay for the private subnets showing the private route table connected to the NAT gateway and Amazon S3 gateway endpoint and their association.

The following screenshot shows public subnets connected to the separate route table that has an internet gateway attached.

Use a Lambda function to create a VPC

We chose to use a Lambda function for the entire VPC creation, including subnets, route tables, internet gateway, and NAT gateway.

We use the CloudFormation template to create an IAM role for the Lambda function with minimum permissions, create Lambda function, and create a custom resource to run the Lambda function one time to create the VPC.

You can manually create a VPC by specifying the following parameters appropriately:

  • Non-overlapping CIDR
  • Number of Availability Zones
  • Dividing the CIDR appropriately for each subnet and avoid any overlap
  • Number of subnets to create
  • Distinction between private and public subnet
  • Resources to attach to public and private subnet

The Lambda function automates those parameters to create an Amazon VPC. The function does the following:

  • Determines the next available non-overlapping CIDR to use
  • Dynamic for different Availability Zones per Region
  • Dynamic for creating public and private subnets
  • Dynamic for allocating IP ranges in the CIDR for each subnet
  • A single command to deploy an Amazon VPC from your account

You can view the Lambda function code in the CloudFormation template create-vpc-lambda.yml.

Create a VPC

The Lambda function takes care of the following steps to create a VPC:

  1. Get the list of existing VPCs.
  2. Find an available CIDR non-overlapping block or use a CIDR that a user provides.
  3. Create a VPC with a default route.
  4. Get the default route, make it private route, and assign it a friendly name.
  5. Get all Availability Zones in the Region.
  6. Create an internet gateway and attach it to the VPC.
  7. Create a route table for public subnets and assign it a friendly name.
  8. Create a route in the public route table to route all traffic to the internet gateway.
  9. Generate a CIDR block for two private subnets and one public subnet.
  10. Create subnets for each Availability Zone and associate the route table.
  11. Create a NAT gateway and assign it a friendly name.
  12. Add a route to the private route table to route internet-bound traffic through the NAT gateway.
  13. Associate an Amazon S3 gateway with the private route table for access to Amazon S3 and assign it a friendly name.

Delete a VPC

The Lambda function is invoked through a CloudFormation stack, and therefore the function also has code to delete the VPC. It takes care of the following steps:

  1. Check if the default security group is attached to any network. If not, we can delete the VPC; otherwise, do not delete the VPC because it has external dependencies.
  2. Get the VPC ID from the CloudFormation stack.
  3. Delete the NAT gateway and release the EIP.
  4. Delete the Amazon S3 gateway endpoint.
  5. Disassociate the subnets from the route tables before deleting them.
  6. Delete the subnets after disassociating them from the route tables.
  7. Delete the routes (except the local route) and route tables.
  8. Delete the internet gateway.
  9. Delete the VPC.

Deploy an RDS for Db2 instance

Selection criteria for choosing a VPC and other AWS features depends on your organization’s scale and security needs:

  • You might choose to isolate database resources in their VPC.
  • You can choose separate VPCs for applications. Use either VPC peering or an AWS managed gateway to have connectivity between the database and application VPCs.
  • In a small environment setup, you can use the same VPC for your database and applications. Use private subnets for databases and public subnets to external-facing web applications through a security group to control access.
  • In a large environment setup, use an Amazon API Gateway VPC link to connect API Gateway to applications and databases in private subnets. Put a Network Load Balancer in front of private services such as databases and applications.

Important networking aspects for Amazon RDS for Db2

After deciding on the proper VPC and upstream networking components, you need to pay attention to two networking components while creating an RDS for Db2 instance:

  • Choose a VPC – You don’t directly select a VPC while creating an RDS for Db2 instance. You choose a security group, which is associated with a VPC. Carefully select the security group because you can’t modify an instance later to change the VPC.
  • Create a subnet group – A subnet group defines the network placement within a VPC. It provides redundancy and high availability by allowing Amazon RDS to deploy across multiple subnets in different Availability Zones. Amazon RDS uses the subnets in the group to deploy standby instances in different Availability Zones. The best practice is to include private subnets in the group to restrict access to the RDS instance from the internet.

Use the following command to list only private subnets and use them to create a subnet group. The command assumes that you have created a VPC using the preceding Lambda method with user-friendly names to define private and public subnets. The following command will not show subnets properly if you have not defined proper tags in your VPC to identify private or public subnets.

VPC_ID=<VPC ID>
PROFILE=<your profile>
REGION=<your Region>
SUBNET_IDS=$(aws ec2 describe-subnets \
  --filters "Name=vpc-id,Values=$VPC_ID" "Name=tag:Name,Values=private*" \
  --query "Subnets[].SubnetId" \
  --region $REGION --profile $PROFILE \
  --output text)
aws rds create-db-subnet-group \
  --db-subnet-group-name my-subnet-group \
  --db-subnet-group-description "DB subnet group for VPC $VPC_ID" \
    --subnet-ids $SUBNET_IDS  

Create an RDS for Db2 instance

If you use the console to create your RDS for Db2 instance, the console creates the DB subnet group automatically. If using an AWS CLI command, you have to define the DB subnet group name. If your security group VPC and DB subnet group name VPC don’t match, the instance creation will fail.

aws rds create-db-instance \
--region us-east-1 \
--db-instance-identifier database-1 \
--allocated-storage 20 \
--db-instance-class db.m6i.xlarge \
--engine db2-se \
--master-username admin \
--master-user-password Passw0rd \
--availability-zone us-east-1d \
--db-parameter-group-name my-db2-se-pg \
--port 8392 \
--no-multi-az \
--engine-version 11.5.9.0.sb00042449.r1 \
--license-model bring-your-own-license \
--no-publicly-accessible \
--storage-type gp3 \
--storage-encrypted \
--no-deletion-protection \
--monitoring-interval 0 \
--vpc-security-group-ids sg-05b6be0a0585113a6 \
--db-subnet-group-name my-subnet-group

Troubleshooting

The VPC creation may fail for some reasons. The most common is exceeding the limit of number of VPCs that you can create in your account. If you are overriding the CIDR, make sure that it’s not overlapping and uses a valid CIDR range. You can navigate to the Lambda function on the Lambda console, and on the Monitoring tab, choose the Amazon CloudWatch logs to see the messages from the Lambda function to check the reason of failure.

Clean up

Delete the RDS for Db2 instance if you no longer need it. After you have deployed the VPC in your Region, you can delete the CloudFormation template because it’s no longer required.

aws rds delete-db-instance \
--region us-east-1 \
--db-instance-identifier database-1

List the CloudFormation templates with the following command:

aws cloudformation describe-stacks --query "Stacks[*].{Name:StackName, Status:StackStatus}" --output table

Find the name from the output that matches VPCCreationLambdaStack, and use the following command to delete it:

aws cloudformation delete-stack --stack-name <StackName>

Replace <StackName> with the name that begins with VPCCreationLambdaStack.

Conclusion

VPCs provide a powerful, flexible way to control networking and security in the cloud. By following best practices such as isolating public and private subnets, using security groups effectively, and using VPC endpoints, you can build secure and scalable network architectures that protect your cloud resources. Through automation using tools like Lambda and AWS CloudFormation, you can further simplify the process of creating and managing VPCs, providing consistency and repeatability in your infrastructure.

Try out the solution for your own use case, and leave your feedback and questions in the comments.


About the authors

Vikram S Khatri is a Sr. DBE for Amazon RDS for Db2. Vikram has over 20 years of experience in Db2. He enjoys developing new products from the ground up. In his spare time, he practices meditation and enjoys listening to podcasts.

Sumit Kumar is a Senior Solutions Architect at AWS, and enjoys solving complex problems. He has been helping customers across various industries to build and design their workloads on the AWS Cloud. He enjoys cooking, playing chess, and spending time with his family.