Apple's built-in Sleep app is free and tracks sleep duration, but there are other paid apps that have even more sleep tracking features.
To use the iPhone's sleep timer, set a time in the Clock app's timer, and set the When Timer Ends option to Stop Playing.