Entire chapters in the Cisco Networking Academy are dedicated to this topic. But basically, a router looks at the IP packet, and compares it to its routing table. The routing table says, for example, "Every packet for the destination network 10.0.5.0 /24 should be sent out of port Ethernet 2/1, next-hop address is 10.0.7.2". "/24" in this case means that the first 24 bits must match.
The routing table itself is maintained manually (static routes), or updated through a routing protocol from neighboring routers.