I’m not an astrophysicist by any means, but the basic concept is, the same gravitational forces that keep solar systems together also keep galaxies together, and galactic clusters together.
Check out the wikipedia page on intergalactic stars. Intergalactic star - Wikipedia You’ll get a starting discussion on why stars ore found in galaxies, and how they can end up ejected.