The security groups are defined when you launch each instance, usually with a "default" one. The default group permits full access to/from all instances in the same default security group and nothing more (default deny), so similar to how a firewall might typically be set up.
The security group can be set up with firewall rules that permit access to the members of the group from a location defined by source IP address/range (CIDR) and destination protocol or TCP port. As well as defining access by IP range, you can define it by a source security group: for example on your "db" group you can permit all members of the group "web" to access port XYZ.
The rules apply to every instance that is a member of the security group (rules are combined if they're members of two or more) with no individual rules per instance.
By default security groups deny access, so you don't have to worry about other customers, servers in other groups or hosts on the internet accessing your instances.