Gravity makes water flow to the lowest point nearby. The Ocean is the lowest point on Earth's surface, but it is not always the lowest point nearby. A river may pass few kilometers from the coast, but if there is a mountain to the coast side and lower plains on the other, it will flow to the other, obviously.