You've asked a very broad question that is difficult to answer succinctly.
The maxim "Theory follows practice" is apt here.
For centuries, musicians have simply been composing music. From time to time, academic musicians have examined the way that music has been written in order to elucidate principles and rules about how the most enduringly popular and influential music is created. They have written down these principles, which are effectively applied mathematics and physics related to pitches and rhythms and the overall structure of whole pieces of music.
Musicians writing music may or may not be aware of the underlying mathematics and physics, to varying degrees. But many people who learn to be musicians find it very helpful to study music theory so that they can better understand how to compose their own music, or how to better read and interpret the music that other people have written which they wish to perform.
For all students who pursue a bachelor's degree in music performance, music theory is a two-year curriculum. Students who pursue a degree in what is called "theory and composition" study the subject of music theory for much longer than that.
It is not necessary to learn the subject of music theory thoroughly in order to be a successful performing musician, or a successful songwriter. However, all musicians, whether they read music or have formal training or not, pick up some music theory along the way, whether they are very aware of it or not.
Get a college textbook on the subject of music theory, and read through its table of contents. You will see the various range of topics that are taught. If you are curious, you can read a great deal on the subject.