The two can be used interchangeably in a number of contexts, but I would say عالم is the more general term whereas دنيا is more restricted in use. In religious contexts دنيا refers to this world (as opposed to the next world, that is, the hereafter), whereas عالم can be the world or universe in general.