Cloud and deployment · Intermediate · 22 min
Control traffic in AWS with security groups and network ACLs
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4
You will build a three-tier set of security groups that chain by group ID, add a network ACL that blocks one abusive address range at the subnet edge, and run a query that lists every rule open to the whole internet.
On this page
Two AWS features decide which packets reach your servers. Security groups wrap each network interface: an EC2 instance, a load balancer node, an RDS database. Network ACLs sit at the edge of each subnet. They look alike in the console, and many teams use only the first, but they behave differently enough that mixing them up causes either a hole or an outage.
In this tutorial you build the rule set for a typical web app with three tiers. A load balancer accepts HTTPS from anyone. The app servers accept traffic only from the load balancer, and the database accepts PostgreSQL only from the app servers. The trick is that the second and third rules name another security group, not an IP range, so they keep working when instances come and go. Then you add a network ACL to the public subnet that drops one abusive address range before it reaches anything, and you finish with a query that lists every rule open to the whole internet, across every Region your account uses.
Everything is built in a new practice VPC called tiers-demo, so nothing touches your existing networks. VPCs, subnets, security groups and network ACLs have no charge of their own (AWS's VPC documentation, checked 26 November 2026). You launch no instances, load balancers or databases, so nothing here bills. Files go in ~/tiers-demo, and the last step deletes all of it.
Step 1 · Create a practice VPC with two subnets
Point the CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder). Security groups and network ACLs belong to one Region, so make sure a Region is set too, in the profile or with AWS_REGION. If your users are in southern Africa, Cape Town (af-south-1) works the same way once the Region is enabled for your account.
aws --version
aws sts get-caller-identity --query Arn --output text
aws configure listMake the working folder, then create the VPC and two subnets. The public subnet is where the load balancer would live and the private one holds the app and the database. This tutorial does not add an internet gateway or routes, because the rules you write here do not depend on them; /tutorials/understand-aws-vpcs-subnets-route-tables-and-nat covers that part.
mkdir -p ~/tiers-demo
cd ~/tiers-demo
VPC_ID=$(aws ec2 create-vpc --cidr-block 10.20.0.0/16 \
--tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=tiers-demo}]' \
--query Vpc.VpcId --output text)
PUBLIC_SUBNET=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.20.1.0/24 \
--tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=tiers-demo-public}]' \
--query Subnet.SubnetId --output text)
PRIVATE_SUBNET=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.20.2.0/24 \
--tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=tiers-demo-private}]' \
--query Subnet.SubnetId --output text)
echo "$VPC_ID $PUBLIC_SUBNET $PRIVATE_SUBNET"The later steps use these three shell variables. If you open a new terminal, look the IDs up again with aws ec2 describe-vpcs --filters Name=tag:Name,Values=tiers-demo and aws ec2 describe-subnets --filters Name=vpc-id,Values=<vpc-id>.
AWS created two things for you along with the VPC: a default security group and a default network ACL, and both subnets are attached to that ACL. You will look at it in a later step.
Check it worked
aws --version starts with aws-cli/2.42, the caller ARN belongs to your sandbox account, and the region row of aws configure list shows your Region (for example eu-west-2) with where it came from: env and AWS_REGION or AWS_DEFAULT_REGION if you exported it, or config_file if it is in your profile. If the row says <not set>, export AWS_REGION before you go on. The echo prints one ID starting vpc- and two starting subnet-.
Step 2 · Open the load balancer group to HTTPS
Create one security group per tier. Names must be unique in the VPC and cannot start with sg-, so prefix them with the project name:
LB_SG=$(aws ec2 create-security-group --vpc-id "$VPC_ID" \
--group-name tiers-demo-lb --description "Load balancer: HTTPS from the internet" \
--query GroupId --output text)
APP_SG=$(aws ec2 create-security-group --vpc-id "$VPC_ID" \
--group-name tiers-demo-app --description "App servers: only from the load balancer" \
--query GroupId --output text)
DB_SG=$(aws ec2 create-security-group --vpc-id "$VPC_ID" \
--group-name tiers-demo-db --description "PostgreSQL: only from the app servers" \
--query GroupId --output text)
echo "lb=$LB_SG app=$APP_SG db=$DB_SG"A new security group has no inbound rules, so it lets nothing in. It does have one outbound rule that allows all traffic out. You change both.
Write the load balancer's inbound rule to a file. A file keeps the JSON readable and lets you reuse it to remove the rule later. Every rule gets a description, which is the first thing you will want when someone asks "why is this open?" a year from now.
cat > lb-in.json <<'EOF'
[
{
"IpProtocol": "tcp",
"FromPort": 443,
"ToPort": 443,
"IpRanges": [{ "CidrIp": "0.0.0.0/0", "Description": "HTTPS from anyone" }]
}
]
EOF
aws ec2 authorize-security-group-ingress --group-id "$LB_SG" --ip-permissions file://lb-in.jsonIf your VPC has an IPv6 range, add a second entry with "Ipv6Ranges": [{ "CidrIpv6": "::/0" }]. IPv4 and IPv6 are separate rules, and a site reachable over IPv6 but not allowed by an IPv6 rule fails only for some visitors, which is slow to diagnose. There is no rule for port 80 here: if you want HTTP to redirect to HTTPS, the load balancer needs port 80 open too, and the redirect happens in its listener, not in the security group.
Check it worked
This prints the one inbound rule as protocol, ports and source:
aws ec2 describe-security-groups --group-ids "$LB_SG" \
--query 'SecurityGroups[0].IpPermissions[].[IpProtocol, FromPort, ToPort, IpRanges[0].CidrIp]' \
--output textYou see tcp 443 443 0.0.0.0/0 on one line, and three group IDs starting sg- were printed above it.
Step 3 · Let only the load balancer reach the app servers
The app listens on port 8080. You could allow 8080 from the public subnet's range, 10.20.1.0/24, but that admits anything you ever place in that subnet, and it breaks when you add a second public subnet. Instead, name the load balancer's security group as the source. The rule then means "any network interface that has tiers-demo-lb attached", whatever its address.
The heredoc delimiter is unquoted this time, so the shell fills in ${LB_SG}:
cat > app-in.json <<EOF
[
{
"IpProtocol": "tcp",
"FromPort": 8080,
"ToPort": 8080,
"UserIdGroupPairs": [{ "GroupId": "${LB_SG}", "Description": "App port, from the load balancer only" }]
}
]
EOF
aws ec2 authorize-security-group-ingress --group-id "$APP_SG" --ip-permissions file://app-in.jsonThree things to know about group references:
- Nothing is copied. The app group does not inherit the load balancer group's rules; it only trusts the interfaces that carry it.
- The referenced group must be in the same VPC, or in one connected by peering or a transit gateway.
- A reference counts as one rule towards the quota of 60 inbound rules per group, however many instances carry the referenced group.
You did not add a rule for the app's replies. Security groups are stateful: when the load balancer opens a connection to port 8080 and the app group allows it, the reply packets go back out automatically, whatever the outbound rules say.
Check it worked
aws ec2 describe-security-groups --group-ids "$APP_SG" \
--query 'SecurityGroups[0].IpPermissions[].[FromPort, UserIdGroupPairs[0].GroupId]' \
--output text
echo "expected source: $LB_SG"The first line shows 8080 followed by the same sg- ID as the expected source, and the app group has no rule with a CIDR range.
Step 4 · Let only the app servers reach the database
Same pattern, one tier down: PostgreSQL's port 5432, from the app group only.
cat > db-in.json <<EOF
[
{
"IpProtocol": "tcp",
"FromPort": 5432,
"ToPort": 5432,
"UserIdGroupPairs": [{ "GroupId": "${APP_SG}", "Description": "PostgreSQL, from the app servers only" }]
}
]
EOF
aws ec2 authorize-security-group-ingress --group-id "$DB_SG" --ip-permissions file://db-in.jsonThe database never starts a connection of its own; it only answers the app, and stateful tracking already lets those answers out. So remove the allow-all outbound rule that every new group starts with. If the database host is ever compromised, it cannot open new connections to the internet to fetch tools or upload data (DNS queries to the VPC resolver still get through, as the next step explains). The catch: a self-managed database on EC2 with no outbound rule also cannot fetch OS or package updates, so allow a mirror or proxy when you patch it. A managed RDS database is not affected, because AWS patches it.
cat > all-out.json <<'EOF'
[
{ "IpProtocol": "-1", "IpRanges": [{ "CidrIp": "0.0.0.0/0" }] }
]
EOF
aws ec2 revoke-security-group-egress --group-id "$DB_SG" --ip-permissions file://all-out.jsonLeave the app group's outbound rule in place for now: app servers usually call payment providers, email services and package mirrors. Tightening it to the destinations you actually use is a good follow-up once you know them.
The load balancer can now reach the app and the app can reach the database, but the load balancer cannot reach the database directly, and nothing on the internet can reach either of the inner tiers. When you later create an RDS database or launch an instance, you pass the matching group ID (for example --vpc-security-group-ids for RDS, --security-group-ids for EC2).
Check it worked
aws ec2 describe-security-groups --group-ids "$DB_SG" \
--query 'SecurityGroups[0].IpPermissions[].[FromPort, UserIdGroupPairs[0].GroupId]' --output text
echo "expected source: $APP_SG"
aws ec2 describe-security-groups --group-ids "$DB_SG" \
--query "length(SecurityGroups[0].IpPermissionsEgress[?IpRanges[?CidrIp=='0.0.0.0/0']])"The first command prints 5432 and the app group's ID, matching the expected source. The last prints 0: the database group has no outbound rule to the internet left.
Step 5 · See how network ACLs differ from security groups
Before writing an ACL, look at the one AWS gave the VPC:
DEFAULT_NACL=$(aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC_ID" \
--query 'NetworkAcls[?IsDefault].NetworkAclId' --output text)
aws ec2 describe-network-acls --network-acl-ids "$DEFAULT_NACL" \
--query 'NetworkAcls[0].Entries[].[Egress, RuleNumber, Protocol, RuleAction, CidrBlock]' \
--output textYou see something like four lines: for inbound (False) and outbound (True), rule 100 allows protocol -1 (all traffic) from 0.0.0.0/0, and rule 32767 denies it. Rule 32767 is the one the console shows as *: the catch-all that applies when nothing above it matched. In the default ACL, rule 100 matches everything first, so the default ACL lets everything through and leaves the filtering to security groups.
Here is how the two layers differ, and why it matters:
- Where they apply. A security group is attached to a network interface, and one interface can carry up to five groups by default. A network ACL is attached to a subnet, and every subnet has exactly one.
- Allow and deny. Security groups only allow; if any attached group allows a packet, it is in. ACL rules can allow or deny, so an ACL is where you block a specific range.
- Order. Security group rules have no order; AWS combines them all. ACL rules are numbered from 1 to 32766 and checked from the lowest number up, and the first match wins, even if a later rule says the opposite.
- State. Security groups are stateful, so replies are allowed automatically. ACLs are stateless: a reply is a new packet that needs its own rule in the other direction.
- Sources. Security group rules can name another security group. ACL rules can only name CIDR ranges.
- Size. 60 inbound and 60 outbound rules per security group, but only 20 rules per direction per ACL by default (40 at most). That is too small for a long blocklist; for hundreds of bad addresses, use an AWS WAF IP set on the load balancer instead.
Statelessness is what catches people out. When a browser connects to the load balancer on 443, the reply goes back to whatever port the browser picked, an ephemeral port. Linux clients pick from 32768 to 61000, Windows from 49152 to 65535, and load balancers and NAT gateways from 1024 to 65535. An ACL that allows 443 in but not those ports out lets the request arrive and silently drops the answer.
Neither layer can block DNS queries to the VPC's own resolver (Route 53 Resolver DNS Firewall is the tool for that), and network ACLs also cannot block calls to the instance metadata service, which has its own settings.
Check it worked
Answer these from the list above, then check: a packet from 203.0.113.7 hits an ACL with rule 200 deny 203.0.113.0/24 and rule 100 allow 0.0.0.0/0 on port 443. Is it allowed? (Yes: rule 100 is checked first and matches.) Can a security group block one IP while allowing everyone else? (No: it has no deny rules.) The default ACL listing you printed shows a rule 100 with allow.
Step 6 · Block an abusive range with a network ACL
Say your load balancer logs show a flood of requests from 198.51.100.0/24. That is a documentation range used here as a placeholder; replace it with the range you actually saw. You cannot block it with a security group, so give the public subnet its own ACL.
A new custom ACL denies everything until you add rules. If you attached it to a subnet now, the subnet would go dark. So add every rule first, and switch the subnet over last.
PUBLIC_NACL=$(aws ec2 create-network-acl --vpc-id "$VPC_ID" \
--tag-specifications 'ResourceType=network-acl,Tags=[{Key=Name,Value=tiers-demo-public}]' \
--query NetworkAcl.NetworkAclId --output text)
echo "$PUBLIC_NACL"Now the rules. --protocol 6 is TCP and -1 means all protocols. The numbers go up in tens so you can slot a rule in between later. The deny rule is number 90, so it is checked before the allows:
aws ec2 create-network-acl-entry --network-acl-id "$PUBLIC_NACL" --ingress \
--rule-number 90 --protocol -1 --cidr-block 198.51.100.0/24 --rule-action deny
aws ec2 create-network-acl-entry --network-acl-id "$PUBLIC_NACL" --ingress \
--rule-number 100 --protocol 6 --port-range From=443,To=443 --cidr-block 0.0.0.0/0 --rule-action allow
aws ec2 create-network-acl-entry --network-acl-id "$PUBLIC_NACL" --ingress \
--rule-number 110 --protocol 6 --port-range From=1024,To=65535 --cidr-block 0.0.0.0/0 --rule-action allow
aws ec2 create-network-acl-entry --network-acl-id "$PUBLIC_NACL" --egress \
--rule-number 100 --protocol 6 --port-range From=1024,To=65535 --cidr-block 0.0.0.0/0 --rule-action allow
aws ec2 create-network-acl-entry --network-acl-id "$PUBLIC_NACL" --egress \
--rule-number 110 --protocol 6 --port-range From=443,To=443 --cidr-block 0.0.0.0/0 --rule-action allowWhat each rule is for:
- In 90: drop everything from the abusive range, before any allow can match it.
- In 100: HTTPS from anyone else.
- In 110: replies coming back to connections started inside the subnet. That covers the app's answers from port 8080 in the private subnet to the load balancer, and HTTPS calls out to the internet.
- Out 100: replies to visitors on their ephemeral ports. The load balancer's own connections to the app on port 8080 also fall inside this range.
- Out 110: HTTPS calls out of the subnet.
Read the inbound rules back in the order AWS checks them:
aws ec2 describe-network-acls --network-acl-ids "$PUBLIC_NACL" \
--query 'sort_by(NetworkAcls[0].Entries[?Egress==`false`], &RuleNumber)[].[RuleNumber, RuleAction, CidrBlock, PortRange.From, PortRange.To]' \
--output textNow attach the ACL to the public subnet. A subnet always has exactly one ACL, so you do not add an association; you replace the existing one, which you look up first:
OLD_ASSOC=$(aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC_ID" \
--query "NetworkAcls[].Associations[?SubnetId=='${PUBLIC_SUBNET}'][].NetworkAclAssociationId" \
--output text)
aws ec2 replace-network-acl-association --association-id "$OLD_ASSOC" --network-acl-id "$PUBLIC_NACL"The private subnet stays on the default ACL. Adding ACLs to every subnet doubles the places a rule can go wrong; use them where you need a deny or a hard subnet boundary, and let security groups do the everyday work. If you do give the private subnet a custom ACL later, remember the load balancer talks to it from ports 1024 to 65535, so both directions need rules.
Check it worked
The sorted listing shows something like this, with 90 deny above the allows and AWS's catch-all at the bottom:
90 deny 198.51.100.0/24 None None
100 allow 0.0.0.0/0 443 443
110 allow 0.0.0.0/0 1024 65535
32767 deny 0.0.0.0/0 None Nonereplace-network-acl-association prints a NewAssociationId, and aws ec2 describe-network-acls --network-acl-ids "$PUBLIC_NACL" --query 'NetworkAcls[0].Associations[].SubnetId' --output text prints the public subnet's ID.
Step 7 · Find rules that are open to the world
A rule open to 0.0.0.0/0 is right for a public load balancer and wrong almost everywhere else. The usual way one appears is a "temporary" SSH rule added during an incident and never removed. Add one on purpose so you have something to find:
cat > ssh-anywhere.json <<'EOF'
[
{
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22,
"IpRanges": [{ "CidrIp": "0.0.0.0/0", "Description": "temporary debug access" }]
}
]
EOF
aws ec2 authorize-security-group-ingress --group-id "$APP_SG" --ip-permissions file://ssh-anywhere.jsonNow ask for every group in the VPC with an inbound rule open to any IPv4 or IPv6 address, and show which ports:
aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC_ID" \
--query "SecurityGroups[?IpPermissions[?IpRanges[?CidrIp=='0.0.0.0/0'] || Ipv6Ranges[?CidrIpv6=='::/0']]].{Group: GroupName, Id: GroupId, Ports: IpPermissions[?IpRanges[?CidrIp=='0.0.0.0/0'] || Ipv6Ranges[?CidrIpv6=='::/0']].[FromPort, ToPort]}"The [?...] parts are JMESPath filters that the CLI applies to the response, so the query works the same in any account. It lists tiers-demo-lb with port 443, which you expect, and tiers-demo-app with port 22, which you do not. Remove the bad rule with the same file you used to add it:
aws ec2 revoke-security-group-ingress --group-id "$APP_SG" --ip-permissions file://ssh-anywhere.jsonTo audit a whole account, loop over every Region it has enabled and print only the group names. describe-regions lists enabled Regions only, so an opt-in Region such as af-south-1 appears once you have turned it on:
for region in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
aws ec2 describe-security-groups --region "$region" \
--query "SecurityGroups[?IpPermissions[?IpRanges[?CidrIp=='0.0.0.0/0'] || Ipv6Ranges[?CidrIpv6=='::/0']]].[GroupId, GroupName]" \
--output text | sed "s/^/$region /"
doneOn a real account, expect more than your demo group: public load balancers, and probably a few groups nobody remembers. Treat each line as a question for its owner, not as something to delete on sight; removing a rule a live service depends on is an outage. The loop makes about 20 small API calls, so it is fine on a mobile connection, but if you work on prepaid data, run it from a cloud shell or CI job instead of re-running it on your laptop.
Check it worked
The first query listed two groups. Run it again after the revoke: it lists only tiers-demo-lb. In the Region loop, your current Region's line shows tiers-demo-lb and no line shows tiers-demo-app.
Step 8 · Clean up
Delete in reverse order of the references: AWS refuses to delete a security group that another group's rule still names. The database group names the app group, and the app group names the load balancer group. Check that every ID below came from this tutorial (they were set by the earlier steps in this shell) before you run anything.
echo "$DB_SG $APP_SG $LB_SG $PUBLIC_NACL $PUBLIC_SUBNET $PRIVATE_SUBNET $VPC_ID"
aws ec2 delete-security-group --group-id "$DB_SG"
aws ec2 delete-security-group --group-id "$APP_SG"
aws ec2 delete-security-group --group-id "$LB_SG"A network ACL cannot be deleted while a subnet uses it, so move the public subnet back to the default ACL first:
NEW_ASSOC=$(aws ec2 describe-network-acls --network-acl-ids "$PUBLIC_NACL" \
--query 'NetworkAcls[0].Associations[0].NetworkAclAssociationId' --output text)
aws ec2 replace-network-acl-association --association-id "$NEW_ASSOC" --network-acl-id "$DEFAULT_NACL"
aws ec2 delete-network-acl --network-acl-id "$PUBLIC_NACL"
aws ec2 delete-subnet --subnet-id "$PUBLIC_SUBNET"
aws ec2 delete-subnet --subnet-id "$PRIVATE_SUBNET"
aws ec2 delete-vpc --vpc-id "$VPC_ID"
cd ~
rm -rf ~/tiers-demo
unset VPC_ID PUBLIC_SUBNET PRIVATE_SUBNET LB_SG APP_SG DB_SG DEFAULT_NACL PUBLIC_NACL OLD_ASSOC NEW_ASSOCDeleting the VPC also removes its default security group and default ACL.
Check it worked
aws ec2 describe-vpcs --filters Name=tag:Name,Values=tiers-demo --query 'Vpcs[].VpcId' --output text prints nothing, and ls ~/tiers-demo reports that the folder does not exist.
Next steps
- Launch an instance with one of these groups and connect to it: launch an EC2 instance and connect.
- Give the database tier a real database: run a managed PostgreSQL database on Amazon RDS.
- Add a host firewall on the instance itself as a third layer: set up the UFW firewall on Ubuntu 26.04.
Related tutorials
- How to Set Up a UFW Firewall on Ubuntu 26.04You will turn on UFW with a deny-by-default policy, allow SSH before you enable it so you stay connected, open only the web ports your server needs, and learn to list, remove and limit rules.
- How to Launch an AWS EC2 Instance and Connect with SSHYou will launch an Ubuntu 26.04 LTS virtual server on AWS EC2 with the AWS CLI, allow SSH from your own address only, log in with a new key pair, and then terminate everything so it stops billing.
- Run a managed PostgreSQL database on Amazon RDSYou will have a PostgreSQL 18 database on Amazon RDS in private subnets, reachable only from your app servers over verified TLS, with its password held in Secrets Manager, a manual snapshot taken and a clean way to delete it all.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials