How should I avoid corrosion at this water heater connection?
With brass connected to galvanised pipe you can get some galvanic corrosion.  There is something called a dielectic union which I've never needed to use.  That may help.  You'll need to clean up the rust. That may require cutting out the rusted part or at least scraping it off.

Here's a picture that describes the dielectric union joint.