Apparently, they can either get captured into orbit or formed out of the accreting gas that went into the planet itself. In the case of the larger moons of Jupiter and Saturn, they were probably formed from material accreted by the planet into a disk. The smaller outer moons, and for instance the two moons of Mars, were captured asteroids. Our own Moon may be material ejected from the Earth and mixed with the material from a large body that collided with the Earth when it was first formed. This material later accumulated into the Moon. So, moons can have a variety of origins.