Melanin is produced by melanocytes that are found within the layers of the hair follicle.
When hair is produced by the reproduction of the epithelial cells comprising the follicle, newly produced melanin accumulates in the cells and colors the hair itself as it emerges from the follicle. There are several reasons for gray hair and these vary by one's age. A big one is heredity. If your genes code for gray hair at a later time, you will become gray as you get older. This may also be done by less blood supply to the follicles.