The first prerequisite is that you beat the game, becoming the first Champion of Alola. In doing this, you should have obtained Solgaleo in Sun or Lunala in Moon. You should put them in your party, then use Charizard Fly to go to Poni Island, to the Altar of the [Sunne/Moone].
At the spot where you battled Solgaleo/Lunala, there should be a fracture in the air. This is the focal point of the Ultra Wormhole. This is where it can get annoying/awkward. In Sun, with Solgaleo in your party at night, or in Moon, with Lunala in your party during the day, walk up to the Wormhole and press A. This will give you dialogue with a Y/N option to go through to the other world. If it is the wrong time of day, or if you do not have Solgaleo/Lunala in your party, the dialogue will instead say "but you can't seem to go through it right now...".
Once you get through, call Charizard Fly again, and go to Ula'Ula island, to Ula'Ula Meadow. The exit up and to the left takes you to the Lake of the [Sunne/Moone]. On the "normal" side of the Wormhole, the temple will be in ruins. But on the "alternate" side, it will be in pristine condition. Go all the way to the final platform, and your Solgaleo/Lunala will call upon Lunala/Solgaleo. Then Cosmog will appear.
It's worth noting that this is the first time in Pokemon history that a Legendary Pokemon can be said to have actually been "breeding". Manaphy into Phione comes close, but it's not the same. Sadly, you can't make Solgaleo and Lunala breed in the Daycare.