There are a lot of theories of where nationalism came from and how it developed. Here's one of my old posts that deals with this issue particularly succinctly by going through several different theories, with more details about here and here and here and probably scattered through other very old posts of mine.